Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / Analysis / InstructionSimplify.cpp
blob843b3e97c0767501c653bb142f0aabc776b8c5df
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions. This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/CmpInstAnalysis.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/LoopAnalysisManager.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/VectorUtils.h"
31 #include "llvm/IR/ConstantRange.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/GetElementPtrTypeIterator.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/KnownBits.h"
42 #include <algorithm>
43 using namespace llvm;
44 using namespace llvm::PatternMatch;
46 #define DEBUG_TYPE "instsimplify"
48 enum { RecursionLimit = 3 };
50 STATISTIC(NumExpand, "Number of expansions");
51 STATISTIC(NumReassoc, "Number of reassociations");
53 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
54 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
55 unsigned);
56 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
57 const SimplifyQuery &, unsigned);
58 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
59 unsigned);
60 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
61 const SimplifyQuery &Q, unsigned MaxRecurse);
62 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
63 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
64 static Value *SimplifyCastInst(unsigned, Value *, Type *,
65 const SimplifyQuery &, unsigned);
66 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
67 unsigned);
69 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
70 Value *FalseVal) {
71 BinaryOperator::BinaryOps BinOpCode;
72 if (auto *BO = dyn_cast<BinaryOperator>(Cond))
73 BinOpCode = BO->getOpcode();
74 else
75 return nullptr;
77 CmpInst::Predicate ExpectedPred, Pred1, Pred2;
78 if (BinOpCode == BinaryOperator::Or) {
79 ExpectedPred = ICmpInst::ICMP_NE;
80 } else if (BinOpCode == BinaryOperator::And) {
81 ExpectedPred = ICmpInst::ICMP_EQ;
82 } else
83 return nullptr;
85 // %A = icmp eq %TV, %FV
86 // %B = icmp eq %X, %Y (and one of these is a select operand)
87 // %C = and %A, %B
88 // %D = select %C, %TV, %FV
89 // -->
90 // %FV
92 // %A = icmp ne %TV, %FV
93 // %B = icmp ne %X, %Y (and one of these is a select operand)
94 // %C = or %A, %B
95 // %D = select %C, %TV, %FV
96 // -->
97 // %TV
98 Value *X, *Y;
99 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
100 m_Specific(FalseVal)),
101 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
102 Pred1 != Pred2 || Pred1 != ExpectedPred)
103 return nullptr;
105 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
106 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
108 return nullptr;
111 /// For a boolean type or a vector of boolean type, return false or a vector
112 /// with every element false.
113 static Constant *getFalse(Type *Ty) {
114 return ConstantInt::getFalse(Ty);
117 /// For a boolean type or a vector of boolean type, return true or a vector
118 /// with every element true.
119 static Constant *getTrue(Type *Ty) {
120 return ConstantInt::getTrue(Ty);
123 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
124 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
125 Value *RHS) {
126 CmpInst *Cmp = dyn_cast<CmpInst>(V);
127 if (!Cmp)
128 return false;
129 CmpInst::Predicate CPred = Cmp->getPredicate();
130 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
131 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
132 return true;
133 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
134 CRHS == LHS;
137 /// Does the given value dominate the specified phi node?
138 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
139 Instruction *I = dyn_cast<Instruction>(V);
140 if (!I)
141 // Arguments and constants dominate all instructions.
142 return true;
144 // If we are processing instructions (and/or basic blocks) that have not been
145 // fully added to a function, the parent nodes may still be null. Simply
146 // return the conservative answer in these cases.
147 if (!I->getParent() || !P->getParent() || !I->getFunction())
148 return false;
150 // If we have a DominatorTree then do a precise test.
151 if (DT)
152 return DT->dominates(I, P);
154 // Otherwise, if the instruction is in the entry block and is not an invoke,
155 // then it obviously dominates all phi nodes.
156 if (I->getParent() == &I->getFunction()->getEntryBlock() &&
157 !isa<InvokeInst>(I))
158 return true;
160 return false;
163 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
164 /// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
165 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
166 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
167 /// Returns the simplified value, or null if no simplification was performed.
168 static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
169 Instruction::BinaryOps OpcodeToExpand,
170 const SimplifyQuery &Q, unsigned MaxRecurse) {
171 // Recursion is always used, so bail out at once if we already hit the limit.
172 if (!MaxRecurse--)
173 return nullptr;
175 // Check whether the expression has the form "(A op' B) op C".
176 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
177 if (Op0->getOpcode() == OpcodeToExpand) {
178 // It does! Try turning it into "(A op C) op' (B op C)".
179 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
180 // Do "A op C" and "B op C" both simplify?
181 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
182 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
183 // They do! Return "L op' R" if it simplifies or is already available.
184 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
185 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
186 && L == B && R == A)) {
187 ++NumExpand;
188 return LHS;
190 // Otherwise return "L op' R" if it simplifies.
191 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
192 ++NumExpand;
193 return V;
198 // Check whether the expression has the form "A op (B op' C)".
199 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
200 if (Op1->getOpcode() == OpcodeToExpand) {
201 // It does! Try turning it into "(A op B) op' (A op C)".
202 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
203 // Do "A op B" and "A op C" both simplify?
204 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
205 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
206 // They do! Return "L op' R" if it simplifies or is already available.
207 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
208 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
209 && L == C && R == B)) {
210 ++NumExpand;
211 return RHS;
213 // Otherwise return "L op' R" if it simplifies.
214 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
215 ++NumExpand;
216 return V;
221 return nullptr;
224 /// Generic simplifications for associative binary operations.
225 /// Returns the simpler value, or null if none was found.
226 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
227 Value *LHS, Value *RHS,
228 const SimplifyQuery &Q,
229 unsigned MaxRecurse) {
230 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
232 // Recursion is always used, so bail out at once if we already hit the limit.
233 if (!MaxRecurse--)
234 return nullptr;
236 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
237 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
239 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
240 if (Op0 && Op0->getOpcode() == Opcode) {
241 Value *A = Op0->getOperand(0);
242 Value *B = Op0->getOperand(1);
243 Value *C = RHS;
245 // Does "B op C" simplify?
246 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
247 // It does! Return "A op V" if it simplifies or is already available.
248 // If V equals B then "A op V" is just the LHS.
249 if (V == B) return LHS;
250 // Otherwise return "A op V" if it simplifies.
251 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
252 ++NumReassoc;
253 return W;
258 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
259 if (Op1 && Op1->getOpcode() == Opcode) {
260 Value *A = LHS;
261 Value *B = Op1->getOperand(0);
262 Value *C = Op1->getOperand(1);
264 // Does "A op B" simplify?
265 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
266 // It does! Return "V op C" if it simplifies or is already available.
267 // If V equals B then "V op C" is just the RHS.
268 if (V == B) return RHS;
269 // Otherwise return "V op C" if it simplifies.
270 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
271 ++NumReassoc;
272 return W;
277 // The remaining transforms require commutativity as well as associativity.
278 if (!Instruction::isCommutative(Opcode))
279 return nullptr;
281 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
282 if (Op0 && Op0->getOpcode() == Opcode) {
283 Value *A = Op0->getOperand(0);
284 Value *B = Op0->getOperand(1);
285 Value *C = RHS;
287 // Does "C op A" simplify?
288 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
289 // It does! Return "V op B" if it simplifies or is already available.
290 // If V equals A then "V op B" is just the LHS.
291 if (V == A) return LHS;
292 // Otherwise return "V op B" if it simplifies.
293 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
294 ++NumReassoc;
295 return W;
300 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
301 if (Op1 && Op1->getOpcode() == Opcode) {
302 Value *A = LHS;
303 Value *B = Op1->getOperand(0);
304 Value *C = Op1->getOperand(1);
306 // Does "C op A" simplify?
307 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
308 // It does! Return "B op V" if it simplifies or is already available.
309 // If V equals C then "B op V" is just the RHS.
310 if (V == C) return RHS;
311 // Otherwise return "B op V" if it simplifies.
312 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
313 ++NumReassoc;
314 return W;
319 return nullptr;
322 /// In the case of a binary operation with a select instruction as an operand,
323 /// try to simplify the binop by seeing whether evaluating it on both branches
324 /// of the select results in the same value. Returns the common value if so,
325 /// otherwise returns null.
326 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
327 Value *RHS, const SimplifyQuery &Q,
328 unsigned MaxRecurse) {
329 // Recursion is always used, so bail out at once if we already hit the limit.
330 if (!MaxRecurse--)
331 return nullptr;
333 SelectInst *SI;
334 if (isa<SelectInst>(LHS)) {
335 SI = cast<SelectInst>(LHS);
336 } else {
337 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
338 SI = cast<SelectInst>(RHS);
341 // Evaluate the BinOp on the true and false branches of the select.
342 Value *TV;
343 Value *FV;
344 if (SI == LHS) {
345 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
346 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
347 } else {
348 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
349 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
352 // If they simplified to the same value, then return the common value.
353 // If they both failed to simplify then return null.
354 if (TV == FV)
355 return TV;
357 // If one branch simplified to undef, return the other one.
358 if (TV && isa<UndefValue>(TV))
359 return FV;
360 if (FV && isa<UndefValue>(FV))
361 return TV;
363 // If applying the operation did not change the true and false select values,
364 // then the result of the binop is the select itself.
365 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
366 return SI;
368 // If one branch simplified and the other did not, and the simplified
369 // value is equal to the unsimplified one, return the simplified value.
370 // For example, select (cond, X, X & Z) & Z -> X & Z.
371 if ((FV && !TV) || (TV && !FV)) {
372 // Check that the simplified value has the form "X op Y" where "op" is the
373 // same as the original operation.
374 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
375 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
376 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
377 // We already know that "op" is the same as for the simplified value. See
378 // if the operands match too. If so, return the simplified value.
379 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
380 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
381 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
382 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
383 Simplified->getOperand(1) == UnsimplifiedRHS)
384 return Simplified;
385 if (Simplified->isCommutative() &&
386 Simplified->getOperand(1) == UnsimplifiedLHS &&
387 Simplified->getOperand(0) == UnsimplifiedRHS)
388 return Simplified;
392 return nullptr;
395 /// In the case of a comparison with a select instruction, try to simplify the
396 /// comparison by seeing whether both branches of the select result in the same
397 /// value. Returns the common value if so, otherwise returns null.
398 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
399 Value *RHS, const SimplifyQuery &Q,
400 unsigned MaxRecurse) {
401 // Recursion is always used, so bail out at once if we already hit the limit.
402 if (!MaxRecurse--)
403 return nullptr;
405 // Make sure the select is on the LHS.
406 if (!isa<SelectInst>(LHS)) {
407 std::swap(LHS, RHS);
408 Pred = CmpInst::getSwappedPredicate(Pred);
410 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
411 SelectInst *SI = cast<SelectInst>(LHS);
412 Value *Cond = SI->getCondition();
413 Value *TV = SI->getTrueValue();
414 Value *FV = SI->getFalseValue();
416 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
417 // Does "cmp TV, RHS" simplify?
418 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
419 if (TCmp == Cond) {
420 // It not only simplified, it simplified to the select condition. Replace
421 // it with 'true'.
422 TCmp = getTrue(Cond->getType());
423 } else if (!TCmp) {
424 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
425 // condition then we can replace it with 'true'. Otherwise give up.
426 if (!isSameCompare(Cond, Pred, TV, RHS))
427 return nullptr;
428 TCmp = getTrue(Cond->getType());
431 // Does "cmp FV, RHS" simplify?
432 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
433 if (FCmp == Cond) {
434 // It not only simplified, it simplified to the select condition. Replace
435 // it with 'false'.
436 FCmp = getFalse(Cond->getType());
437 } else if (!FCmp) {
438 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
439 // condition then we can replace it with 'false'. Otherwise give up.
440 if (!isSameCompare(Cond, Pred, FV, RHS))
441 return nullptr;
442 FCmp = getFalse(Cond->getType());
445 // If both sides simplified to the same value, then use it as the result of
446 // the original comparison.
447 if (TCmp == FCmp)
448 return TCmp;
450 // The remaining cases only make sense if the select condition has the same
451 // type as the result of the comparison, so bail out if this is not so.
452 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
453 return nullptr;
454 // If the false value simplified to false, then the result of the compare
455 // is equal to "Cond && TCmp". This also catches the case when the false
456 // value simplified to false and the true value to true, returning "Cond".
457 if (match(FCmp, m_Zero()))
458 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
459 return V;
460 // If the true value simplified to true, then the result of the compare
461 // is equal to "Cond || FCmp".
462 if (match(TCmp, m_One()))
463 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
464 return V;
465 // Finally, if the false value simplified to true and the true value to
466 // false, then the result of the compare is equal to "!Cond".
467 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
468 if (Value *V =
469 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
470 Q, MaxRecurse))
471 return V;
473 return nullptr;
476 /// In the case of a binary operation with an operand that is a PHI instruction,
477 /// try to simplify the binop by seeing whether evaluating it on the incoming
478 /// phi values yields the same result for every value. If so returns the common
479 /// value, otherwise returns null.
480 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
481 Value *RHS, const SimplifyQuery &Q,
482 unsigned MaxRecurse) {
483 // Recursion is always used, so bail out at once if we already hit the limit.
484 if (!MaxRecurse--)
485 return nullptr;
487 PHINode *PI;
488 if (isa<PHINode>(LHS)) {
489 PI = cast<PHINode>(LHS);
490 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
491 if (!valueDominatesPHI(RHS, PI, Q.DT))
492 return nullptr;
493 } else {
494 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
495 PI = cast<PHINode>(RHS);
496 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
497 if (!valueDominatesPHI(LHS, PI, Q.DT))
498 return nullptr;
501 // Evaluate the BinOp on the incoming phi values.
502 Value *CommonValue = nullptr;
503 for (Value *Incoming : PI->incoming_values()) {
504 // If the incoming value is the phi node itself, it can safely be skipped.
505 if (Incoming == PI) continue;
506 Value *V = PI == LHS ?
507 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
508 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
509 // If the operation failed to simplify, or simplified to a different value
510 // to previously, then give up.
511 if (!V || (CommonValue && V != CommonValue))
512 return nullptr;
513 CommonValue = V;
516 return CommonValue;
519 /// In the case of a comparison with a PHI instruction, try to simplify the
520 /// comparison by seeing whether comparing with all of the incoming phi values
521 /// yields the same result every time. If so returns the common result,
522 /// otherwise returns null.
523 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
524 const SimplifyQuery &Q, unsigned MaxRecurse) {
525 // Recursion is always used, so bail out at once if we already hit the limit.
526 if (!MaxRecurse--)
527 return nullptr;
529 // Make sure the phi is on the LHS.
530 if (!isa<PHINode>(LHS)) {
531 std::swap(LHS, RHS);
532 Pred = CmpInst::getSwappedPredicate(Pred);
534 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
535 PHINode *PI = cast<PHINode>(LHS);
537 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
538 if (!valueDominatesPHI(RHS, PI, Q.DT))
539 return nullptr;
541 // Evaluate the BinOp on the incoming phi values.
542 Value *CommonValue = nullptr;
543 for (Value *Incoming : PI->incoming_values()) {
544 // If the incoming value is the phi node itself, it can safely be skipped.
545 if (Incoming == PI) continue;
546 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
547 // If the operation failed to simplify, or simplified to a different value
548 // to previously, then give up.
549 if (!V || (CommonValue && V != CommonValue))
550 return nullptr;
551 CommonValue = V;
554 return CommonValue;
557 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
558 Value *&Op0, Value *&Op1,
559 const SimplifyQuery &Q) {
560 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
561 if (auto *CRHS = dyn_cast<Constant>(Op1))
562 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
564 // Canonicalize the constant to the RHS if this is a commutative operation.
565 if (Instruction::isCommutative(Opcode))
566 std::swap(Op0, Op1);
568 return nullptr;
571 /// Given operands for an Add, see if we can fold the result.
572 /// If not, this returns null.
573 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
574 const SimplifyQuery &Q, unsigned MaxRecurse) {
575 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
576 return C;
578 // X + undef -> undef
579 if (match(Op1, m_Undef()))
580 return Op1;
582 // X + 0 -> X
583 if (match(Op1, m_Zero()))
584 return Op0;
586 // If two operands are negative, return 0.
587 if (isKnownNegation(Op0, Op1))
588 return Constant::getNullValue(Op0->getType());
590 // X + (Y - X) -> Y
591 // (Y - X) + X -> Y
592 // Eg: X + -X -> 0
593 Value *Y = nullptr;
594 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
595 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
596 return Y;
598 // X + ~X -> -1 since ~X = -X-1
599 Type *Ty = Op0->getType();
600 if (match(Op0, m_Not(m_Specific(Op1))) ||
601 match(Op1, m_Not(m_Specific(Op0))))
602 return Constant::getAllOnesValue(Ty);
604 // add nsw/nuw (xor Y, signmask), signmask --> Y
605 // The no-wrapping add guarantees that the top bit will be set by the add.
606 // Therefore, the xor must be clearing the already set sign bit of Y.
607 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
608 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
609 return Y;
611 // add nuw %x, -1 -> -1, because %x can only be 0.
612 if (IsNUW && match(Op1, m_AllOnes()))
613 return Op1; // Which is -1.
615 /// i1 add -> xor.
616 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
617 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
618 return V;
620 // Try some generic simplifications for associative operations.
621 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
622 MaxRecurse))
623 return V;
625 // Threading Add over selects and phi nodes is pointless, so don't bother.
626 // Threading over the select in "A + select(cond, B, C)" means evaluating
627 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
628 // only if B and C are equal. If B and C are equal then (since we assume
629 // that operands have already been simplified) "select(cond, B, C)" should
630 // have been simplified to the common value of B and C already. Analysing
631 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
632 // for threading over phi nodes.
634 return nullptr;
637 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
638 const SimplifyQuery &Query) {
639 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
642 /// Compute the base pointer and cumulative constant offsets for V.
644 /// This strips all constant offsets off of V, leaving it the base pointer, and
645 /// accumulates the total constant offset applied in the returned constant. It
646 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
647 /// no constant offsets applied.
649 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
650 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
651 /// folding.
652 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
653 bool AllowNonInbounds = false) {
654 assert(V->getType()->isPtrOrPtrVectorTy());
656 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
657 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
659 // Even though we don't look through PHI nodes, we could be called on an
660 // instruction in an unreachable block, which may be on a cycle.
661 SmallPtrSet<Value *, 4> Visited;
662 Visited.insert(V);
663 do {
664 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
665 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
666 !GEP->accumulateConstantOffset(DL, Offset))
667 break;
668 V = GEP->getPointerOperand();
669 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
670 V = cast<Operator>(V)->getOperand(0);
671 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
672 if (GA->isInterposable())
673 break;
674 V = GA->getAliasee();
675 } else {
676 if (auto *Call = dyn_cast<CallBase>(V))
677 if (Value *RV = Call->getReturnedArgOperand()) {
678 V = RV;
679 continue;
681 break;
683 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
684 } while (Visited.insert(V).second);
686 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
687 if (V->getType()->isVectorTy())
688 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
689 OffsetIntPtr);
690 return OffsetIntPtr;
693 /// Compute the constant difference between two pointer values.
694 /// If the difference is not a constant, returns zero.
695 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
696 Value *RHS) {
697 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
698 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
700 // If LHS and RHS are not related via constant offsets to the same base
701 // value, there is nothing we can do here.
702 if (LHS != RHS)
703 return nullptr;
705 // Otherwise, the difference of LHS - RHS can be computed as:
706 // LHS - RHS
707 // = (LHSOffset + Base) - (RHSOffset + Base)
708 // = LHSOffset - RHSOffset
709 return ConstantExpr::getSub(LHSOffset, RHSOffset);
712 /// Given operands for a Sub, see if we can fold the result.
713 /// If not, this returns null.
714 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
715 const SimplifyQuery &Q, unsigned MaxRecurse) {
716 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
717 return C;
719 // X - undef -> undef
720 // undef - X -> undef
721 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
722 return UndefValue::get(Op0->getType());
724 // X - 0 -> X
725 if (match(Op1, m_Zero()))
726 return Op0;
728 // X - X -> 0
729 if (Op0 == Op1)
730 return Constant::getNullValue(Op0->getType());
732 // Is this a negation?
733 if (match(Op0, m_Zero())) {
734 // 0 - X -> 0 if the sub is NUW.
735 if (isNUW)
736 return Constant::getNullValue(Op0->getType());
738 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
739 if (Known.Zero.isMaxSignedValue()) {
740 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
741 // Op1 must be 0 because negating the minimum signed value is undefined.
742 if (isNSW)
743 return Constant::getNullValue(Op0->getType());
745 // 0 - X -> X if X is 0 or the minimum signed value.
746 return Op1;
750 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
751 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
752 Value *X = nullptr, *Y = nullptr, *Z = Op1;
753 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
754 // See if "V === Y - Z" simplifies.
755 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
756 // It does! Now see if "X + V" simplifies.
757 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
758 // It does, we successfully reassociated!
759 ++NumReassoc;
760 return W;
762 // See if "V === X - Z" simplifies.
763 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
764 // It does! Now see if "Y + V" simplifies.
765 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
766 // It does, we successfully reassociated!
767 ++NumReassoc;
768 return W;
772 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
773 // For example, X - (X + 1) -> -1
774 X = Op0;
775 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
776 // See if "V === X - Y" simplifies.
777 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
778 // It does! Now see if "V - Z" simplifies.
779 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
780 // It does, we successfully reassociated!
781 ++NumReassoc;
782 return W;
784 // See if "V === X - Z" simplifies.
785 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
786 // It does! Now see if "V - Y" simplifies.
787 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
788 // It does, we successfully reassociated!
789 ++NumReassoc;
790 return W;
794 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
795 // For example, X - (X - Y) -> Y.
796 Z = Op0;
797 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
798 // See if "V === Z - X" simplifies.
799 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
800 // It does! Now see if "V + Y" simplifies.
801 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
802 // It does, we successfully reassociated!
803 ++NumReassoc;
804 return W;
807 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
808 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
809 match(Op1, m_Trunc(m_Value(Y))))
810 if (X->getType() == Y->getType())
811 // See if "V === X - Y" simplifies.
812 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
813 // It does! Now see if "trunc V" simplifies.
814 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
815 Q, MaxRecurse - 1))
816 // It does, return the simplified "trunc V".
817 return W;
819 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
820 if (match(Op0, m_PtrToInt(m_Value(X))) &&
821 match(Op1, m_PtrToInt(m_Value(Y))))
822 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
823 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
825 // i1 sub -> xor.
826 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
827 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
828 return V;
830 // Threading Sub over selects and phi nodes is pointless, so don't bother.
831 // Threading over the select in "A - select(cond, B, C)" means evaluating
832 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
833 // only if B and C are equal. If B and C are equal then (since we assume
834 // that operands have already been simplified) "select(cond, B, C)" should
835 // have been simplified to the common value of B and C already. Analysing
836 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
837 // for threading over phi nodes.
839 return nullptr;
842 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
843 const SimplifyQuery &Q) {
844 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
847 /// Given operands for a Mul, see if we can fold the result.
848 /// If not, this returns null.
849 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
850 unsigned MaxRecurse) {
851 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
852 return C;
854 // X * undef -> 0
855 // X * 0 -> 0
856 if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
857 return Constant::getNullValue(Op0->getType());
859 // X * 1 -> X
860 if (match(Op1, m_One()))
861 return Op0;
863 // (X / Y) * Y -> X if the division is exact.
864 Value *X = nullptr;
865 if (Q.IIQ.UseInstrInfo &&
866 (match(Op0,
867 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
868 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
869 return X;
871 // i1 mul -> and.
872 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
873 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
874 return V;
876 // Try some generic simplifications for associative operations.
877 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
878 MaxRecurse))
879 return V;
881 // Mul distributes over Add. Try some generic simplifications based on this.
882 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
883 Q, MaxRecurse))
884 return V;
886 // If the operation is with the result of a select instruction, check whether
887 // operating on either branch of the select always yields the same value.
888 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
889 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
890 MaxRecurse))
891 return V;
893 // If the operation is with the result of a phi instruction, check whether
894 // operating on all incoming values of the phi always yields the same value.
895 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
896 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
897 MaxRecurse))
898 return V;
900 return nullptr;
903 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
904 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
907 /// Check for common or similar folds of integer division or integer remainder.
908 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
909 static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
910 Type *Ty = Op0->getType();
912 // X / undef -> undef
913 // X % undef -> undef
914 if (match(Op1, m_Undef()))
915 return Op1;
917 // X / 0 -> undef
918 // X % 0 -> undef
919 // We don't need to preserve faults!
920 if (match(Op1, m_Zero()))
921 return UndefValue::get(Ty);
923 // If any element of a constant divisor vector is zero or undef, the whole op
924 // is undef.
925 auto *Op1C = dyn_cast<Constant>(Op1);
926 if (Op1C && Ty->isVectorTy()) {
927 unsigned NumElts = Ty->getVectorNumElements();
928 for (unsigned i = 0; i != NumElts; ++i) {
929 Constant *Elt = Op1C->getAggregateElement(i);
930 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
931 return UndefValue::get(Ty);
935 // undef / X -> 0
936 // undef % X -> 0
937 if (match(Op0, m_Undef()))
938 return Constant::getNullValue(Ty);
940 // 0 / X -> 0
941 // 0 % X -> 0
942 if (match(Op0, m_Zero()))
943 return Constant::getNullValue(Op0->getType());
945 // X / X -> 1
946 // X % X -> 0
947 if (Op0 == Op1)
948 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
950 // X / 1 -> X
951 // X % 1 -> 0
952 // If this is a boolean op (single-bit element type), we can't have
953 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
954 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
955 Value *X;
956 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
957 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
958 return IsDiv ? Op0 : Constant::getNullValue(Ty);
960 return nullptr;
963 /// Given a predicate and two operands, return true if the comparison is true.
964 /// This is a helper for div/rem simplification where we return some other value
965 /// when we can prove a relationship between the operands.
966 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
967 const SimplifyQuery &Q, unsigned MaxRecurse) {
968 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
969 Constant *C = dyn_cast_or_null<Constant>(V);
970 return (C && C->isAllOnesValue());
973 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
974 /// to simplify X % Y to X.
975 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
976 unsigned MaxRecurse, bool IsSigned) {
977 // Recursion is always used, so bail out at once if we already hit the limit.
978 if (!MaxRecurse--)
979 return false;
981 if (IsSigned) {
982 // |X| / |Y| --> 0
984 // We require that 1 operand is a simple constant. That could be extended to
985 // 2 variables if we computed the sign bit for each.
987 // Make sure that a constant is not the minimum signed value because taking
988 // the abs() of that is undefined.
989 Type *Ty = X->getType();
990 const APInt *C;
991 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
992 // Is the variable divisor magnitude always greater than the constant
993 // dividend magnitude?
994 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
995 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
996 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
997 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
998 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
999 return true;
1001 if (match(Y, m_APInt(C))) {
1002 // Special-case: we can't take the abs() of a minimum signed value. If
1003 // that's the divisor, then all we have to do is prove that the dividend
1004 // is also not the minimum signed value.
1005 if (C->isMinSignedValue())
1006 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1008 // Is the variable dividend magnitude always less than the constant
1009 // divisor magnitude?
1010 // |X| < |C| --> X > -abs(C) and X < abs(C)
1011 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1012 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1013 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1014 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1015 return true;
1017 return false;
1020 // IsSigned == false.
1021 // Is the dividend unsigned less than the divisor?
1022 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1025 /// These are simplifications common to SDiv and UDiv.
1026 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1027 const SimplifyQuery &Q, unsigned MaxRecurse) {
1028 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1029 return C;
1031 if (Value *V = simplifyDivRem(Op0, Op1, true))
1032 return V;
1034 bool IsSigned = Opcode == Instruction::SDiv;
1036 // (X * Y) / Y -> X if the multiplication does not overflow.
1037 Value *X;
1038 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1039 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1040 // If the Mul does not overflow, then we are good to go.
1041 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1042 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)))
1043 return X;
1044 // If X has the form X = A / Y, then X * Y cannot overflow.
1045 if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1046 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1047 return X;
1050 // (X rem Y) / Y -> 0
1051 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1052 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1053 return Constant::getNullValue(Op0->getType());
1055 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1056 ConstantInt *C1, *C2;
1057 if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1058 match(Op1, m_ConstantInt(C2))) {
1059 bool Overflow;
1060 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1061 if (Overflow)
1062 return Constant::getNullValue(Op0->getType());
1065 // If the operation is with the result of a select instruction, check whether
1066 // operating on either branch of the select always yields the same value.
1067 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1068 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1069 return V;
1071 // If the operation is with the result of a phi instruction, check whether
1072 // operating on all incoming values of the phi always yields the same value.
1073 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1074 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1075 return V;
1077 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1078 return Constant::getNullValue(Op0->getType());
1080 return nullptr;
1083 /// These are simplifications common to SRem and URem.
1084 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1085 const SimplifyQuery &Q, unsigned MaxRecurse) {
1086 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1087 return C;
1089 if (Value *V = simplifyDivRem(Op0, Op1, false))
1090 return V;
1092 // (X % Y) % Y -> X % Y
1093 if ((Opcode == Instruction::SRem &&
1094 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1095 (Opcode == Instruction::URem &&
1096 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1097 return Op0;
1099 // (X << Y) % X -> 0
1100 if (Q.IIQ.UseInstrInfo &&
1101 ((Opcode == Instruction::SRem &&
1102 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1103 (Opcode == Instruction::URem &&
1104 match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1105 return Constant::getNullValue(Op0->getType());
1107 // If the operation is with the result of a select instruction, check whether
1108 // operating on either branch of the select always yields the same value.
1109 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1110 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1111 return V;
1113 // If the operation is with the result of a phi instruction, check whether
1114 // operating on all incoming values of the phi always yields the same value.
1115 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1116 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1117 return V;
1119 // If X / Y == 0, then X % Y == X.
1120 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1121 return Op0;
1123 return nullptr;
1126 /// Given operands for an SDiv, see if we can fold the result.
1127 /// If not, this returns null.
1128 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1129 unsigned MaxRecurse) {
1130 // If two operands are negated and no signed overflow, return -1.
1131 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1132 return Constant::getAllOnesValue(Op0->getType());
1134 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1137 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1138 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1141 /// Given operands for a UDiv, see if we can fold the result.
1142 /// If not, this returns null.
1143 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1144 unsigned MaxRecurse) {
1145 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1148 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1149 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1152 /// Given operands for an SRem, see if we can fold the result.
1153 /// If not, this returns null.
1154 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1155 unsigned MaxRecurse) {
1156 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1157 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1158 Value *X;
1159 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1160 return ConstantInt::getNullValue(Op0->getType());
1162 // If the two operands are negated, return 0.
1163 if (isKnownNegation(Op0, Op1))
1164 return ConstantInt::getNullValue(Op0->getType());
1166 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1169 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1170 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1173 /// Given operands for a URem, see if we can fold the result.
1174 /// If not, this returns null.
1175 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1176 unsigned MaxRecurse) {
1177 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1180 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1181 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1184 /// Returns true if a shift by \c Amount always yields undef.
1185 static bool isUndefShift(Value *Amount) {
1186 Constant *C = dyn_cast<Constant>(Amount);
1187 if (!C)
1188 return false;
1190 // X shift by undef -> undef because it may shift by the bitwidth.
1191 if (isa<UndefValue>(C))
1192 return true;
1194 // Shifting by the bitwidth or more is undefined.
1195 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1196 if (CI->getValue().getLimitedValue() >=
1197 CI->getType()->getScalarSizeInBits())
1198 return true;
1200 // If all lanes of a vector shift are undefined the whole shift is.
1201 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1202 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1203 if (!isUndefShift(C->getAggregateElement(I)))
1204 return false;
1205 return true;
1208 return false;
1211 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1212 /// If not, this returns null.
1213 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1214 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
1215 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1216 return C;
1218 // 0 shift by X -> 0
1219 if (match(Op0, m_Zero()))
1220 return Constant::getNullValue(Op0->getType());
1222 // X shift by 0 -> X
1223 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1224 // would be poison.
1225 Value *X;
1226 if (match(Op1, m_Zero()) ||
1227 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1228 return Op0;
1230 // Fold undefined shifts.
1231 if (isUndefShift(Op1))
1232 return UndefValue::get(Op0->getType());
1234 // If the operation is with the result of a select instruction, check whether
1235 // operating on either branch of the select always yields the same value.
1236 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1237 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1238 return V;
1240 // If the operation is with the result of a phi instruction, check whether
1241 // operating on all incoming values of the phi always yields the same value.
1242 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1243 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1244 return V;
1246 // If any bits in the shift amount make that value greater than or equal to
1247 // the number of bits in the type, the shift is undefined.
1248 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1249 if (Known.One.getLimitedValue() >= Known.getBitWidth())
1250 return UndefValue::get(Op0->getType());
1252 // If all valid bits in the shift amount are known zero, the first operand is
1253 // unchanged.
1254 unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
1255 if (Known.countMinTrailingZeros() >= NumValidShiftBits)
1256 return Op0;
1258 return nullptr;
1261 /// Given operands for an Shl, LShr or AShr, see if we can
1262 /// fold the result. If not, this returns null.
1263 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1264 Value *Op1, bool isExact, const SimplifyQuery &Q,
1265 unsigned MaxRecurse) {
1266 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1267 return V;
1269 // X >> X -> 0
1270 if (Op0 == Op1)
1271 return Constant::getNullValue(Op0->getType());
1273 // undef >> X -> 0
1274 // undef >> X -> undef (if it's exact)
1275 if (match(Op0, m_Undef()))
1276 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1278 // The low bit cannot be shifted out of an exact shift if it is set.
1279 if (isExact) {
1280 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1281 if (Op0Known.One[0])
1282 return Op0;
1285 return nullptr;
1288 /// Given operands for an Shl, see if we can fold the result.
1289 /// If not, this returns null.
1290 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1291 const SimplifyQuery &Q, unsigned MaxRecurse) {
1292 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1293 return V;
1295 // undef << X -> 0
1296 // undef << X -> undef if (if it's NSW/NUW)
1297 if (match(Op0, m_Undef()))
1298 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1300 // (X >> A) << A -> X
1301 Value *X;
1302 if (Q.IIQ.UseInstrInfo &&
1303 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1304 return X;
1306 // shl nuw i8 C, %x -> C iff C has sign bit set.
1307 if (isNUW && match(Op0, m_Negative()))
1308 return Op0;
1309 // NOTE: could use computeKnownBits() / LazyValueInfo,
1310 // but the cost-benefit analysis suggests it isn't worth it.
1312 return nullptr;
1315 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1316 const SimplifyQuery &Q) {
1317 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1320 /// Given operands for an LShr, see if we can fold the result.
1321 /// If not, this returns null.
1322 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1323 const SimplifyQuery &Q, unsigned MaxRecurse) {
1324 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1325 MaxRecurse))
1326 return V;
1328 // (X << A) >> A -> X
1329 Value *X;
1330 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1331 return X;
1333 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1334 // We can return X as we do in the above case since OR alters no bits in X.
1335 // SimplifyDemandedBits in InstCombine can do more general optimization for
1336 // bit manipulation. This pattern aims to provide opportunities for other
1337 // optimizers by supporting a simple but common case in InstSimplify.
1338 Value *Y;
1339 const APInt *ShRAmt, *ShLAmt;
1340 if (match(Op1, m_APInt(ShRAmt)) &&
1341 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1342 *ShRAmt == *ShLAmt) {
1343 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1344 const unsigned Width = Op0->getType()->getScalarSizeInBits();
1345 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1346 if (ShRAmt->uge(EffWidthY))
1347 return X;
1350 return nullptr;
1353 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1354 const SimplifyQuery &Q) {
1355 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1358 /// Given operands for an AShr, see if we can fold the result.
1359 /// If not, this returns null.
1360 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1361 const SimplifyQuery &Q, unsigned MaxRecurse) {
1362 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1363 MaxRecurse))
1364 return V;
1366 // all ones >>a X -> -1
1367 // Do not return Op0 because it may contain undef elements if it's a vector.
1368 if (match(Op0, m_AllOnes()))
1369 return Constant::getAllOnesValue(Op0->getType());
1371 // (X << A) >> A -> X
1372 Value *X;
1373 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1374 return X;
1376 // Arithmetic shifting an all-sign-bit value is a no-op.
1377 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1378 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1379 return Op0;
1381 return nullptr;
1384 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1385 const SimplifyQuery &Q) {
1386 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1389 /// Commuted variants are assumed to be handled by calling this function again
1390 /// with the parameters swapped.
1391 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1392 ICmpInst *UnsignedICmp, bool IsAnd) {
1393 Value *X, *Y;
1395 ICmpInst::Predicate EqPred;
1396 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1397 !ICmpInst::isEquality(EqPred))
1398 return nullptr;
1400 ICmpInst::Predicate UnsignedPred;
1401 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1402 ICmpInst::isUnsigned(UnsignedPred))
1404 else if (match(UnsignedICmp,
1405 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1406 ICmpInst::isUnsigned(UnsignedPred))
1407 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1408 else
1409 return nullptr;
1411 // X < Y && Y != 0 --> X < Y
1412 // X < Y || Y != 0 --> Y != 0
1413 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1414 return IsAnd ? UnsignedICmp : ZeroICmp;
1416 // X >= Y || Y != 0 --> true
1417 // X >= Y || Y == 0 --> X >= Y
1418 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1419 if (EqPred == ICmpInst::ICMP_NE)
1420 return getTrue(UnsignedICmp->getType());
1421 return UnsignedICmp;
1424 // X < Y && Y == 0 --> false
1425 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1426 IsAnd)
1427 return getFalse(UnsignedICmp->getType());
1429 return nullptr;
1432 /// Commuted variants are assumed to be handled by calling this function again
1433 /// with the parameters swapped.
1434 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1435 ICmpInst::Predicate Pred0, Pred1;
1436 Value *A ,*B;
1437 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1438 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1439 return nullptr;
1441 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1442 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1443 // can eliminate Op1 from this 'and'.
1444 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1445 return Op0;
1447 // Check for any combination of predicates that are guaranteed to be disjoint.
1448 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1449 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1450 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1451 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1452 return getFalse(Op0->getType());
1454 return nullptr;
1457 /// Commuted variants are assumed to be handled by calling this function again
1458 /// with the parameters swapped.
1459 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1460 ICmpInst::Predicate Pred0, Pred1;
1461 Value *A ,*B;
1462 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1463 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1464 return nullptr;
1466 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1467 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1468 // can eliminate Op0 from this 'or'.
1469 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1470 return Op1;
1472 // Check for any combination of predicates that cover the entire range of
1473 // possibilities.
1474 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1475 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1476 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1477 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1478 return getTrue(Op0->getType());
1480 return nullptr;
1483 /// Test if a pair of compares with a shared operand and 2 constants has an
1484 /// empty set intersection, full set union, or if one compare is a superset of
1485 /// the other.
1486 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1487 bool IsAnd) {
1488 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1489 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1490 return nullptr;
1492 const APInt *C0, *C1;
1493 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1494 !match(Cmp1->getOperand(1), m_APInt(C1)))
1495 return nullptr;
1497 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1498 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1500 // For and-of-compares, check if the intersection is empty:
1501 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1502 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1503 return getFalse(Cmp0->getType());
1505 // For or-of-compares, check if the union is full:
1506 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1507 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1508 return getTrue(Cmp0->getType());
1510 // Is one range a superset of the other?
1511 // If this is and-of-compares, take the smaller set:
1512 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1513 // If this is or-of-compares, take the larger set:
1514 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1515 if (Range0.contains(Range1))
1516 return IsAnd ? Cmp1 : Cmp0;
1517 if (Range1.contains(Range0))
1518 return IsAnd ? Cmp0 : Cmp1;
1520 return nullptr;
1523 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1524 bool IsAnd) {
1525 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1526 if (!match(Cmp0->getOperand(1), m_Zero()) ||
1527 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1528 return nullptr;
1530 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1531 return nullptr;
1533 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1534 Value *X = Cmp0->getOperand(0);
1535 Value *Y = Cmp1->getOperand(0);
1537 // If one of the compares is a masked version of a (not) null check, then
1538 // that compare implies the other, so we eliminate the other. Optionally, look
1539 // through a pointer-to-int cast to match a null check of a pointer type.
1541 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1542 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1543 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1544 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1545 if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1546 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1547 return Cmp1;
1549 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1550 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1551 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1552 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1553 if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1554 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1555 return Cmp0;
1557 return nullptr;
1560 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1561 const InstrInfoQuery &IIQ) {
1562 // (icmp (add V, C0), C1) & (icmp V, C0)
1563 ICmpInst::Predicate Pred0, Pred1;
1564 const APInt *C0, *C1;
1565 Value *V;
1566 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1567 return nullptr;
1569 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1570 return nullptr;
1572 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1573 if (AddInst->getOperand(1) != Op1->getOperand(1))
1574 return nullptr;
1576 Type *ITy = Op0->getType();
1577 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1578 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1580 const APInt Delta = *C1 - *C0;
1581 if (C0->isStrictlyPositive()) {
1582 if (Delta == 2) {
1583 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1584 return getFalse(ITy);
1585 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1586 return getFalse(ITy);
1588 if (Delta == 1) {
1589 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1590 return getFalse(ITy);
1591 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1592 return getFalse(ITy);
1595 if (C0->getBoolValue() && isNUW) {
1596 if (Delta == 2)
1597 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1598 return getFalse(ITy);
1599 if (Delta == 1)
1600 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1601 return getFalse(ITy);
1604 return nullptr;
1607 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1608 const InstrInfoQuery &IIQ) {
1609 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1610 return X;
1611 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
1612 return X;
1614 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1615 return X;
1616 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1617 return X;
1619 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1620 return X;
1622 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1623 return X;
1625 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, IIQ))
1626 return X;
1627 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, IIQ))
1628 return X;
1630 return nullptr;
1633 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1634 const InstrInfoQuery &IIQ) {
1635 // (icmp (add V, C0), C1) | (icmp V, C0)
1636 ICmpInst::Predicate Pred0, Pred1;
1637 const APInt *C0, *C1;
1638 Value *V;
1639 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1640 return nullptr;
1642 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1643 return nullptr;
1645 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1646 if (AddInst->getOperand(1) != Op1->getOperand(1))
1647 return nullptr;
1649 Type *ITy = Op0->getType();
1650 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1651 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1653 const APInt Delta = *C1 - *C0;
1654 if (C0->isStrictlyPositive()) {
1655 if (Delta == 2) {
1656 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1657 return getTrue(ITy);
1658 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1659 return getTrue(ITy);
1661 if (Delta == 1) {
1662 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1663 return getTrue(ITy);
1664 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1665 return getTrue(ITy);
1668 if (C0->getBoolValue() && isNUW) {
1669 if (Delta == 2)
1670 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1671 return getTrue(ITy);
1672 if (Delta == 1)
1673 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1674 return getTrue(ITy);
1677 return nullptr;
1680 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1681 const InstrInfoQuery &IIQ) {
1682 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1683 return X;
1684 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
1685 return X;
1687 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1688 return X;
1689 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1690 return X;
1692 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1693 return X;
1695 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1696 return X;
1698 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, IIQ))
1699 return X;
1700 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, IIQ))
1701 return X;
1703 return nullptr;
1706 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1707 FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1708 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1709 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1710 if (LHS0->getType() != RHS0->getType())
1711 return nullptr;
1713 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1714 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1715 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1716 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1717 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1718 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1719 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1720 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1721 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1722 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1723 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1724 if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1725 (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1726 return RHS;
1728 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1729 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1730 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1731 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1732 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1733 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1734 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1735 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1736 if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1737 (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1738 return LHS;
1741 return nullptr;
1744 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
1745 Value *Op0, Value *Op1, bool IsAnd) {
1746 // Look through casts of the 'and' operands to find compares.
1747 auto *Cast0 = dyn_cast<CastInst>(Op0);
1748 auto *Cast1 = dyn_cast<CastInst>(Op1);
1749 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1750 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1751 Op0 = Cast0->getOperand(0);
1752 Op1 = Cast1->getOperand(0);
1755 Value *V = nullptr;
1756 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1757 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1758 if (ICmp0 && ICmp1)
1759 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q.IIQ)
1760 : simplifyOrOfICmps(ICmp0, ICmp1, Q.IIQ);
1762 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1763 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1764 if (FCmp0 && FCmp1)
1765 V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
1767 if (!V)
1768 return nullptr;
1769 if (!Cast0)
1770 return V;
1772 // If we looked through casts, we can only handle a constant simplification
1773 // because we are not allowed to create a cast instruction here.
1774 if (auto *C = dyn_cast<Constant>(V))
1775 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
1777 return nullptr;
1780 /// Given operands for an And, see if we can fold the result.
1781 /// If not, this returns null.
1782 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1783 unsigned MaxRecurse) {
1784 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1785 return C;
1787 // X & undef -> 0
1788 if (match(Op1, m_Undef()))
1789 return Constant::getNullValue(Op0->getType());
1791 // X & X = X
1792 if (Op0 == Op1)
1793 return Op0;
1795 // X & 0 = 0
1796 if (match(Op1, m_Zero()))
1797 return Constant::getNullValue(Op0->getType());
1799 // X & -1 = X
1800 if (match(Op1, m_AllOnes()))
1801 return Op0;
1803 // A & ~A = ~A & A = 0
1804 if (match(Op0, m_Not(m_Specific(Op1))) ||
1805 match(Op1, m_Not(m_Specific(Op0))))
1806 return Constant::getNullValue(Op0->getType());
1808 // (A | ?) & A = A
1809 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
1810 return Op1;
1812 // A & (A | ?) = A
1813 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
1814 return Op0;
1816 // A mask that only clears known zeros of a shifted value is a no-op.
1817 Value *X;
1818 const APInt *Mask;
1819 const APInt *ShAmt;
1820 if (match(Op1, m_APInt(Mask))) {
1821 // If all bits in the inverted and shifted mask are clear:
1822 // and (shl X, ShAmt), Mask --> shl X, ShAmt
1823 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1824 (~(*Mask)).lshr(*ShAmt).isNullValue())
1825 return Op0;
1827 // If all bits in the inverted and shifted mask are clear:
1828 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1829 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1830 (~(*Mask)).shl(*ShAmt).isNullValue())
1831 return Op0;
1834 // A & (-A) = A if A is a power of two or zero.
1835 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1836 match(Op1, m_Neg(m_Specific(Op0)))) {
1837 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1838 Q.DT))
1839 return Op0;
1840 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1841 Q.DT))
1842 return Op1;
1845 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
1846 return V;
1848 // Try some generic simplifications for associative operations.
1849 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1850 MaxRecurse))
1851 return V;
1853 // And distributes over Or. Try some generic simplifications based on this.
1854 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1855 Q, MaxRecurse))
1856 return V;
1858 // And distributes over Xor. Try some generic simplifications based on this.
1859 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1860 Q, MaxRecurse))
1861 return V;
1863 // If the operation is with the result of a select instruction, check whether
1864 // operating on either branch of the select always yields the same value.
1865 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1866 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1867 MaxRecurse))
1868 return V;
1870 // If the operation is with the result of a phi instruction, check whether
1871 // operating on all incoming values of the phi always yields the same value.
1872 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1873 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1874 MaxRecurse))
1875 return V;
1877 // Assuming the effective width of Y is not larger than A, i.e. all bits
1878 // from X and Y are disjoint in (X << A) | Y,
1879 // if the mask of this AND op covers all bits of X or Y, while it covers
1880 // no bits from the other, we can bypass this AND op. E.g.,
1881 // ((X << A) | Y) & Mask -> Y,
1882 // if Mask = ((1 << effective_width_of(Y)) - 1)
1883 // ((X << A) | Y) & Mask -> X << A,
1884 // if Mask = ((1 << effective_width_of(X)) - 1) << A
1885 // SimplifyDemandedBits in InstCombine can optimize the general case.
1886 // This pattern aims to help other passes for a common case.
1887 Value *Y, *XShifted;
1888 if (match(Op1, m_APInt(Mask)) &&
1889 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
1890 m_Value(XShifted)),
1891 m_Value(Y)))) {
1892 const unsigned Width = Op0->getType()->getScalarSizeInBits();
1893 const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
1894 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1895 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1896 if (EffWidthY <= ShftCnt) {
1897 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
1898 Q.DT);
1899 const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros();
1900 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
1901 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
1902 // If the mask is extracting all bits from X or Y as is, we can skip
1903 // this AND op.
1904 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
1905 return Y;
1906 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
1907 return XShifted;
1911 return nullptr;
1914 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1915 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1918 /// Given operands for an Or, see if we can fold the result.
1919 /// If not, this returns null.
1920 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1921 unsigned MaxRecurse) {
1922 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1923 return C;
1925 // X | undef -> -1
1926 // X | -1 = -1
1927 // Do not return Op1 because it may contain undef elements if it's a vector.
1928 if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
1929 return Constant::getAllOnesValue(Op0->getType());
1931 // X | X = X
1932 // X | 0 = X
1933 if (Op0 == Op1 || match(Op1, m_Zero()))
1934 return Op0;
1936 // A | ~A = ~A | A = -1
1937 if (match(Op0, m_Not(m_Specific(Op1))) ||
1938 match(Op1, m_Not(m_Specific(Op0))))
1939 return Constant::getAllOnesValue(Op0->getType());
1941 // (A & ?) | A = A
1942 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
1943 return Op1;
1945 // A | (A & ?) = A
1946 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
1947 return Op0;
1949 // ~(A & ?) | A = -1
1950 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
1951 return Constant::getAllOnesValue(Op1->getType());
1953 // A | ~(A & ?) = -1
1954 if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
1955 return Constant::getAllOnesValue(Op0->getType());
1957 Value *A, *B;
1958 // (A & ~B) | (A ^ B) -> (A ^ B)
1959 // (~B & A) | (A ^ B) -> (A ^ B)
1960 // (A & ~B) | (B ^ A) -> (B ^ A)
1961 // (~B & A) | (B ^ A) -> (B ^ A)
1962 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1963 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1964 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
1965 return Op1;
1967 // Commute the 'or' operands.
1968 // (A ^ B) | (A & ~B) -> (A ^ B)
1969 // (A ^ B) | (~B & A) -> (A ^ B)
1970 // (B ^ A) | (A & ~B) -> (B ^ A)
1971 // (B ^ A) | (~B & A) -> (B ^ A)
1972 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1973 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1974 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
1975 return Op0;
1977 // (A & B) | (~A ^ B) -> (~A ^ B)
1978 // (B & A) | (~A ^ B) -> (~A ^ B)
1979 // (A & B) | (B ^ ~A) -> (B ^ ~A)
1980 // (B & A) | (B ^ ~A) -> (B ^ ~A)
1981 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1982 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1983 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1984 return Op1;
1986 // (~A ^ B) | (A & B) -> (~A ^ B)
1987 // (~A ^ B) | (B & A) -> (~A ^ B)
1988 // (B ^ ~A) | (A & B) -> (B ^ ~A)
1989 // (B ^ ~A) | (B & A) -> (B ^ ~A)
1990 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1991 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1992 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1993 return Op0;
1995 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
1996 return V;
1998 // Try some generic simplifications for associative operations.
1999 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2000 MaxRecurse))
2001 return V;
2003 // Or distributes over And. Try some generic simplifications based on this.
2004 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
2005 MaxRecurse))
2006 return V;
2008 // If the operation is with the result of a select instruction, check whether
2009 // operating on either branch of the select always yields the same value.
2010 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
2011 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
2012 MaxRecurse))
2013 return V;
2015 // (A & C1)|(B & C2)
2016 const APInt *C1, *C2;
2017 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2018 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2019 if (*C1 == ~*C2) {
2020 // (A & C1)|(B & C2)
2021 // If we have: ((V + N) & C1) | (V & C2)
2022 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2023 // replace with V+N.
2024 Value *N;
2025 if (C2->isMask() && // C2 == 0+1+
2026 match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2027 // Add commutes, try both ways.
2028 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2029 return A;
2031 // Or commutes, try both ways.
2032 if (C1->isMask() &&
2033 match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2034 // Add commutes, try both ways.
2035 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2036 return B;
2041 // If the operation is with the result of a phi instruction, check whether
2042 // operating on all incoming values of the phi always yields the same value.
2043 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2044 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2045 return V;
2047 return nullptr;
2050 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2051 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2054 /// Given operands for a Xor, see if we can fold the result.
2055 /// If not, this returns null.
2056 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2057 unsigned MaxRecurse) {
2058 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2059 return C;
2061 // A ^ undef -> undef
2062 if (match(Op1, m_Undef()))
2063 return Op1;
2065 // A ^ 0 = A
2066 if (match(Op1, m_Zero()))
2067 return Op0;
2069 // A ^ A = 0
2070 if (Op0 == Op1)
2071 return Constant::getNullValue(Op0->getType());
2073 // A ^ ~A = ~A ^ A = -1
2074 if (match(Op0, m_Not(m_Specific(Op1))) ||
2075 match(Op1, m_Not(m_Specific(Op0))))
2076 return Constant::getAllOnesValue(Op0->getType());
2078 // Try some generic simplifications for associative operations.
2079 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2080 MaxRecurse))
2081 return V;
2083 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2084 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2085 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2086 // only if B and C are equal. If B and C are equal then (since we assume
2087 // that operands have already been simplified) "select(cond, B, C)" should
2088 // have been simplified to the common value of B and C already. Analysing
2089 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2090 // for threading over phi nodes.
2092 return nullptr;
2095 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2096 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2100 static Type *GetCompareTy(Value *Op) {
2101 return CmpInst::makeCmpResultType(Op->getType());
2104 /// Rummage around inside V looking for something equivalent to the comparison
2105 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2106 /// Helper function for analyzing max/min idioms.
2107 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2108 Value *LHS, Value *RHS) {
2109 SelectInst *SI = dyn_cast<SelectInst>(V);
2110 if (!SI)
2111 return nullptr;
2112 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2113 if (!Cmp)
2114 return nullptr;
2115 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2116 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2117 return Cmp;
2118 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2119 LHS == CmpRHS && RHS == CmpLHS)
2120 return Cmp;
2121 return nullptr;
2124 // A significant optimization not implemented here is assuming that alloca
2125 // addresses are not equal to incoming argument values. They don't *alias*,
2126 // as we say, but that doesn't mean they aren't equal, so we take a
2127 // conservative approach.
2129 // This is inspired in part by C++11 5.10p1:
2130 // "Two pointers of the same type compare equal if and only if they are both
2131 // null, both point to the same function, or both represent the same
2132 // address."
2134 // This is pretty permissive.
2136 // It's also partly due to C11 6.5.9p6:
2137 // "Two pointers compare equal if and only if both are null pointers, both are
2138 // pointers to the same object (including a pointer to an object and a
2139 // subobject at its beginning) or function, both are pointers to one past the
2140 // last element of the same array object, or one is a pointer to one past the
2141 // end of one array object and the other is a pointer to the start of a
2142 // different array object that happens to immediately follow the first array
2143 // object in the address space.)
2145 // C11's version is more restrictive, however there's no reason why an argument
2146 // couldn't be a one-past-the-end value for a stack object in the caller and be
2147 // equal to the beginning of a stack object in the callee.
2149 // If the C and C++ standards are ever made sufficiently restrictive in this
2150 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2151 // this optimization.
2152 static Constant *
2153 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2154 const DominatorTree *DT, CmpInst::Predicate Pred,
2155 AssumptionCache *AC, const Instruction *CxtI,
2156 const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) {
2157 // First, skip past any trivial no-ops.
2158 LHS = LHS->stripPointerCasts();
2159 RHS = RHS->stripPointerCasts();
2161 // A non-null pointer is not equal to a null pointer.
2162 if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2163 IIQ.UseInstrInfo) &&
2164 isa<ConstantPointerNull>(RHS) &&
2165 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2166 return ConstantInt::get(GetCompareTy(LHS),
2167 !CmpInst::isTrueWhenEqual(Pred));
2169 // We can only fold certain predicates on pointer comparisons.
2170 switch (Pred) {
2171 default:
2172 return nullptr;
2174 // Equality comaprisons are easy to fold.
2175 case CmpInst::ICMP_EQ:
2176 case CmpInst::ICMP_NE:
2177 break;
2179 // We can only handle unsigned relational comparisons because 'inbounds' on
2180 // a GEP only protects against unsigned wrapping.
2181 case CmpInst::ICMP_UGT:
2182 case CmpInst::ICMP_UGE:
2183 case CmpInst::ICMP_ULT:
2184 case CmpInst::ICMP_ULE:
2185 // However, we have to switch them to their signed variants to handle
2186 // negative indices from the base pointer.
2187 Pred = ICmpInst::getSignedPredicate(Pred);
2188 break;
2191 // Strip off any constant offsets so that we can reason about them.
2192 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2193 // here and compare base addresses like AliasAnalysis does, however there are
2194 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2195 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2196 // doesn't need to guarantee pointer inequality when it says NoAlias.
2197 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2198 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2200 // If LHS and RHS are related via constant offsets to the same base
2201 // value, we can replace it with an icmp which just compares the offsets.
2202 if (LHS == RHS)
2203 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2205 // Various optimizations for (in)equality comparisons.
2206 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2207 // Different non-empty allocations that exist at the same time have
2208 // different addresses (if the program can tell). Global variables always
2209 // exist, so they always exist during the lifetime of each other and all
2210 // allocas. Two different allocas usually have different addresses...
2212 // However, if there's an @llvm.stackrestore dynamically in between two
2213 // allocas, they may have the same address. It's tempting to reduce the
2214 // scope of the problem by only looking at *static* allocas here. That would
2215 // cover the majority of allocas while significantly reducing the likelihood
2216 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2217 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2218 // an entry block. Also, if we have a block that's not attached to a
2219 // function, we can't tell if it's "static" under the current definition.
2220 // Theoretically, this problem could be fixed by creating a new kind of
2221 // instruction kind specifically for static allocas. Such a new instruction
2222 // could be required to be at the top of the entry block, thus preventing it
2223 // from being subject to a @llvm.stackrestore. Instcombine could even
2224 // convert regular allocas into these special allocas. It'd be nifty.
2225 // However, until then, this problem remains open.
2227 // So, we'll assume that two non-empty allocas have different addresses
2228 // for now.
2230 // With all that, if the offsets are within the bounds of their allocations
2231 // (and not one-past-the-end! so we can't use inbounds!), and their
2232 // allocations aren't the same, the pointers are not equal.
2234 // Note that it's not necessary to check for LHS being a global variable
2235 // address, due to canonicalization and constant folding.
2236 if (isa<AllocaInst>(LHS) &&
2237 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2238 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2239 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2240 uint64_t LHSSize, RHSSize;
2241 ObjectSizeOpts Opts;
2242 Opts.NullIsUnknownSize =
2243 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
2244 if (LHSOffsetCI && RHSOffsetCI &&
2245 getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2246 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
2247 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2248 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2249 if (!LHSOffsetValue.isNegative() &&
2250 !RHSOffsetValue.isNegative() &&
2251 LHSOffsetValue.ult(LHSSize) &&
2252 RHSOffsetValue.ult(RHSSize)) {
2253 return ConstantInt::get(GetCompareTy(LHS),
2254 !CmpInst::isTrueWhenEqual(Pred));
2258 // Repeat the above check but this time without depending on DataLayout
2259 // or being able to compute a precise size.
2260 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2261 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2262 LHSOffset->isNullValue() &&
2263 RHSOffset->isNullValue())
2264 return ConstantInt::get(GetCompareTy(LHS),
2265 !CmpInst::isTrueWhenEqual(Pred));
2268 // Even if an non-inbounds GEP occurs along the path we can still optimize
2269 // equality comparisons concerning the result. We avoid walking the whole
2270 // chain again by starting where the last calls to
2271 // stripAndComputeConstantOffsets left off and accumulate the offsets.
2272 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2273 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2274 if (LHS == RHS)
2275 return ConstantExpr::getICmp(Pred,
2276 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2277 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2279 // If one side of the equality comparison must come from a noalias call
2280 // (meaning a system memory allocation function), and the other side must
2281 // come from a pointer that cannot overlap with dynamically-allocated
2282 // memory within the lifetime of the current function (allocas, byval
2283 // arguments, globals), then determine the comparison result here.
2284 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2285 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2286 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2288 // Is the set of underlying objects all noalias calls?
2289 auto IsNAC = [](ArrayRef<Value *> Objects) {
2290 return all_of(Objects, isNoAliasCall);
2293 // Is the set of underlying objects all things which must be disjoint from
2294 // noalias calls. For allocas, we consider only static ones (dynamic
2295 // allocas might be transformed into calls to malloc not simultaneously
2296 // live with the compared-to allocation). For globals, we exclude symbols
2297 // that might be resolve lazily to symbols in another dynamically-loaded
2298 // library (and, thus, could be malloc'ed by the implementation).
2299 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2300 return all_of(Objects, [](Value *V) {
2301 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2302 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2303 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2304 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2305 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2306 !GV->isThreadLocal();
2307 if (const Argument *A = dyn_cast<Argument>(V))
2308 return A->hasByValAttr();
2309 return false;
2313 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2314 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2315 return ConstantInt::get(GetCompareTy(LHS),
2316 !CmpInst::isTrueWhenEqual(Pred));
2318 // Fold comparisons for non-escaping pointer even if the allocation call
2319 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2320 // dynamic allocation call could be either of the operands.
2321 Value *MI = nullptr;
2322 if (isAllocLikeFn(LHS, TLI) &&
2323 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2324 MI = LHS;
2325 else if (isAllocLikeFn(RHS, TLI) &&
2326 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2327 MI = RHS;
2328 // FIXME: We should also fold the compare when the pointer escapes, but the
2329 // compare dominates the pointer escape
2330 if (MI && !PointerMayBeCaptured(MI, true, true))
2331 return ConstantInt::get(GetCompareTy(LHS),
2332 CmpInst::isFalseWhenEqual(Pred));
2335 // Otherwise, fail.
2336 return nullptr;
2339 /// Fold an icmp when its operands have i1 scalar type.
2340 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2341 Value *RHS, const SimplifyQuery &Q) {
2342 Type *ITy = GetCompareTy(LHS); // The return type.
2343 Type *OpTy = LHS->getType(); // The operand type.
2344 if (!OpTy->isIntOrIntVectorTy(1))
2345 return nullptr;
2347 // A boolean compared to true/false can be simplified in 14 out of the 20
2348 // (10 predicates * 2 constants) possible combinations. Cases not handled here
2349 // require a 'not' of the LHS, so those must be transformed in InstCombine.
2350 if (match(RHS, m_Zero())) {
2351 switch (Pred) {
2352 case CmpInst::ICMP_NE: // X != 0 -> X
2353 case CmpInst::ICMP_UGT: // X >u 0 -> X
2354 case CmpInst::ICMP_SLT: // X <s 0 -> X
2355 return LHS;
2357 case CmpInst::ICMP_ULT: // X <u 0 -> false
2358 case CmpInst::ICMP_SGT: // X >s 0 -> false
2359 return getFalse(ITy);
2361 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2362 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2363 return getTrue(ITy);
2365 default: break;
2367 } else if (match(RHS, m_One())) {
2368 switch (Pred) {
2369 case CmpInst::ICMP_EQ: // X == 1 -> X
2370 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2371 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2372 return LHS;
2374 case CmpInst::ICMP_UGT: // X >u 1 -> false
2375 case CmpInst::ICMP_SLT: // X <s -1 -> false
2376 return getFalse(ITy);
2378 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2379 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2380 return getTrue(ITy);
2382 default: break;
2386 switch (Pred) {
2387 default:
2388 break;
2389 case ICmpInst::ICMP_UGE:
2390 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2391 return getTrue(ITy);
2392 break;
2393 case ICmpInst::ICMP_SGE:
2394 /// For signed comparison, the values for an i1 are 0 and -1
2395 /// respectively. This maps into a truth table of:
2396 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2397 /// 0 | 0 | 1 (0 >= 0) | 1
2398 /// 0 | 1 | 1 (0 >= -1) | 1
2399 /// 1 | 0 | 0 (-1 >= 0) | 0
2400 /// 1 | 1 | 1 (-1 >= -1) | 1
2401 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2402 return getTrue(ITy);
2403 break;
2404 case ICmpInst::ICMP_ULE:
2405 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2406 return getTrue(ITy);
2407 break;
2410 return nullptr;
2413 /// Try hard to fold icmp with zero RHS because this is a common case.
2414 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2415 Value *RHS, const SimplifyQuery &Q) {
2416 if (!match(RHS, m_Zero()))
2417 return nullptr;
2419 Type *ITy = GetCompareTy(LHS); // The return type.
2420 switch (Pred) {
2421 default:
2422 llvm_unreachable("Unknown ICmp predicate!");
2423 case ICmpInst::ICMP_ULT:
2424 return getFalse(ITy);
2425 case ICmpInst::ICMP_UGE:
2426 return getTrue(ITy);
2427 case ICmpInst::ICMP_EQ:
2428 case ICmpInst::ICMP_ULE:
2429 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2430 return getFalse(ITy);
2431 break;
2432 case ICmpInst::ICMP_NE:
2433 case ICmpInst::ICMP_UGT:
2434 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2435 return getTrue(ITy);
2436 break;
2437 case ICmpInst::ICMP_SLT: {
2438 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2439 if (LHSKnown.isNegative())
2440 return getTrue(ITy);
2441 if (LHSKnown.isNonNegative())
2442 return getFalse(ITy);
2443 break;
2445 case ICmpInst::ICMP_SLE: {
2446 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2447 if (LHSKnown.isNegative())
2448 return getTrue(ITy);
2449 if (LHSKnown.isNonNegative() &&
2450 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2451 return getFalse(ITy);
2452 break;
2454 case ICmpInst::ICMP_SGE: {
2455 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2456 if (LHSKnown.isNegative())
2457 return getFalse(ITy);
2458 if (LHSKnown.isNonNegative())
2459 return getTrue(ITy);
2460 break;
2462 case ICmpInst::ICMP_SGT: {
2463 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2464 if (LHSKnown.isNegative())
2465 return getFalse(ITy);
2466 if (LHSKnown.isNonNegative() &&
2467 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2468 return getTrue(ITy);
2469 break;
2473 return nullptr;
2476 /// Many binary operators with a constant operand have an easy-to-compute
2477 /// range of outputs. This can be used to fold a comparison to always true or
2478 /// always false.
2479 static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper,
2480 const InstrInfoQuery &IIQ) {
2481 unsigned Width = Lower.getBitWidth();
2482 const APInt *C;
2483 switch (BO.getOpcode()) {
2484 case Instruction::Add:
2485 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
2486 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2487 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
2488 // 'add nuw x, C' produces [C, UINT_MAX].
2489 Lower = *C;
2490 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
2491 if (C->isNegative()) {
2492 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2493 Lower = APInt::getSignedMinValue(Width);
2494 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2495 } else {
2496 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2497 Lower = APInt::getSignedMinValue(Width) + *C;
2498 Upper = APInt::getSignedMaxValue(Width) + 1;
2502 break;
2504 case Instruction::And:
2505 if (match(BO.getOperand(1), m_APInt(C)))
2506 // 'and x, C' produces [0, C].
2507 Upper = *C + 1;
2508 break;
2510 case Instruction::Or:
2511 if (match(BO.getOperand(1), m_APInt(C)))
2512 // 'or x, C' produces [C, UINT_MAX].
2513 Lower = *C;
2514 break;
2516 case Instruction::AShr:
2517 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2518 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2519 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2520 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2521 } else if (match(BO.getOperand(0), m_APInt(C))) {
2522 unsigned ShiftAmount = Width - 1;
2523 if (!C->isNullValue() && IIQ.isExact(&BO))
2524 ShiftAmount = C->countTrailingZeros();
2525 if (C->isNegative()) {
2526 // 'ashr C, x' produces [C, C >> (Width-1)]
2527 Lower = *C;
2528 Upper = C->ashr(ShiftAmount) + 1;
2529 } else {
2530 // 'ashr C, x' produces [C >> (Width-1), C]
2531 Lower = C->ashr(ShiftAmount);
2532 Upper = *C + 1;
2535 break;
2537 case Instruction::LShr:
2538 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2539 // 'lshr x, C' produces [0, UINT_MAX >> C].
2540 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2541 } else if (match(BO.getOperand(0), m_APInt(C))) {
2542 // 'lshr C, x' produces [C >> (Width-1), C].
2543 unsigned ShiftAmount = Width - 1;
2544 if (!C->isNullValue() && IIQ.isExact(&BO))
2545 ShiftAmount = C->countTrailingZeros();
2546 Lower = C->lshr(ShiftAmount);
2547 Upper = *C + 1;
2549 break;
2551 case Instruction::Shl:
2552 if (match(BO.getOperand(0), m_APInt(C))) {
2553 if (IIQ.hasNoUnsignedWrap(&BO)) {
2554 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2555 Lower = *C;
2556 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2557 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2558 if (C->isNegative()) {
2559 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2560 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2561 Lower = C->shl(ShiftAmount);
2562 Upper = *C + 1;
2563 } else {
2564 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2565 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2566 Lower = *C;
2567 Upper = C->shl(ShiftAmount) + 1;
2571 break;
2573 case Instruction::SDiv:
2574 if (match(BO.getOperand(1), m_APInt(C))) {
2575 APInt IntMin = APInt::getSignedMinValue(Width);
2576 APInt IntMax = APInt::getSignedMaxValue(Width);
2577 if (C->isAllOnesValue()) {
2578 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2579 // where C != -1 and C != 0 and C != 1
2580 Lower = IntMin + 1;
2581 Upper = IntMax + 1;
2582 } else if (C->countLeadingZeros() < Width - 1) {
2583 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2584 // where C != -1 and C != 0 and C != 1
2585 Lower = IntMin.sdiv(*C);
2586 Upper = IntMax.sdiv(*C);
2587 if (Lower.sgt(Upper))
2588 std::swap(Lower, Upper);
2589 Upper = Upper + 1;
2590 assert(Upper != Lower && "Upper part of range has wrapped!");
2592 } else if (match(BO.getOperand(0), m_APInt(C))) {
2593 if (C->isMinSignedValue()) {
2594 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2595 Lower = *C;
2596 Upper = Lower.lshr(1) + 1;
2597 } else {
2598 // 'sdiv C, x' produces [-|C|, |C|].
2599 Upper = C->abs() + 1;
2600 Lower = (-Upper) + 1;
2603 break;
2605 case Instruction::UDiv:
2606 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
2607 // 'udiv x, C' produces [0, UINT_MAX / C].
2608 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2609 } else if (match(BO.getOperand(0), m_APInt(C))) {
2610 // 'udiv C, x' produces [0, C].
2611 Upper = *C + 1;
2613 break;
2615 case Instruction::SRem:
2616 if (match(BO.getOperand(1), m_APInt(C))) {
2617 // 'srem x, C' produces (-|C|, |C|).
2618 Upper = C->abs();
2619 Lower = (-Upper) + 1;
2621 break;
2623 case Instruction::URem:
2624 if (match(BO.getOperand(1), m_APInt(C)))
2625 // 'urem x, C' produces [0, C).
2626 Upper = *C;
2627 break;
2629 default:
2630 break;
2634 /// Some intrinsics with a constant operand have an easy-to-compute range of
2635 /// outputs. This can be used to fold a comparison to always true or always
2636 /// false.
2637 static void setLimitsForIntrinsic(IntrinsicInst &II, APInt &Lower,
2638 APInt &Upper) {
2639 unsigned Width = Lower.getBitWidth();
2640 const APInt *C;
2641 switch (II.getIntrinsicID()) {
2642 case Intrinsic::uadd_sat:
2643 // uadd.sat(x, C) produces [C, UINT_MAX].
2644 if (match(II.getOperand(0), m_APInt(C)) ||
2645 match(II.getOperand(1), m_APInt(C)))
2646 Lower = *C;
2647 break;
2648 case Intrinsic::sadd_sat:
2649 if (match(II.getOperand(0), m_APInt(C)) ||
2650 match(II.getOperand(1), m_APInt(C))) {
2651 if (C->isNegative()) {
2652 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
2653 Lower = APInt::getSignedMinValue(Width);
2654 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2655 } else {
2656 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
2657 Lower = APInt::getSignedMinValue(Width) + *C;
2658 Upper = APInt::getSignedMaxValue(Width) + 1;
2661 break;
2662 case Intrinsic::usub_sat:
2663 // usub.sat(C, x) produces [0, C].
2664 if (match(II.getOperand(0), m_APInt(C)))
2665 Upper = *C + 1;
2666 // usub.sat(x, C) produces [0, UINT_MAX - C].
2667 else if (match(II.getOperand(1), m_APInt(C)))
2668 Upper = APInt::getMaxValue(Width) - *C + 1;
2669 break;
2670 case Intrinsic::ssub_sat:
2671 if (match(II.getOperand(0), m_APInt(C))) {
2672 if (C->isNegative()) {
2673 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
2674 Lower = APInt::getSignedMinValue(Width);
2675 Upper = *C - APInt::getSignedMinValue(Width) + 1;
2676 } else {
2677 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
2678 Lower = *C - APInt::getSignedMaxValue(Width);
2679 Upper = APInt::getSignedMaxValue(Width) + 1;
2681 } else if (match(II.getOperand(1), m_APInt(C))) {
2682 if (C->isNegative()) {
2683 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
2684 Lower = APInt::getSignedMinValue(Width) - *C;
2685 Upper = APInt::getSignedMaxValue(Width) + 1;
2686 } else {
2687 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
2688 Lower = APInt::getSignedMinValue(Width);
2689 Upper = APInt::getSignedMaxValue(Width) - *C + 1;
2692 break;
2693 default:
2694 break;
2698 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2699 Value *RHS, const InstrInfoQuery &IIQ) {
2700 Type *ITy = GetCompareTy(RHS); // The return type.
2702 Value *X;
2703 // Sign-bit checks can be optimized to true/false after unsigned
2704 // floating-point casts:
2705 // icmp slt (bitcast (uitofp X)), 0 --> false
2706 // icmp sgt (bitcast (uitofp X)), -1 --> true
2707 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2708 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2709 return ConstantInt::getFalse(ITy);
2710 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2711 return ConstantInt::getTrue(ITy);
2714 const APInt *C;
2715 if (!match(RHS, m_APInt(C)))
2716 return nullptr;
2718 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2719 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
2720 if (RHS_CR.isEmptySet())
2721 return ConstantInt::getFalse(ITy);
2722 if (RHS_CR.isFullSet())
2723 return ConstantInt::getTrue(ITy);
2725 // Find the range of possible values for binary operators.
2726 unsigned Width = C->getBitWidth();
2727 APInt Lower = APInt(Width, 0);
2728 APInt Upper = APInt(Width, 0);
2729 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2730 setLimitsForBinOp(*BO, Lower, Upper, IIQ);
2731 else if (auto *II = dyn_cast<IntrinsicInst>(LHS))
2732 setLimitsForIntrinsic(*II, Lower, Upper);
2734 ConstantRange LHS_CR =
2735 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2737 if (auto *I = dyn_cast<Instruction>(LHS))
2738 if (auto *Ranges = IIQ.getMetadata(I, LLVMContext::MD_range))
2739 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2741 if (!LHS_CR.isFullSet()) {
2742 if (RHS_CR.contains(LHS_CR))
2743 return ConstantInt::getTrue(ITy);
2744 if (RHS_CR.inverse().contains(LHS_CR))
2745 return ConstantInt::getFalse(ITy);
2748 return nullptr;
2751 /// TODO: A large part of this logic is duplicated in InstCombine's
2752 /// foldICmpBinOp(). We should be able to share that and avoid the code
2753 /// duplication.
2754 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2755 Value *RHS, const SimplifyQuery &Q,
2756 unsigned MaxRecurse) {
2757 Type *ITy = GetCompareTy(LHS); // The return type.
2759 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2760 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2761 if (MaxRecurse && (LBO || RBO)) {
2762 // Analyze the case when either LHS or RHS is an add instruction.
2763 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2764 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2765 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2766 if (LBO && LBO->getOpcode() == Instruction::Add) {
2767 A = LBO->getOperand(0);
2768 B = LBO->getOperand(1);
2769 NoLHSWrapProblem =
2770 ICmpInst::isEquality(Pred) ||
2771 (CmpInst::isUnsigned(Pred) &&
2772 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2773 (CmpInst::isSigned(Pred) &&
2774 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
2776 if (RBO && RBO->getOpcode() == Instruction::Add) {
2777 C = RBO->getOperand(0);
2778 D = RBO->getOperand(1);
2779 NoRHSWrapProblem =
2780 ICmpInst::isEquality(Pred) ||
2781 (CmpInst::isUnsigned(Pred) &&
2782 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2783 (CmpInst::isSigned(Pred) &&
2784 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
2787 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2788 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2789 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2790 Constant::getNullValue(RHS->getType()), Q,
2791 MaxRecurse - 1))
2792 return V;
2794 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2795 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2796 if (Value *V =
2797 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2798 C == LHS ? D : C, Q, MaxRecurse - 1))
2799 return V;
2801 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2802 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2803 NoRHSWrapProblem) {
2804 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2805 Value *Y, *Z;
2806 if (A == C) {
2807 // C + B == C + D -> B == D
2808 Y = B;
2809 Z = D;
2810 } else if (A == D) {
2811 // D + B == C + D -> B == C
2812 Y = B;
2813 Z = C;
2814 } else if (B == C) {
2815 // A + C == C + D -> A == D
2816 Y = A;
2817 Z = D;
2818 } else {
2819 assert(B == D);
2820 // A + D == C + D -> A == C
2821 Y = A;
2822 Z = C;
2824 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2825 return V;
2830 Value *Y = nullptr;
2831 // icmp pred (or X, Y), X
2832 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2833 if (Pred == ICmpInst::ICMP_ULT)
2834 return getFalse(ITy);
2835 if (Pred == ICmpInst::ICMP_UGE)
2836 return getTrue(ITy);
2838 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2839 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2840 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2841 if (RHSKnown.isNonNegative() && YKnown.isNegative())
2842 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2843 if (RHSKnown.isNegative() || YKnown.isNonNegative())
2844 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2847 // icmp pred X, (or X, Y)
2848 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2849 if (Pred == ICmpInst::ICMP_ULE)
2850 return getTrue(ITy);
2851 if (Pred == ICmpInst::ICMP_UGT)
2852 return getFalse(ITy);
2854 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2855 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2856 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2857 if (LHSKnown.isNonNegative() && YKnown.isNegative())
2858 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2859 if (LHSKnown.isNegative() || YKnown.isNonNegative())
2860 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2865 // icmp pred (and X, Y), X
2866 if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2867 if (Pred == ICmpInst::ICMP_UGT)
2868 return getFalse(ITy);
2869 if (Pred == ICmpInst::ICMP_ULE)
2870 return getTrue(ITy);
2872 // icmp pred X, (and X, Y)
2873 if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
2874 if (Pred == ICmpInst::ICMP_UGE)
2875 return getTrue(ITy);
2876 if (Pred == ICmpInst::ICMP_ULT)
2877 return getFalse(ITy);
2880 // 0 - (zext X) pred C
2881 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2882 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2883 if (RHSC->getValue().isStrictlyPositive()) {
2884 if (Pred == ICmpInst::ICMP_SLT)
2885 return ConstantInt::getTrue(RHSC->getContext());
2886 if (Pred == ICmpInst::ICMP_SGE)
2887 return ConstantInt::getFalse(RHSC->getContext());
2888 if (Pred == ICmpInst::ICMP_EQ)
2889 return ConstantInt::getFalse(RHSC->getContext());
2890 if (Pred == ICmpInst::ICMP_NE)
2891 return ConstantInt::getTrue(RHSC->getContext());
2893 if (RHSC->getValue().isNonNegative()) {
2894 if (Pred == ICmpInst::ICMP_SLE)
2895 return ConstantInt::getTrue(RHSC->getContext());
2896 if (Pred == ICmpInst::ICMP_SGT)
2897 return ConstantInt::getFalse(RHSC->getContext());
2902 // icmp pred (urem X, Y), Y
2903 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2904 switch (Pred) {
2905 default:
2906 break;
2907 case ICmpInst::ICMP_SGT:
2908 case ICmpInst::ICMP_SGE: {
2909 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2910 if (!Known.isNonNegative())
2911 break;
2912 LLVM_FALLTHROUGH;
2914 case ICmpInst::ICMP_EQ:
2915 case ICmpInst::ICMP_UGT:
2916 case ICmpInst::ICMP_UGE:
2917 return getFalse(ITy);
2918 case ICmpInst::ICMP_SLT:
2919 case ICmpInst::ICMP_SLE: {
2920 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2921 if (!Known.isNonNegative())
2922 break;
2923 LLVM_FALLTHROUGH;
2925 case ICmpInst::ICMP_NE:
2926 case ICmpInst::ICMP_ULT:
2927 case ICmpInst::ICMP_ULE:
2928 return getTrue(ITy);
2932 // icmp pred X, (urem Y, X)
2933 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2934 switch (Pred) {
2935 default:
2936 break;
2937 case ICmpInst::ICMP_SGT:
2938 case ICmpInst::ICMP_SGE: {
2939 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2940 if (!Known.isNonNegative())
2941 break;
2942 LLVM_FALLTHROUGH;
2944 case ICmpInst::ICMP_NE:
2945 case ICmpInst::ICMP_UGT:
2946 case ICmpInst::ICMP_UGE:
2947 return getTrue(ITy);
2948 case ICmpInst::ICMP_SLT:
2949 case ICmpInst::ICMP_SLE: {
2950 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2951 if (!Known.isNonNegative())
2952 break;
2953 LLVM_FALLTHROUGH;
2955 case ICmpInst::ICMP_EQ:
2956 case ICmpInst::ICMP_ULT:
2957 case ICmpInst::ICMP_ULE:
2958 return getFalse(ITy);
2962 // x >> y <=u x
2963 // x udiv y <=u x.
2964 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2965 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2966 // icmp pred (X op Y), X
2967 if (Pred == ICmpInst::ICMP_UGT)
2968 return getFalse(ITy);
2969 if (Pred == ICmpInst::ICMP_ULE)
2970 return getTrue(ITy);
2973 // x >=u x >> y
2974 // x >=u x udiv y.
2975 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2976 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2977 // icmp pred X, (X op Y)
2978 if (Pred == ICmpInst::ICMP_ULT)
2979 return getFalse(ITy);
2980 if (Pred == ICmpInst::ICMP_UGE)
2981 return getTrue(ITy);
2984 // handle:
2985 // CI2 << X == CI
2986 // CI2 << X != CI
2988 // where CI2 is a power of 2 and CI isn't
2989 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2990 const APInt *CI2Val, *CIVal = &CI->getValue();
2991 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2992 CI2Val->isPowerOf2()) {
2993 if (!CIVal->isPowerOf2()) {
2994 // CI2 << X can equal zero in some circumstances,
2995 // this simplification is unsafe if CI is zero.
2997 // We know it is safe if:
2998 // - The shift is nsw, we can't shift out the one bit.
2999 // - The shift is nuw, we can't shift out the one bit.
3000 // - CI2 is one
3001 // - CI isn't zero
3002 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3003 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3004 CI2Val->isOneValue() || !CI->isZero()) {
3005 if (Pred == ICmpInst::ICMP_EQ)
3006 return ConstantInt::getFalse(RHS->getContext());
3007 if (Pred == ICmpInst::ICMP_NE)
3008 return ConstantInt::getTrue(RHS->getContext());
3011 if (CIVal->isSignMask() && CI2Val->isOneValue()) {
3012 if (Pred == ICmpInst::ICMP_UGT)
3013 return ConstantInt::getFalse(RHS->getContext());
3014 if (Pred == ICmpInst::ICMP_ULE)
3015 return ConstantInt::getTrue(RHS->getContext());
3020 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3021 LBO->getOperand(1) == RBO->getOperand(1)) {
3022 switch (LBO->getOpcode()) {
3023 default:
3024 break;
3025 case Instruction::UDiv:
3026 case Instruction::LShr:
3027 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3028 !Q.IIQ.isExact(RBO))
3029 break;
3030 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3031 RBO->getOperand(0), Q, MaxRecurse - 1))
3032 return V;
3033 break;
3034 case Instruction::SDiv:
3035 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3036 !Q.IIQ.isExact(RBO))
3037 break;
3038 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3039 RBO->getOperand(0), Q, MaxRecurse - 1))
3040 return V;
3041 break;
3042 case Instruction::AShr:
3043 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3044 break;
3045 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3046 RBO->getOperand(0), Q, MaxRecurse - 1))
3047 return V;
3048 break;
3049 case Instruction::Shl: {
3050 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3051 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3052 if (!NUW && !NSW)
3053 break;
3054 if (!NSW && ICmpInst::isSigned(Pred))
3055 break;
3056 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3057 RBO->getOperand(0), Q, MaxRecurse - 1))
3058 return V;
3059 break;
3063 return nullptr;
3066 static Value *simplifyICmpWithAbsNabs(CmpInst::Predicate Pred, Value *Op0,
3067 Value *Op1) {
3068 // We need a comparison with a constant.
3069 const APInt *C;
3070 if (!match(Op1, m_APInt(C)))
3071 return nullptr;
3073 // matchSelectPattern returns the negation part of an abs pattern in SP1.
3074 // If the negate has an NSW flag, abs(INT_MIN) is undefined. Without that
3075 // constraint, we can't make a contiguous range for the result of abs.
3076 ICmpInst::Predicate AbsPred = ICmpInst::BAD_ICMP_PREDICATE;
3077 Value *SP0, *SP1;
3078 SelectPatternFlavor SPF = matchSelectPattern(Op0, SP0, SP1).Flavor;
3079 if (SPF == SelectPatternFlavor::SPF_ABS &&
3080 cast<Instruction>(SP1)->hasNoSignedWrap())
3081 // The result of abs(X) is >= 0 (with nsw).
3082 AbsPred = ICmpInst::ICMP_SGE;
3083 if (SPF == SelectPatternFlavor::SPF_NABS)
3084 // The result of -abs(X) is <= 0.
3085 AbsPred = ICmpInst::ICMP_SLE;
3087 if (AbsPred == ICmpInst::BAD_ICMP_PREDICATE)
3088 return nullptr;
3090 // If there is no intersection between abs/nabs and the range of this icmp,
3091 // the icmp must be false. If the abs/nabs range is a subset of the icmp
3092 // range, the icmp must be true.
3093 APInt Zero = APInt::getNullValue(C->getBitWidth());
3094 ConstantRange AbsRange = ConstantRange::makeExactICmpRegion(AbsPred, Zero);
3095 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(Pred, *C);
3096 if (AbsRange.intersectWith(CmpRange).isEmptySet())
3097 return getFalse(GetCompareTy(Op0));
3098 if (CmpRange.contains(AbsRange))
3099 return getTrue(GetCompareTy(Op0));
3101 return nullptr;
3104 /// Simplify integer comparisons where at least one operand of the compare
3105 /// matches an integer min/max idiom.
3106 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3107 Value *RHS, const SimplifyQuery &Q,
3108 unsigned MaxRecurse) {
3109 Type *ITy = GetCompareTy(LHS); // The return type.
3110 Value *A, *B;
3111 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3112 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3114 // Signed variants on "max(a,b)>=a -> true".
3115 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3116 if (A != RHS)
3117 std::swap(A, B); // smax(A, B) pred A.
3118 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3119 // We analyze this as smax(A, B) pred A.
3120 P = Pred;
3121 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3122 (A == LHS || B == LHS)) {
3123 if (A != LHS)
3124 std::swap(A, B); // A pred smax(A, B).
3125 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3126 // We analyze this as smax(A, B) swapped-pred A.
3127 P = CmpInst::getSwappedPredicate(Pred);
3128 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3129 (A == RHS || B == RHS)) {
3130 if (A != RHS)
3131 std::swap(A, B); // smin(A, B) pred A.
3132 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3133 // We analyze this as smax(-A, -B) swapped-pred -A.
3134 // Note that we do not need to actually form -A or -B thanks to EqP.
3135 P = CmpInst::getSwappedPredicate(Pred);
3136 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3137 (A == LHS || B == LHS)) {
3138 if (A != LHS)
3139 std::swap(A, B); // A pred smin(A, B).
3140 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3141 // We analyze this as smax(-A, -B) pred -A.
3142 // Note that we do not need to actually form -A or -B thanks to EqP.
3143 P = Pred;
3145 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3146 // Cases correspond to "max(A, B) p A".
3147 switch (P) {
3148 default:
3149 break;
3150 case CmpInst::ICMP_EQ:
3151 case CmpInst::ICMP_SLE:
3152 // Equivalent to "A EqP B". This may be the same as the condition tested
3153 // in the max/min; if so, we can just return that.
3154 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3155 return V;
3156 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3157 return V;
3158 // Otherwise, see if "A EqP B" simplifies.
3159 if (MaxRecurse)
3160 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3161 return V;
3162 break;
3163 case CmpInst::ICMP_NE:
3164 case CmpInst::ICMP_SGT: {
3165 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3166 // Equivalent to "A InvEqP B". This may be the same as the condition
3167 // tested in the max/min; if so, we can just return that.
3168 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3169 return V;
3170 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3171 return V;
3172 // Otherwise, see if "A InvEqP B" simplifies.
3173 if (MaxRecurse)
3174 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3175 return V;
3176 break;
3178 case CmpInst::ICMP_SGE:
3179 // Always true.
3180 return getTrue(ITy);
3181 case CmpInst::ICMP_SLT:
3182 // Always false.
3183 return getFalse(ITy);
3187 // Unsigned variants on "max(a,b)>=a -> true".
3188 P = CmpInst::BAD_ICMP_PREDICATE;
3189 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3190 if (A != RHS)
3191 std::swap(A, B); // umax(A, B) pred A.
3192 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3193 // We analyze this as umax(A, B) pred A.
3194 P = Pred;
3195 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3196 (A == LHS || B == LHS)) {
3197 if (A != LHS)
3198 std::swap(A, B); // A pred umax(A, B).
3199 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3200 // We analyze this as umax(A, B) swapped-pred A.
3201 P = CmpInst::getSwappedPredicate(Pred);
3202 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3203 (A == RHS || B == RHS)) {
3204 if (A != RHS)
3205 std::swap(A, B); // umin(A, B) pred A.
3206 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3207 // We analyze this as umax(-A, -B) swapped-pred -A.
3208 // Note that we do not need to actually form -A or -B thanks to EqP.
3209 P = CmpInst::getSwappedPredicate(Pred);
3210 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3211 (A == LHS || B == LHS)) {
3212 if (A != LHS)
3213 std::swap(A, B); // A pred umin(A, B).
3214 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3215 // We analyze this as umax(-A, -B) pred -A.
3216 // Note that we do not need to actually form -A or -B thanks to EqP.
3217 P = Pred;
3219 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3220 // Cases correspond to "max(A, B) p A".
3221 switch (P) {
3222 default:
3223 break;
3224 case CmpInst::ICMP_EQ:
3225 case CmpInst::ICMP_ULE:
3226 // Equivalent to "A EqP B". This may be the same as the condition tested
3227 // in the max/min; if so, we can just return that.
3228 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3229 return V;
3230 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3231 return V;
3232 // Otherwise, see if "A EqP B" simplifies.
3233 if (MaxRecurse)
3234 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3235 return V;
3236 break;
3237 case CmpInst::ICMP_NE:
3238 case CmpInst::ICMP_UGT: {
3239 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3240 // Equivalent to "A InvEqP B". This may be the same as the condition
3241 // tested in the max/min; if so, we can just return that.
3242 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3243 return V;
3244 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3245 return V;
3246 // Otherwise, see if "A InvEqP B" simplifies.
3247 if (MaxRecurse)
3248 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3249 return V;
3250 break;
3252 case CmpInst::ICMP_UGE:
3253 // Always true.
3254 return getTrue(ITy);
3255 case CmpInst::ICMP_ULT:
3256 // Always false.
3257 return getFalse(ITy);
3261 // Variants on "max(x,y) >= min(x,z)".
3262 Value *C, *D;
3263 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3264 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3265 (A == C || A == D || B == C || B == D)) {
3266 // max(x, ?) pred min(x, ?).
3267 if (Pred == CmpInst::ICMP_SGE)
3268 // Always true.
3269 return getTrue(ITy);
3270 if (Pred == CmpInst::ICMP_SLT)
3271 // Always false.
3272 return getFalse(ITy);
3273 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3274 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3275 (A == C || A == D || B == C || B == D)) {
3276 // min(x, ?) pred max(x, ?).
3277 if (Pred == CmpInst::ICMP_SLE)
3278 // Always true.
3279 return getTrue(ITy);
3280 if (Pred == CmpInst::ICMP_SGT)
3281 // Always false.
3282 return getFalse(ITy);
3283 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3284 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3285 (A == C || A == D || B == C || B == D)) {
3286 // max(x, ?) pred min(x, ?).
3287 if (Pred == CmpInst::ICMP_UGE)
3288 // Always true.
3289 return getTrue(ITy);
3290 if (Pred == CmpInst::ICMP_ULT)
3291 // Always false.
3292 return getFalse(ITy);
3293 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3294 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3295 (A == C || A == D || B == C || B == D)) {
3296 // min(x, ?) pred max(x, ?).
3297 if (Pred == CmpInst::ICMP_ULE)
3298 // Always true.
3299 return getTrue(ITy);
3300 if (Pred == CmpInst::ICMP_UGT)
3301 // Always false.
3302 return getFalse(ITy);
3305 return nullptr;
3308 /// Given operands for an ICmpInst, see if we can fold the result.
3309 /// If not, this returns null.
3310 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3311 const SimplifyQuery &Q, unsigned MaxRecurse) {
3312 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3313 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3315 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3316 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3317 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3319 // If we have a constant, make sure it is on the RHS.
3320 std::swap(LHS, RHS);
3321 Pred = CmpInst::getSwappedPredicate(Pred);
3324 Type *ITy = GetCompareTy(LHS); // The return type.
3326 // icmp X, X -> true/false
3327 // icmp X, undef -> true/false because undef could be X.
3328 if (LHS == RHS || isa<UndefValue>(RHS))
3329 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3331 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3332 return V;
3334 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3335 return V;
3337 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3338 return V;
3340 // If both operands have range metadata, use the metadata
3341 // to simplify the comparison.
3342 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3343 auto RHS_Instr = cast<Instruction>(RHS);
3344 auto LHS_Instr = cast<Instruction>(LHS);
3346 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3347 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3348 auto RHS_CR = getConstantRangeFromMetadata(
3349 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3350 auto LHS_CR = getConstantRangeFromMetadata(
3351 *LHS_Instr->getMetadata(LLVMContext::MD_range));
3353 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3354 if (Satisfied_CR.contains(LHS_CR))
3355 return ConstantInt::getTrue(RHS->getContext());
3357 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3358 CmpInst::getInversePredicate(Pred), RHS_CR);
3359 if (InversedSatisfied_CR.contains(LHS_CR))
3360 return ConstantInt::getFalse(RHS->getContext());
3364 // Compare of cast, for example (zext X) != 0 -> X != 0
3365 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3366 Instruction *LI = cast<CastInst>(LHS);
3367 Value *SrcOp = LI->getOperand(0);
3368 Type *SrcTy = SrcOp->getType();
3369 Type *DstTy = LI->getType();
3371 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3372 // if the integer type is the same size as the pointer type.
3373 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3374 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3375 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3376 // Transfer the cast to the constant.
3377 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3378 ConstantExpr::getIntToPtr(RHSC, SrcTy),
3379 Q, MaxRecurse-1))
3380 return V;
3381 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3382 if (RI->getOperand(0)->getType() == SrcTy)
3383 // Compare without the cast.
3384 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3385 Q, MaxRecurse-1))
3386 return V;
3390 if (isa<ZExtInst>(LHS)) {
3391 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3392 // same type.
3393 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3394 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3395 // Compare X and Y. Note that signed predicates become unsigned.
3396 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3397 SrcOp, RI->getOperand(0), Q,
3398 MaxRecurse-1))
3399 return V;
3401 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3402 // too. If not, then try to deduce the result of the comparison.
3403 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3404 // Compute the constant that would happen if we truncated to SrcTy then
3405 // reextended to DstTy.
3406 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3407 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3409 // If the re-extended constant didn't change then this is effectively
3410 // also a case of comparing two zero-extended values.
3411 if (RExt == CI && MaxRecurse)
3412 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3413 SrcOp, Trunc, Q, MaxRecurse-1))
3414 return V;
3416 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3417 // there. Use this to work out the result of the comparison.
3418 if (RExt != CI) {
3419 switch (Pred) {
3420 default: llvm_unreachable("Unknown ICmp predicate!");
3421 // LHS <u RHS.
3422 case ICmpInst::ICMP_EQ:
3423 case ICmpInst::ICMP_UGT:
3424 case ICmpInst::ICMP_UGE:
3425 return ConstantInt::getFalse(CI->getContext());
3427 case ICmpInst::ICMP_NE:
3428 case ICmpInst::ICMP_ULT:
3429 case ICmpInst::ICMP_ULE:
3430 return ConstantInt::getTrue(CI->getContext());
3432 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3433 // is non-negative then LHS <s RHS.
3434 case ICmpInst::ICMP_SGT:
3435 case ICmpInst::ICMP_SGE:
3436 return CI->getValue().isNegative() ?
3437 ConstantInt::getTrue(CI->getContext()) :
3438 ConstantInt::getFalse(CI->getContext());
3440 case ICmpInst::ICMP_SLT:
3441 case ICmpInst::ICMP_SLE:
3442 return CI->getValue().isNegative() ?
3443 ConstantInt::getFalse(CI->getContext()) :
3444 ConstantInt::getTrue(CI->getContext());
3450 if (isa<SExtInst>(LHS)) {
3451 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3452 // same type.
3453 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3454 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3455 // Compare X and Y. Note that the predicate does not change.
3456 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3457 Q, MaxRecurse-1))
3458 return V;
3460 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3461 // too. If not, then try to deduce the result of the comparison.
3462 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3463 // Compute the constant that would happen if we truncated to SrcTy then
3464 // reextended to DstTy.
3465 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3466 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3468 // If the re-extended constant didn't change then this is effectively
3469 // also a case of comparing two sign-extended values.
3470 if (RExt == CI && MaxRecurse)
3471 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3472 return V;
3474 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3475 // bits there. Use this to work out the result of the comparison.
3476 if (RExt != CI) {
3477 switch (Pred) {
3478 default: llvm_unreachable("Unknown ICmp predicate!");
3479 case ICmpInst::ICMP_EQ:
3480 return ConstantInt::getFalse(CI->getContext());
3481 case ICmpInst::ICMP_NE:
3482 return ConstantInt::getTrue(CI->getContext());
3484 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3485 // LHS >s RHS.
3486 case ICmpInst::ICMP_SGT:
3487 case ICmpInst::ICMP_SGE:
3488 return CI->getValue().isNegative() ?
3489 ConstantInt::getTrue(CI->getContext()) :
3490 ConstantInt::getFalse(CI->getContext());
3491 case ICmpInst::ICMP_SLT:
3492 case ICmpInst::ICMP_SLE:
3493 return CI->getValue().isNegative() ?
3494 ConstantInt::getFalse(CI->getContext()) :
3495 ConstantInt::getTrue(CI->getContext());
3497 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3498 // LHS >u RHS.
3499 case ICmpInst::ICMP_UGT:
3500 case ICmpInst::ICMP_UGE:
3501 // Comparison is true iff the LHS <s 0.
3502 if (MaxRecurse)
3503 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3504 Constant::getNullValue(SrcTy),
3505 Q, MaxRecurse-1))
3506 return V;
3507 break;
3508 case ICmpInst::ICMP_ULT:
3509 case ICmpInst::ICMP_ULE:
3510 // Comparison is true iff the LHS >=s 0.
3511 if (MaxRecurse)
3512 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3513 Constant::getNullValue(SrcTy),
3514 Q, MaxRecurse-1))
3515 return V;
3516 break;
3523 // icmp eq|ne X, Y -> false|true if X != Y
3524 if (ICmpInst::isEquality(Pred) &&
3525 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3526 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3529 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3530 return V;
3532 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3533 return V;
3535 if (Value *V = simplifyICmpWithAbsNabs(Pred, LHS, RHS))
3536 return V;
3538 // Simplify comparisons of related pointers using a powerful, recursive
3539 // GEP-walk when we have target data available..
3540 if (LHS->getType()->isPointerTy())
3541 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3542 Q.IIQ, LHS, RHS))
3543 return C;
3544 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3545 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3546 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3547 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3548 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3549 Q.DL.getTypeSizeInBits(CRHS->getType()))
3550 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3551 Q.IIQ, CLHS->getPointerOperand(),
3552 CRHS->getPointerOperand()))
3553 return C;
3555 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3556 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3557 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3558 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3559 (ICmpInst::isEquality(Pred) ||
3560 (GLHS->isInBounds() && GRHS->isInBounds() &&
3561 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3562 // The bases are equal and the indices are constant. Build a constant
3563 // expression GEP with the same indices and a null base pointer to see
3564 // what constant folding can make out of it.
3565 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3566 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3567 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3568 GLHS->getSourceElementType(), Null, IndicesLHS);
3570 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3571 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3572 GLHS->getSourceElementType(), Null, IndicesRHS);
3573 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3578 // If the comparison is with the result of a select instruction, check whether
3579 // comparing with either branch of the select always yields the same value.
3580 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3581 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3582 return V;
3584 // If the comparison is with the result of a phi instruction, check whether
3585 // doing the compare with each incoming phi value yields a common result.
3586 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3587 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3588 return V;
3590 return nullptr;
3593 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3594 const SimplifyQuery &Q) {
3595 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3598 /// Given operands for an FCmpInst, see if we can fold the result.
3599 /// If not, this returns null.
3600 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3601 FastMathFlags FMF, const SimplifyQuery &Q,
3602 unsigned MaxRecurse) {
3603 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3604 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3606 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3607 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3608 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3610 // If we have a constant, make sure it is on the RHS.
3611 std::swap(LHS, RHS);
3612 Pred = CmpInst::getSwappedPredicate(Pred);
3615 // Fold trivial predicates.
3616 Type *RetTy = GetCompareTy(LHS);
3617 if (Pred == FCmpInst::FCMP_FALSE)
3618 return getFalse(RetTy);
3619 if (Pred == FCmpInst::FCMP_TRUE)
3620 return getTrue(RetTy);
3622 // Fold (un)ordered comparison if we can determine there are no NaNs.
3623 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3624 if (FMF.noNaNs() ||
3625 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3626 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3628 // NaN is unordered; NaN is not ordered.
3629 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3630 "Comparison must be either ordered or unordered");
3631 if (match(RHS, m_NaN()))
3632 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3634 // fcmp pred x, undef and fcmp pred undef, x
3635 // fold to true if unordered, false if ordered
3636 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3637 // Choosing NaN for the undef will always make unordered comparison succeed
3638 // and ordered comparison fail.
3639 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3642 // fcmp x,x -> true/false. Not all compares are foldable.
3643 if (LHS == RHS) {
3644 if (CmpInst::isTrueWhenEqual(Pred))
3645 return getTrue(RetTy);
3646 if (CmpInst::isFalseWhenEqual(Pred))
3647 return getFalse(RetTy);
3650 // Handle fcmp with constant RHS.
3651 const APFloat *C;
3652 if (match(RHS, m_APFloat(C))) {
3653 // Check whether the constant is an infinity.
3654 if (C->isInfinity()) {
3655 if (C->isNegative()) {
3656 switch (Pred) {
3657 case FCmpInst::FCMP_OLT:
3658 // No value is ordered and less than negative infinity.
3659 return getFalse(RetTy);
3660 case FCmpInst::FCMP_UGE:
3661 // All values are unordered with or at least negative infinity.
3662 return getTrue(RetTy);
3663 default:
3664 break;
3666 } else {
3667 switch (Pred) {
3668 case FCmpInst::FCMP_OGT:
3669 // No value is ordered and greater than infinity.
3670 return getFalse(RetTy);
3671 case FCmpInst::FCMP_ULE:
3672 // All values are unordered with and at most infinity.
3673 return getTrue(RetTy);
3674 default:
3675 break;
3679 if (C->isZero()) {
3680 switch (Pred) {
3681 case FCmpInst::FCMP_OGE:
3682 if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3683 return getTrue(RetTy);
3684 break;
3685 case FCmpInst::FCMP_UGE:
3686 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3687 return getTrue(RetTy);
3688 break;
3689 case FCmpInst::FCMP_ULT:
3690 if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3691 return getFalse(RetTy);
3692 break;
3693 case FCmpInst::FCMP_OLT:
3694 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3695 return getFalse(RetTy);
3696 break;
3697 default:
3698 break;
3700 } else if (C->isNegative()) {
3701 assert(!C->isNaN() && "Unexpected NaN constant!");
3702 // TODO: We can catch more cases by using a range check rather than
3703 // relying on CannotBeOrderedLessThanZero.
3704 switch (Pred) {
3705 case FCmpInst::FCMP_UGE:
3706 case FCmpInst::FCMP_UGT:
3707 case FCmpInst::FCMP_UNE:
3708 // (X >= 0) implies (X > C) when (C < 0)
3709 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3710 return getTrue(RetTy);
3711 break;
3712 case FCmpInst::FCMP_OEQ:
3713 case FCmpInst::FCMP_OLE:
3714 case FCmpInst::FCMP_OLT:
3715 // (X >= 0) implies !(X < C) when (C < 0)
3716 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3717 return getFalse(RetTy);
3718 break;
3719 default:
3720 break;
3725 // If the comparison is with the result of a select instruction, check whether
3726 // comparing with either branch of the select always yields the same value.
3727 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3728 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3729 return V;
3731 // If the comparison is with the result of a phi instruction, check whether
3732 // doing the compare with each incoming phi value yields a common result.
3733 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3734 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3735 return V;
3737 return nullptr;
3740 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3741 FastMathFlags FMF, const SimplifyQuery &Q) {
3742 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3745 /// See if V simplifies when its operand Op is replaced with RepOp.
3746 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3747 const SimplifyQuery &Q,
3748 unsigned MaxRecurse) {
3749 // Trivial replacement.
3750 if (V == Op)
3751 return RepOp;
3753 // We cannot replace a constant, and shouldn't even try.
3754 if (isa<Constant>(Op))
3755 return nullptr;
3757 auto *I = dyn_cast<Instruction>(V);
3758 if (!I)
3759 return nullptr;
3761 // If this is a binary operator, try to simplify it with the replaced op.
3762 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3763 // Consider:
3764 // %cmp = icmp eq i32 %x, 2147483647
3765 // %add = add nsw i32 %x, 1
3766 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3768 // We can't replace %sel with %add unless we strip away the flags.
3769 if (isa<OverflowingBinaryOperator>(B))
3770 if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
3771 return nullptr;
3772 if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3773 return nullptr;
3775 if (MaxRecurse) {
3776 if (B->getOperand(0) == Op)
3777 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3778 MaxRecurse - 1);
3779 if (B->getOperand(1) == Op)
3780 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3781 MaxRecurse - 1);
3785 // Same for CmpInsts.
3786 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3787 if (MaxRecurse) {
3788 if (C->getOperand(0) == Op)
3789 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3790 MaxRecurse - 1);
3791 if (C->getOperand(1) == Op)
3792 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3793 MaxRecurse - 1);
3797 // Same for GEPs.
3798 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3799 if (MaxRecurse) {
3800 SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3801 transform(GEP->operands(), NewOps.begin(),
3802 [&](Value *V) { return V == Op ? RepOp : V; });
3803 return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3804 MaxRecurse - 1);
3808 // TODO: We could hand off more cases to instsimplify here.
3810 // If all operands are constant after substituting Op for RepOp then we can
3811 // constant fold the instruction.
3812 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3813 // Build a list of all constant operands.
3814 SmallVector<Constant *, 8> ConstOps;
3815 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3816 if (I->getOperand(i) == Op)
3817 ConstOps.push_back(CRepOp);
3818 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3819 ConstOps.push_back(COp);
3820 else
3821 break;
3824 // All operands were constants, fold it.
3825 if (ConstOps.size() == I->getNumOperands()) {
3826 if (CmpInst *C = dyn_cast<CmpInst>(I))
3827 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3828 ConstOps[1], Q.DL, Q.TLI);
3830 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3831 if (!LI->isVolatile())
3832 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3834 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3838 return nullptr;
3841 /// Try to simplify a select instruction when its condition operand is an
3842 /// integer comparison where one operand of the compare is a constant.
3843 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3844 const APInt *Y, bool TrueWhenUnset) {
3845 const APInt *C;
3847 // (X & Y) == 0 ? X & ~Y : X --> X
3848 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3849 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3850 *Y == ~*C)
3851 return TrueWhenUnset ? FalseVal : TrueVal;
3853 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3854 // (X & Y) != 0 ? X : X & ~Y --> X
3855 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3856 *Y == ~*C)
3857 return TrueWhenUnset ? FalseVal : TrueVal;
3859 if (Y->isPowerOf2()) {
3860 // (X & Y) == 0 ? X | Y : X --> X | Y
3861 // (X & Y) != 0 ? X | Y : X --> X
3862 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3863 *Y == *C)
3864 return TrueWhenUnset ? TrueVal : FalseVal;
3866 // (X & Y) == 0 ? X : X | Y --> X
3867 // (X & Y) != 0 ? X : X | Y --> X | Y
3868 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3869 *Y == *C)
3870 return TrueWhenUnset ? TrueVal : FalseVal;
3873 return nullptr;
3876 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3877 /// eq/ne.
3878 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3879 ICmpInst::Predicate Pred,
3880 Value *TrueVal, Value *FalseVal) {
3881 Value *X;
3882 APInt Mask;
3883 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3884 return nullptr;
3886 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3887 Pred == ICmpInst::ICMP_EQ);
3890 /// Try to simplify a select instruction when its condition operand is an
3891 /// integer comparison.
3892 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3893 Value *FalseVal, const SimplifyQuery &Q,
3894 unsigned MaxRecurse) {
3895 ICmpInst::Predicate Pred;
3896 Value *CmpLHS, *CmpRHS;
3897 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3898 return nullptr;
3900 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3901 Value *X;
3902 const APInt *Y;
3903 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3904 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3905 Pred == ICmpInst::ICMP_EQ))
3906 return V;
3908 // Test for zero-shift-guard-ops around funnel shifts. These are used to
3909 // avoid UB from oversized shifts in raw IR rotate patterns, but the
3910 // intrinsics do not have that problem.
3911 Value *ShAmt;
3912 auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3913 m_Value(ShAmt)),
3914 m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3915 m_Value(ShAmt)));
3916 // (ShAmt != 0) ? fshl(X, *, ShAmt) : X --> fshl(X, *, ShAmt)
3917 // (ShAmt != 0) ? fshr(*, X, ShAmt) : X --> fshr(*, X, ShAmt)
3918 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3919 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3920 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
3921 return Pred == ICmpInst::ICMP_NE ? TrueVal : X;
3923 // (ShAmt == 0) ? X : fshl(X, *, ShAmt) --> fshl(X, *, ShAmt)
3924 // (ShAmt == 0) ? X : fshr(*, X, ShAmt) --> fshr(*, X, ShAmt)
3925 // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3926 // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3927 if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt)
3928 return Pred == ICmpInst::ICMP_EQ ? FalseVal : X;
3931 // Check for other compares that behave like bit test.
3932 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3933 TrueVal, FalseVal))
3934 return V;
3936 // If we have an equality comparison, then we know the value in one of the
3937 // arms of the select. See if substituting this value into the arm and
3938 // simplifying the result yields the same value as the other arm.
3939 if (Pred == ICmpInst::ICMP_EQ) {
3940 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3941 TrueVal ||
3942 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3943 TrueVal)
3944 return FalseVal;
3945 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3946 FalseVal ||
3947 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3948 FalseVal)
3949 return FalseVal;
3950 } else if (Pred == ICmpInst::ICMP_NE) {
3951 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3952 FalseVal ||
3953 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3954 FalseVal)
3955 return TrueVal;
3956 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3957 TrueVal ||
3958 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3959 TrueVal)
3960 return TrueVal;
3963 return nullptr;
3966 /// Try to simplify a select instruction when its condition operand is a
3967 /// floating-point comparison.
3968 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) {
3969 FCmpInst::Predicate Pred;
3970 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3971 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3972 return nullptr;
3974 // TODO: The transform may not be valid with -0.0. An incomplete way of
3975 // testing for that possibility is to check if at least one operand is a
3976 // non-zero constant.
3977 const APFloat *C;
3978 if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3979 (match(F, m_APFloat(C)) && C->isNonZero())) {
3980 // (T == F) ? T : F --> F
3981 // (F == T) ? T : F --> F
3982 if (Pred == FCmpInst::FCMP_OEQ)
3983 return F;
3985 // (T != F) ? T : F --> T
3986 // (F != T) ? T : F --> T
3987 if (Pred == FCmpInst::FCMP_UNE)
3988 return T;
3991 return nullptr;
3994 /// Given operands for a SelectInst, see if we can fold the result.
3995 /// If not, this returns null.
3996 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3997 const SimplifyQuery &Q, unsigned MaxRecurse) {
3998 if (auto *CondC = dyn_cast<Constant>(Cond)) {
3999 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4000 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4001 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4003 // select undef, X, Y -> X or Y
4004 if (isa<UndefValue>(CondC))
4005 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4007 // TODO: Vector constants with undef elements don't simplify.
4009 // select true, X, Y -> X
4010 if (CondC->isAllOnesValue())
4011 return TrueVal;
4012 // select false, X, Y -> Y
4013 if (CondC->isNullValue())
4014 return FalseVal;
4017 // select ?, X, X -> X
4018 if (TrueVal == FalseVal)
4019 return TrueVal;
4021 if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X
4022 return FalseVal;
4023 if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X
4024 return TrueVal;
4026 if (Value *V =
4027 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4028 return V;
4030 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
4031 return V;
4033 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4034 return V;
4036 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4037 if (Imp)
4038 return *Imp ? TrueVal : FalseVal;
4040 return nullptr;
4043 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4044 const SimplifyQuery &Q) {
4045 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4048 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4049 /// If not, this returns null.
4050 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4051 const SimplifyQuery &Q, unsigned) {
4052 // The type of the GEP pointer operand.
4053 unsigned AS =
4054 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
4056 // getelementptr P -> P.
4057 if (Ops.size() == 1)
4058 return Ops[0];
4060 // Compute the (pointer) type returned by the GEP instruction.
4061 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
4062 Type *GEPTy = PointerType::get(LastType, AS);
4063 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
4064 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
4065 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
4066 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
4068 if (isa<UndefValue>(Ops[0]))
4069 return UndefValue::get(GEPTy);
4071 if (Ops.size() == 2) {
4072 // getelementptr P, 0 -> P.
4073 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
4074 return Ops[0];
4076 Type *Ty = SrcTy;
4077 if (Ty->isSized()) {
4078 Value *P;
4079 uint64_t C;
4080 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4081 // getelementptr P, N -> P if P points to a type of zero size.
4082 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
4083 return Ops[0];
4085 // The following transforms are only safe if the ptrtoint cast
4086 // doesn't truncate the pointers.
4087 if (Ops[1]->getType()->getScalarSizeInBits() ==
4088 Q.DL.getIndexSizeInBits(AS)) {
4089 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
4090 if (match(P, m_Zero()))
4091 return Constant::getNullValue(GEPTy);
4092 Value *Temp;
4093 if (match(P, m_PtrToInt(m_Value(Temp))))
4094 if (Temp->getType() == GEPTy)
4095 return Temp;
4096 return nullptr;
4099 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4100 if (TyAllocSize == 1 &&
4101 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
4102 if (Value *R = PtrToIntOrZero(P))
4103 return R;
4105 // getelementptr V, (ashr (sub P, V), C) -> Q
4106 // if P points to a type of size 1 << C.
4107 if (match(Ops[1],
4108 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4109 m_ConstantInt(C))) &&
4110 TyAllocSize == 1ULL << C)
4111 if (Value *R = PtrToIntOrZero(P))
4112 return R;
4114 // getelementptr V, (sdiv (sub P, V), C) -> Q
4115 // if P points to a type of size C.
4116 if (match(Ops[1],
4117 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4118 m_SpecificInt(TyAllocSize))))
4119 if (Value *R = PtrToIntOrZero(P))
4120 return R;
4125 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
4126 all_of(Ops.slice(1).drop_back(1),
4127 [](Value *Idx) { return match(Idx, m_Zero()); })) {
4128 unsigned IdxWidth =
4129 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4130 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4131 APInt BasePtrOffset(IdxWidth, 0);
4132 Value *StrippedBasePtr =
4133 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4134 BasePtrOffset);
4136 // gep (gep V, C), (sub 0, V) -> C
4137 if (match(Ops.back(),
4138 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
4139 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4140 return ConstantExpr::getIntToPtr(CI, GEPTy);
4142 // gep (gep V, C), (xor V, -1) -> C-1
4143 if (match(Ops.back(),
4144 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
4145 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4146 return ConstantExpr::getIntToPtr(CI, GEPTy);
4151 // Check to see if this is constant foldable.
4152 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4153 return nullptr;
4155 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4156 Ops.slice(1));
4157 if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
4158 return CEFolded;
4159 return CE;
4162 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
4163 const SimplifyQuery &Q) {
4164 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
4167 /// Given operands for an InsertValueInst, see if we can fold the result.
4168 /// If not, this returns null.
4169 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
4170 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4171 unsigned) {
4172 if (Constant *CAgg = dyn_cast<Constant>(Agg))
4173 if (Constant *CVal = dyn_cast<Constant>(Val))
4174 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4176 // insertvalue x, undef, n -> x
4177 if (match(Val, m_Undef()))
4178 return Agg;
4180 // insertvalue x, (extractvalue y, n), n
4181 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4182 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4183 EV->getIndices() == Idxs) {
4184 // insertvalue undef, (extractvalue y, n), n -> y
4185 if (match(Agg, m_Undef()))
4186 return EV->getAggregateOperand();
4188 // insertvalue y, (extractvalue y, n), n -> y
4189 if (Agg == EV->getAggregateOperand())
4190 return Agg;
4193 return nullptr;
4196 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4197 ArrayRef<unsigned> Idxs,
4198 const SimplifyQuery &Q) {
4199 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4202 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4203 const SimplifyQuery &Q) {
4204 // Try to constant fold.
4205 auto *VecC = dyn_cast<Constant>(Vec);
4206 auto *ValC = dyn_cast<Constant>(Val);
4207 auto *IdxC = dyn_cast<Constant>(Idx);
4208 if (VecC && ValC && IdxC)
4209 return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
4211 // Fold into undef if index is out of bounds.
4212 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4213 uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
4214 if (CI->uge(NumElements))
4215 return UndefValue::get(Vec->getType());
4218 // If index is undef, it might be out of bounds (see above case)
4219 if (isa<UndefValue>(Idx))
4220 return UndefValue::get(Vec->getType());
4222 return nullptr;
4225 /// Given operands for an ExtractValueInst, see if we can fold the result.
4226 /// If not, this returns null.
4227 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4228 const SimplifyQuery &, unsigned) {
4229 if (auto *CAgg = dyn_cast<Constant>(Agg))
4230 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4232 // extractvalue x, (insertvalue y, elt, n), n -> elt
4233 unsigned NumIdxs = Idxs.size();
4234 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4235 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4236 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4237 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4238 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4239 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4240 Idxs.slice(0, NumCommonIdxs)) {
4241 if (NumIdxs == NumInsertValueIdxs)
4242 return IVI->getInsertedValueOperand();
4243 break;
4247 return nullptr;
4250 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
4251 const SimplifyQuery &Q) {
4252 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4255 /// Given operands for an ExtractElementInst, see if we can fold the result.
4256 /// If not, this returns null.
4257 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
4258 unsigned) {
4259 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4260 if (auto *CIdx = dyn_cast<Constant>(Idx))
4261 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4263 // The index is not relevant if our vector is a splat.
4264 if (auto *Splat = CVec->getSplatValue())
4265 return Splat;
4267 if (isa<UndefValue>(Vec))
4268 return UndefValue::get(Vec->getType()->getVectorElementType());
4271 // If extracting a specified index from the vector, see if we can recursively
4272 // find a previously computed scalar that was inserted into the vector.
4273 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4274 if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4275 // definitely out of bounds, thus undefined result
4276 return UndefValue::get(Vec->getType()->getVectorElementType());
4277 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4278 return Elt;
4281 // An undef extract index can be arbitrarily chosen to be an out-of-range
4282 // index value, which would result in the instruction being undef.
4283 if (isa<UndefValue>(Idx))
4284 return UndefValue::get(Vec->getType()->getVectorElementType());
4286 return nullptr;
4289 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4290 const SimplifyQuery &Q) {
4291 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4294 /// See if we can fold the given phi. If not, returns null.
4295 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4296 // If all of the PHI's incoming values are the same then replace the PHI node
4297 // with the common value.
4298 Value *CommonValue = nullptr;
4299 bool HasUndefInput = false;
4300 for (Value *Incoming : PN->incoming_values()) {
4301 // If the incoming value is the phi node itself, it can safely be skipped.
4302 if (Incoming == PN) continue;
4303 if (isa<UndefValue>(Incoming)) {
4304 // Remember that we saw an undef value, but otherwise ignore them.
4305 HasUndefInput = true;
4306 continue;
4308 if (CommonValue && Incoming != CommonValue)
4309 return nullptr; // Not the same, bail out.
4310 CommonValue = Incoming;
4313 // If CommonValue is null then all of the incoming values were either undef or
4314 // equal to the phi node itself.
4315 if (!CommonValue)
4316 return UndefValue::get(PN->getType());
4318 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4319 // instruction, we cannot return X as the result of the PHI node unless it
4320 // dominates the PHI block.
4321 if (HasUndefInput)
4322 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4324 return CommonValue;
4327 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4328 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4329 if (auto *C = dyn_cast<Constant>(Op))
4330 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4332 if (auto *CI = dyn_cast<CastInst>(Op)) {
4333 auto *Src = CI->getOperand(0);
4334 Type *SrcTy = Src->getType();
4335 Type *MidTy = CI->getType();
4336 Type *DstTy = Ty;
4337 if (Src->getType() == Ty) {
4338 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4339 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4340 Type *SrcIntPtrTy =
4341 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4342 Type *MidIntPtrTy =
4343 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4344 Type *DstIntPtrTy =
4345 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4346 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4347 SrcIntPtrTy, MidIntPtrTy,
4348 DstIntPtrTy) == Instruction::BitCast)
4349 return Src;
4353 // bitcast x -> x
4354 if (CastOpc == Instruction::BitCast)
4355 if (Op->getType() == Ty)
4356 return Op;
4358 return nullptr;
4361 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4362 const SimplifyQuery &Q) {
4363 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4366 /// For the given destination element of a shuffle, peek through shuffles to
4367 /// match a root vector source operand that contains that element in the same
4368 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4369 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4370 int MaskVal, Value *RootVec,
4371 unsigned MaxRecurse) {
4372 if (!MaxRecurse--)
4373 return nullptr;
4375 // Bail out if any mask value is undefined. That kind of shuffle may be
4376 // simplified further based on demanded bits or other folds.
4377 if (MaskVal == -1)
4378 return nullptr;
4380 // The mask value chooses which source operand we need to look at next.
4381 int InVecNumElts = Op0->getType()->getVectorNumElements();
4382 int RootElt = MaskVal;
4383 Value *SourceOp = Op0;
4384 if (MaskVal >= InVecNumElts) {
4385 RootElt = MaskVal - InVecNumElts;
4386 SourceOp = Op1;
4389 // If the source operand is a shuffle itself, look through it to find the
4390 // matching root vector.
4391 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4392 return foldIdentityShuffles(
4393 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4394 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4397 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4398 // size?
4400 // The source operand is not a shuffle. Initialize the root vector value for
4401 // this shuffle if that has not been done yet.
4402 if (!RootVec)
4403 RootVec = SourceOp;
4405 // Give up as soon as a source operand does not match the existing root value.
4406 if (RootVec != SourceOp)
4407 return nullptr;
4409 // The element must be coming from the same lane in the source vector
4410 // (although it may have crossed lanes in intermediate shuffles).
4411 if (RootElt != DestElt)
4412 return nullptr;
4414 return RootVec;
4417 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4418 Type *RetTy, const SimplifyQuery &Q,
4419 unsigned MaxRecurse) {
4420 if (isa<UndefValue>(Mask))
4421 return UndefValue::get(RetTy);
4423 Type *InVecTy = Op0->getType();
4424 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4425 unsigned InVecNumElts = InVecTy->getVectorNumElements();
4427 SmallVector<int, 32> Indices;
4428 ShuffleVectorInst::getShuffleMask(Mask, Indices);
4429 assert(MaskNumElts == Indices.size() &&
4430 "Size of Indices not same as number of mask elements?");
4432 // Canonicalization: If mask does not select elements from an input vector,
4433 // replace that input vector with undef.
4434 bool MaskSelects0 = false, MaskSelects1 = false;
4435 for (unsigned i = 0; i != MaskNumElts; ++i) {
4436 if (Indices[i] == -1)
4437 continue;
4438 if ((unsigned)Indices[i] < InVecNumElts)
4439 MaskSelects0 = true;
4440 else
4441 MaskSelects1 = true;
4443 if (!MaskSelects0)
4444 Op0 = UndefValue::get(InVecTy);
4445 if (!MaskSelects1)
4446 Op1 = UndefValue::get(InVecTy);
4448 auto *Op0Const = dyn_cast<Constant>(Op0);
4449 auto *Op1Const = dyn_cast<Constant>(Op1);
4451 // If all operands are constant, constant fold the shuffle.
4452 if (Op0Const && Op1Const)
4453 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4455 // Canonicalization: if only one input vector is constant, it shall be the
4456 // second one.
4457 if (Op0Const && !Op1Const) {
4458 std::swap(Op0, Op1);
4459 ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
4462 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4463 // value type is same as the input vectors' type.
4464 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4465 if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4466 OpShuf->getMask()->getSplatValue())
4467 return Op0;
4469 // Don't fold a shuffle with undef mask elements. This may get folded in a
4470 // better way using demanded bits or other analysis.
4471 // TODO: Should we allow this?
4472 if (find(Indices, -1) != Indices.end())
4473 return nullptr;
4475 // Check if every element of this shuffle can be mapped back to the
4476 // corresponding element of a single root vector. If so, we don't need this
4477 // shuffle. This handles simple identity shuffles as well as chains of
4478 // shuffles that may widen/narrow and/or move elements across lanes and back.
4479 Value *RootVec = nullptr;
4480 for (unsigned i = 0; i != MaskNumElts; ++i) {
4481 // Note that recursion is limited for each vector element, so if any element
4482 // exceeds the limit, this will fail to simplify.
4483 RootVec =
4484 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4486 // We can't replace a widening/narrowing shuffle with one of its operands.
4487 if (!RootVec || RootVec->getType() != RetTy)
4488 return nullptr;
4490 return RootVec;
4493 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4494 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4495 Type *RetTy, const SimplifyQuery &Q) {
4496 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4499 static Constant *propagateNaN(Constant *In) {
4500 // If the input is a vector with undef elements, just return a default NaN.
4501 if (!In->isNaN())
4502 return ConstantFP::getNaN(In->getType());
4504 // Propagate the existing NaN constant when possible.
4505 // TODO: Should we quiet a signaling NaN?
4506 return In;
4509 static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4510 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4511 return ConstantFP::getNaN(Op0->getType());
4513 if (match(Op0, m_NaN()))
4514 return propagateNaN(cast<Constant>(Op0));
4515 if (match(Op1, m_NaN()))
4516 return propagateNaN(cast<Constant>(Op1));
4518 return nullptr;
4521 /// Given operands for an FAdd, see if we can fold the result. If not, this
4522 /// returns null.
4523 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4524 const SimplifyQuery &Q, unsigned MaxRecurse) {
4525 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4526 return C;
4528 if (Constant *C = simplifyFPBinop(Op0, Op1))
4529 return C;
4531 // fadd X, -0 ==> X
4532 if (match(Op1, m_NegZeroFP()))
4533 return Op0;
4535 // fadd X, 0 ==> X, when we know X is not -0
4536 if (match(Op1, m_PosZeroFP()) &&
4537 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4538 return Op0;
4540 // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant)
4541 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4542 // Negative zeros are allowed because we always end up with positive zero:
4543 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4544 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4545 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4546 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4547 if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4548 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))))
4549 return ConstantFP::getNullValue(Op0->getType());
4551 // (X - Y) + Y --> X
4552 // Y + (X - Y) --> X
4553 Value *X;
4554 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4555 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4556 match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4557 return X;
4559 return nullptr;
4562 /// Given operands for an FSub, see if we can fold the result. If not, this
4563 /// returns null.
4564 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4565 const SimplifyQuery &Q, unsigned MaxRecurse) {
4566 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4567 return C;
4569 if (Constant *C = simplifyFPBinop(Op0, Op1))
4570 return C;
4572 // fsub X, +0 ==> X
4573 if (match(Op1, m_PosZeroFP()))
4574 return Op0;
4576 // fsub X, -0 ==> X, when we know X is not -0
4577 if (match(Op1, m_NegZeroFP()) &&
4578 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4579 return Op0;
4581 // fsub -0.0, (fsub -0.0, X) ==> X
4582 Value *X;
4583 if (match(Op0, m_NegZeroFP()) &&
4584 match(Op1, m_FSub(m_NegZeroFP(), m_Value(X))))
4585 return X;
4587 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4588 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4589 match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))))
4590 return X;
4592 // fsub nnan x, x ==> 0.0
4593 if (FMF.noNaNs() && Op0 == Op1)
4594 return Constant::getNullValue(Op0->getType());
4596 // Y - (Y - X) --> X
4597 // (X + Y) - Y --> X
4598 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4599 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4600 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4601 return X;
4603 return nullptr;
4606 /// Given the operands for an FMul, see if we can fold the result
4607 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4608 const SimplifyQuery &Q, unsigned MaxRecurse) {
4609 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4610 return C;
4612 if (Constant *C = simplifyFPBinop(Op0, Op1))
4613 return C;
4615 // fmul X, 1.0 ==> X
4616 if (match(Op1, m_FPOne()))
4617 return Op0;
4619 // fmul nnan nsz X, 0 ==> 0
4620 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4621 return ConstantFP::getNullValue(Op0->getType());
4623 // sqrt(X) * sqrt(X) --> X, if we can:
4624 // 1. Remove the intermediate rounding (reassociate).
4625 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4626 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4627 Value *X;
4628 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4629 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4630 return X;
4632 return nullptr;
4635 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4636 const SimplifyQuery &Q) {
4637 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4641 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4642 const SimplifyQuery &Q) {
4643 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4646 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4647 const SimplifyQuery &Q) {
4648 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4651 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4652 const SimplifyQuery &Q, unsigned) {
4653 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4654 return C;
4656 if (Constant *C = simplifyFPBinop(Op0, Op1))
4657 return C;
4659 // X / 1.0 -> X
4660 if (match(Op1, m_FPOne()))
4661 return Op0;
4663 // 0 / X -> 0
4664 // Requires that NaNs are off (X could be zero) and signed zeroes are
4665 // ignored (X could be positive or negative, so the output sign is unknown).
4666 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4667 return ConstantFP::getNullValue(Op0->getType());
4669 if (FMF.noNaNs()) {
4670 // X / X -> 1.0 is legal when NaNs are ignored.
4671 // We can ignore infinities because INF/INF is NaN.
4672 if (Op0 == Op1)
4673 return ConstantFP::get(Op0->getType(), 1.0);
4675 // (X * Y) / Y --> X if we can reassociate to the above form.
4676 Value *X;
4677 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4678 return X;
4680 // -X / X -> -1.0 and
4681 // X / -X -> -1.0 are legal when NaNs are ignored.
4682 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4683 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4684 match(Op1, m_FNegNSZ(m_Specific(Op0))))
4685 return ConstantFP::get(Op0->getType(), -1.0);
4688 return nullptr;
4691 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4692 const SimplifyQuery &Q) {
4693 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4696 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4697 const SimplifyQuery &Q, unsigned) {
4698 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4699 return C;
4701 if (Constant *C = simplifyFPBinop(Op0, Op1))
4702 return C;
4704 // Unlike fdiv, the result of frem always matches the sign of the dividend.
4705 // The constant match may include undef elements in a vector, so return a full
4706 // zero constant as the result.
4707 if (FMF.noNaNs()) {
4708 // +0 % X -> 0
4709 if (match(Op0, m_PosZeroFP()))
4710 return ConstantFP::getNullValue(Op0->getType());
4711 // -0 % X -> -0
4712 if (match(Op0, m_NegZeroFP()))
4713 return ConstantFP::getNegativeZero(Op0->getType());
4716 return nullptr;
4719 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4720 const SimplifyQuery &Q) {
4721 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4724 //=== Helper functions for higher up the class hierarchy.
4726 /// Given operands for a BinaryOperator, see if we can fold the result.
4727 /// If not, this returns null.
4728 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4729 const SimplifyQuery &Q, unsigned MaxRecurse) {
4730 switch (Opcode) {
4731 case Instruction::Add:
4732 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4733 case Instruction::Sub:
4734 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4735 case Instruction::Mul:
4736 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4737 case Instruction::SDiv:
4738 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4739 case Instruction::UDiv:
4740 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4741 case Instruction::SRem:
4742 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4743 case Instruction::URem:
4744 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4745 case Instruction::Shl:
4746 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4747 case Instruction::LShr:
4748 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4749 case Instruction::AShr:
4750 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4751 case Instruction::And:
4752 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4753 case Instruction::Or:
4754 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4755 case Instruction::Xor:
4756 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4757 case Instruction::FAdd:
4758 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4759 case Instruction::FSub:
4760 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4761 case Instruction::FMul:
4762 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4763 case Instruction::FDiv:
4764 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4765 case Instruction::FRem:
4766 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4767 default:
4768 llvm_unreachable("Unexpected opcode");
4772 /// Given operands for a BinaryOperator, see if we can fold the result.
4773 /// If not, this returns null.
4774 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4775 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4776 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4777 const FastMathFlags &FMF, const SimplifyQuery &Q,
4778 unsigned MaxRecurse) {
4779 switch (Opcode) {
4780 case Instruction::FAdd:
4781 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4782 case Instruction::FSub:
4783 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4784 case Instruction::FMul:
4785 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
4786 case Instruction::FDiv:
4787 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
4788 default:
4789 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4793 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4794 const SimplifyQuery &Q) {
4795 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4798 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4799 FastMathFlags FMF, const SimplifyQuery &Q) {
4800 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4803 /// Given operands for a CmpInst, see if we can fold the result.
4804 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4805 const SimplifyQuery &Q, unsigned MaxRecurse) {
4806 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
4807 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
4808 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4811 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4812 const SimplifyQuery &Q) {
4813 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4816 static bool IsIdempotent(Intrinsic::ID ID) {
4817 switch (ID) {
4818 default: return false;
4820 // Unary idempotent: f(f(x)) = f(x)
4821 case Intrinsic::fabs:
4822 case Intrinsic::floor:
4823 case Intrinsic::ceil:
4824 case Intrinsic::trunc:
4825 case Intrinsic::rint:
4826 case Intrinsic::nearbyint:
4827 case Intrinsic::round:
4828 case Intrinsic::canonicalize:
4829 return true;
4833 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4834 const DataLayout &DL) {
4835 GlobalValue *PtrSym;
4836 APInt PtrOffset;
4837 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4838 return nullptr;
4840 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4841 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4842 Type *Int32PtrTy = Int32Ty->getPointerTo();
4843 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4845 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4846 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4847 return nullptr;
4849 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4850 if (OffsetInt % 4 != 0)
4851 return nullptr;
4853 Constant *C = ConstantExpr::getGetElementPtr(
4854 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4855 ConstantInt::get(Int64Ty, OffsetInt / 4));
4856 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4857 if (!Loaded)
4858 return nullptr;
4860 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4861 if (!LoadedCE)
4862 return nullptr;
4864 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4865 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4866 if (!LoadedCE)
4867 return nullptr;
4870 if (LoadedCE->getOpcode() != Instruction::Sub)
4871 return nullptr;
4873 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4874 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4875 return nullptr;
4876 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4878 Constant *LoadedRHS = LoadedCE->getOperand(1);
4879 GlobalValue *LoadedRHSSym;
4880 APInt LoadedRHSOffset;
4881 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4882 DL) ||
4883 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4884 return nullptr;
4886 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4889 static bool maskIsAllZeroOrUndef(Value *Mask) {
4890 auto *ConstMask = dyn_cast<Constant>(Mask);
4891 if (!ConstMask)
4892 return false;
4893 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4894 return true;
4895 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4896 ++I) {
4897 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4898 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4899 continue;
4900 return false;
4902 return true;
4905 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
4906 const SimplifyQuery &Q) {
4907 // Idempotent functions return the same result when called repeatedly.
4908 Intrinsic::ID IID = F->getIntrinsicID();
4909 if (IsIdempotent(IID))
4910 if (auto *II = dyn_cast<IntrinsicInst>(Op0))
4911 if (II->getIntrinsicID() == IID)
4912 return II;
4914 Value *X;
4915 switch (IID) {
4916 case Intrinsic::fabs:
4917 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
4918 break;
4919 case Intrinsic::bswap:
4920 // bswap(bswap(x)) -> x
4921 if (match(Op0, m_BSwap(m_Value(X)))) return X;
4922 break;
4923 case Intrinsic::bitreverse:
4924 // bitreverse(bitreverse(x)) -> x
4925 if (match(Op0, m_BitReverse(m_Value(X)))) return X;
4926 break;
4927 case Intrinsic::exp:
4928 // exp(log(x)) -> x
4929 if (Q.CxtI->hasAllowReassoc() &&
4930 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
4931 break;
4932 case Intrinsic::exp2:
4933 // exp2(log2(x)) -> x
4934 if (Q.CxtI->hasAllowReassoc() &&
4935 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
4936 break;
4937 case Intrinsic::log:
4938 // log(exp(x)) -> x
4939 if (Q.CxtI->hasAllowReassoc() &&
4940 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
4941 break;
4942 case Intrinsic::log2:
4943 // log2(exp2(x)) -> x
4944 if (Q.CxtI->hasAllowReassoc() &&
4945 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
4946 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
4947 m_Value(X))))) return X;
4948 break;
4949 case Intrinsic::log10:
4950 // log10(pow(10.0, x)) -> x
4951 if (Q.CxtI->hasAllowReassoc() &&
4952 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
4953 m_Value(X)))) return X;
4954 break;
4955 default:
4956 break;
4959 return nullptr;
4962 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
4963 const SimplifyQuery &Q) {
4964 Intrinsic::ID IID = F->getIntrinsicID();
4965 Type *ReturnType = F->getReturnType();
4966 switch (IID) {
4967 case Intrinsic::usub_with_overflow:
4968 case Intrinsic::ssub_with_overflow:
4969 // X - X -> { 0, false }
4970 if (Op0 == Op1)
4971 return Constant::getNullValue(ReturnType);
4972 // X - undef -> undef
4973 // undef - X -> undef
4974 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4975 return UndefValue::get(ReturnType);
4976 break;
4977 case Intrinsic::uadd_with_overflow:
4978 case Intrinsic::sadd_with_overflow:
4979 // X + undef -> undef
4980 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4981 return UndefValue::get(ReturnType);
4982 break;
4983 case Intrinsic::umul_with_overflow:
4984 case Intrinsic::smul_with_overflow:
4985 // 0 * X -> { 0, false }
4986 // X * 0 -> { 0, false }
4987 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
4988 return Constant::getNullValue(ReturnType);
4989 // undef * X -> { 0, false }
4990 // X * undef -> { 0, false }
4991 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4992 return Constant::getNullValue(ReturnType);
4993 break;
4994 case Intrinsic::uadd_sat:
4995 // sat(MAX + X) -> MAX
4996 // sat(X + MAX) -> MAX
4997 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
4998 return Constant::getAllOnesValue(ReturnType);
4999 LLVM_FALLTHROUGH;
5000 case Intrinsic::sadd_sat:
5001 // sat(X + undef) -> -1
5002 // sat(undef + X) -> -1
5003 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5004 // For signed: Assume undef is ~X, in which case X + ~X = -1.
5005 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
5006 return Constant::getAllOnesValue(ReturnType);
5008 // X + 0 -> X
5009 if (match(Op1, m_Zero()))
5010 return Op0;
5011 // 0 + X -> X
5012 if (match(Op0, m_Zero()))
5013 return Op1;
5014 break;
5015 case Intrinsic::usub_sat:
5016 // sat(0 - X) -> 0, sat(X - MAX) -> 0
5017 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5018 return Constant::getNullValue(ReturnType);
5019 LLVM_FALLTHROUGH;
5020 case Intrinsic::ssub_sat:
5021 // X - X -> 0, X - undef -> 0, undef - X -> 0
5022 if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
5023 return Constant::getNullValue(ReturnType);
5024 // X - 0 -> X
5025 if (match(Op1, m_Zero()))
5026 return Op0;
5027 break;
5028 case Intrinsic::load_relative:
5029 if (auto *C0 = dyn_cast<Constant>(Op0))
5030 if (auto *C1 = dyn_cast<Constant>(Op1))
5031 return SimplifyRelativeLoad(C0, C1, Q.DL);
5032 break;
5033 case Intrinsic::powi:
5034 if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5035 // powi(x, 0) -> 1.0
5036 if (Power->isZero())
5037 return ConstantFP::get(Op0->getType(), 1.0);
5038 // powi(x, 1) -> x
5039 if (Power->isOne())
5040 return Op0;
5042 break;
5043 case Intrinsic::maxnum:
5044 case Intrinsic::minnum:
5045 case Intrinsic::maximum:
5046 case Intrinsic::minimum: {
5047 // If the arguments are the same, this is a no-op.
5048 if (Op0 == Op1) return Op0;
5050 // If one argument is undef, return the other argument.
5051 if (match(Op0, m_Undef()))
5052 return Op1;
5053 if (match(Op1, m_Undef()))
5054 return Op0;
5056 // If one argument is NaN, return other or NaN appropriately.
5057 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5058 if (match(Op0, m_NaN()))
5059 return PropagateNaN ? Op0 : Op1;
5060 if (match(Op1, m_NaN()))
5061 return PropagateNaN ? Op1 : Op0;
5063 // Min/max of the same operation with common operand:
5064 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5065 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5066 if (M0->getIntrinsicID() == IID &&
5067 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5068 return Op0;
5069 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5070 if (M1->getIntrinsicID() == IID &&
5071 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5072 return Op1;
5074 // min(X, -Inf) --> -Inf (and commuted variant)
5075 // max(X, +Inf) --> +Inf (and commuted variant)
5076 bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
5077 const APFloat *C;
5078 if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
5079 C->isNegative() == UseNegInf) ||
5080 (match(Op1, m_APFloat(C)) && C->isInfinity() &&
5081 C->isNegative() == UseNegInf))
5082 return ConstantFP::getInfinity(ReturnType, UseNegInf);
5084 // TODO: minnum(nnan x, inf) -> x
5085 // TODO: minnum(nnan ninf x, flt_max) -> x
5086 // TODO: maxnum(nnan x, -inf) -> x
5087 // TODO: maxnum(nnan ninf x, -flt_max) -> x
5088 break;
5090 default:
5091 break;
5094 return nullptr;
5097 template <typename IterTy>
5098 static Value *simplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
5099 const SimplifyQuery &Q) {
5100 // Intrinsics with no operands have some kind of side effect. Don't simplify.
5101 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
5102 if (NumOperands == 0)
5103 return nullptr;
5105 Intrinsic::ID IID = F->getIntrinsicID();
5106 if (NumOperands == 1)
5107 return simplifyUnaryIntrinsic(F, ArgBegin[0], Q);
5109 if (NumOperands == 2)
5110 return simplifyBinaryIntrinsic(F, ArgBegin[0], ArgBegin[1], Q);
5112 // Handle intrinsics with 3 or more arguments.
5113 switch (IID) {
5114 case Intrinsic::masked_load: {
5115 Value *MaskArg = ArgBegin[2];
5116 Value *PassthruArg = ArgBegin[3];
5117 // If the mask is all zeros or undef, the "passthru" argument is the result.
5118 if (maskIsAllZeroOrUndef(MaskArg))
5119 return PassthruArg;
5120 return nullptr;
5122 case Intrinsic::fshl:
5123 case Intrinsic::fshr: {
5124 Value *Op0 = ArgBegin[0], *Op1 = ArgBegin[1], *ShAmtArg = ArgBegin[2];
5126 // If both operands are undef, the result is undef.
5127 if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
5128 return UndefValue::get(F->getReturnType());
5130 // If shift amount is undef, assume it is zero.
5131 if (match(ShAmtArg, m_Undef()))
5132 return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
5134 const APInt *ShAmtC;
5135 if (match(ShAmtArg, m_APInt(ShAmtC))) {
5136 // If there's effectively no shift, return the 1st arg or 2nd arg.
5137 // TODO: For vectors, we could check each element of a non-splat constant.
5138 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5139 if (ShAmtC->urem(BitWidth).isNullValue())
5140 return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
5142 return nullptr;
5144 default:
5145 return nullptr;
5149 template <typename IterTy>
5150 static Value *SimplifyCall(CallBase *Call, Value *V, IterTy ArgBegin,
5151 IterTy ArgEnd, const SimplifyQuery &Q,
5152 unsigned MaxRecurse) {
5153 Type *Ty = V->getType();
5154 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
5155 Ty = PTy->getElementType();
5156 FunctionType *FTy = cast<FunctionType>(Ty);
5158 // call undef -> undef
5159 // call null -> undef
5160 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
5161 return UndefValue::get(FTy->getReturnType());
5163 Function *F = dyn_cast<Function>(V);
5164 if (!F)
5165 return nullptr;
5167 if (F->isIntrinsic())
5168 if (Value *Ret = simplifyIntrinsic(F, ArgBegin, ArgEnd, Q))
5169 return Ret;
5171 if (!canConstantFoldCallTo(Call, F))
5172 return nullptr;
5174 SmallVector<Constant *, 4> ConstantArgs;
5175 ConstantArgs.reserve(ArgEnd - ArgBegin);
5176 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
5177 Constant *C = dyn_cast<Constant>(*I);
5178 if (!C)
5179 return nullptr;
5180 ConstantArgs.push_back(C);
5183 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
5186 Value *llvm::SimplifyCall(CallBase *Call, Value *V, User::op_iterator ArgBegin,
5187 User::op_iterator ArgEnd, const SimplifyQuery &Q) {
5188 return ::SimplifyCall(Call, V, ArgBegin, ArgEnd, Q, RecursionLimit);
5191 Value *llvm::SimplifyCall(CallBase *Call, Value *V, ArrayRef<Value *> Args,
5192 const SimplifyQuery &Q) {
5193 return ::SimplifyCall(Call, V, Args.begin(), Args.end(), Q, RecursionLimit);
5196 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5197 return ::SimplifyCall(Call, Call->getCalledValue(), Call->arg_begin(),
5198 Call->arg_end(), Q, RecursionLimit);
5201 /// See if we can compute a simplified version of this instruction.
5202 /// If not, this returns null.
5204 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
5205 OptimizationRemarkEmitter *ORE) {
5206 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
5207 Value *Result;
5209 switch (I->getOpcode()) {
5210 default:
5211 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
5212 break;
5213 case Instruction::FAdd:
5214 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
5215 I->getFastMathFlags(), Q);
5216 break;
5217 case Instruction::Add:
5218 Result =
5219 SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5220 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5221 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5222 break;
5223 case Instruction::FSub:
5224 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
5225 I->getFastMathFlags(), Q);
5226 break;
5227 case Instruction::Sub:
5228 Result =
5229 SimplifySubInst(I->getOperand(0), I->getOperand(1),
5230 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5231 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5232 break;
5233 case Instruction::FMul:
5234 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
5235 I->getFastMathFlags(), Q);
5236 break;
5237 case Instruction::Mul:
5238 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
5239 break;
5240 case Instruction::SDiv:
5241 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
5242 break;
5243 case Instruction::UDiv:
5244 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
5245 break;
5246 case Instruction::FDiv:
5247 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
5248 I->getFastMathFlags(), Q);
5249 break;
5250 case Instruction::SRem:
5251 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
5252 break;
5253 case Instruction::URem:
5254 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
5255 break;
5256 case Instruction::FRem:
5257 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
5258 I->getFastMathFlags(), Q);
5259 break;
5260 case Instruction::Shl:
5261 Result =
5262 SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5263 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5264 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
5265 break;
5266 case Instruction::LShr:
5267 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
5268 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5269 break;
5270 case Instruction::AShr:
5271 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
5272 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
5273 break;
5274 case Instruction::And:
5275 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
5276 break;
5277 case Instruction::Or:
5278 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
5279 break;
5280 case Instruction::Xor:
5281 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
5282 break;
5283 case Instruction::ICmp:
5284 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5285 I->getOperand(0), I->getOperand(1), Q);
5286 break;
5287 case Instruction::FCmp:
5288 Result =
5289 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5290 I->getOperand(1), I->getFastMathFlags(), Q);
5291 break;
5292 case Instruction::Select:
5293 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
5294 I->getOperand(2), Q);
5295 break;
5296 case Instruction::GetElementPtr: {
5297 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
5298 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
5299 Ops, Q);
5300 break;
5302 case Instruction::InsertValue: {
5303 InsertValueInst *IV = cast<InsertValueInst>(I);
5304 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5305 IV->getInsertedValueOperand(),
5306 IV->getIndices(), Q);
5307 break;
5309 case Instruction::InsertElement: {
5310 auto *IE = cast<InsertElementInst>(I);
5311 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5312 IE->getOperand(2), Q);
5313 break;
5315 case Instruction::ExtractValue: {
5316 auto *EVI = cast<ExtractValueInst>(I);
5317 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
5318 EVI->getIndices(), Q);
5319 break;
5321 case Instruction::ExtractElement: {
5322 auto *EEI = cast<ExtractElementInst>(I);
5323 Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5324 EEI->getIndexOperand(), Q);
5325 break;
5327 case Instruction::ShuffleVector: {
5328 auto *SVI = cast<ShuffleVectorInst>(I);
5329 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5330 SVI->getMask(), SVI->getType(), Q);
5331 break;
5333 case Instruction::PHI:
5334 Result = SimplifyPHINode(cast<PHINode>(I), Q);
5335 break;
5336 case Instruction::Call: {
5337 Result = SimplifyCall(cast<CallInst>(I), Q);
5338 break;
5340 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5341 #include "llvm/IR/Instruction.def"
5342 #undef HANDLE_CAST_INST
5343 Result =
5344 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
5345 break;
5346 case Instruction::Alloca:
5347 // No simplifications for Alloca and it can't be constant folded.
5348 Result = nullptr;
5349 break;
5352 // In general, it is possible for computeKnownBits to determine all bits in a
5353 // value even when the operands are not all constants.
5354 if (!Result && I->getType()->isIntOrIntVectorTy()) {
5355 KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
5356 if (Known.isConstant())
5357 Result = ConstantInt::get(I->getType(), Known.getConstant());
5360 /// If called on unreachable code, the above logic may report that the
5361 /// instruction simplified to itself. Make life easier for users by
5362 /// detecting that case here, returning a safe value instead.
5363 return Result == I ? UndefValue::get(I->getType()) : Result;
5366 /// Implementation of recursive simplification through an instruction's
5367 /// uses.
5369 /// This is the common implementation of the recursive simplification routines.
5370 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5371 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5372 /// instructions to process and attempt to simplify it using
5373 /// InstructionSimplify.
5375 /// This routine returns 'true' only when *it* simplifies something. The passed
5376 /// in simplified value does not count toward this.
5377 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
5378 const TargetLibraryInfo *TLI,
5379 const DominatorTree *DT,
5380 AssumptionCache *AC) {
5381 bool Simplified = false;
5382 SmallSetVector<Instruction *, 8> Worklist;
5383 const DataLayout &DL = I->getModule()->getDataLayout();
5385 // If we have an explicit value to collapse to, do that round of the
5386 // simplification loop by hand initially.
5387 if (SimpleV) {
5388 for (User *U : I->users())
5389 if (U != I)
5390 Worklist.insert(cast<Instruction>(U));
5392 // Replace the instruction with its simplified value.
5393 I->replaceAllUsesWith(SimpleV);
5395 // Gracefully handle edge cases where the instruction is not wired into any
5396 // parent block.
5397 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5398 !I->mayHaveSideEffects())
5399 I->eraseFromParent();
5400 } else {
5401 Worklist.insert(I);
5404 // Note that we must test the size on each iteration, the worklist can grow.
5405 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5406 I = Worklist[Idx];
5408 // See if this instruction simplifies.
5409 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
5410 if (!SimpleV)
5411 continue;
5413 Simplified = true;
5415 // Stash away all the uses of the old instruction so we can check them for
5416 // recursive simplifications after a RAUW. This is cheaper than checking all
5417 // uses of To on the recursive step in most cases.
5418 for (User *U : I->users())
5419 Worklist.insert(cast<Instruction>(U));
5421 // Replace the instruction with its simplified value.
5422 I->replaceAllUsesWith(SimpleV);
5424 // Gracefully handle edge cases where the instruction is not wired into any
5425 // parent block.
5426 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
5427 !I->mayHaveSideEffects())
5428 I->eraseFromParent();
5430 return Simplified;
5433 bool llvm::recursivelySimplifyInstruction(Instruction *I,
5434 const TargetLibraryInfo *TLI,
5435 const DominatorTree *DT,
5436 AssumptionCache *AC) {
5437 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
5440 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
5441 const TargetLibraryInfo *TLI,
5442 const DominatorTree *DT,
5443 AssumptionCache *AC) {
5444 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5445 assert(SimpleV && "Must provide a simplified value.");
5446 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
5449 namespace llvm {
5450 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5451 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5452 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5453 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5454 auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5455 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5456 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5457 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5460 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5461 const DataLayout &DL) {
5462 return {DL, &AR.TLI, &AR.DT, &AR.AC};
5465 template <class T, class... TArgs>
5466 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5467 Function &F) {
5468 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5469 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5470 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5471 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5473 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5474 Function &);