LLVM 20.0.0git
ConstraintElimination.cpp
Go to the documentation of this file.
1//===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
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// Eliminate conditions based on constraints collected from dominating
10// conditions.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Module.h"
34#include "llvm/IR/Verifier.h"
35#include "llvm/Pass.h"
37#include "llvm/Support/Debug.h"
42
43#include <cmath>
44#include <optional>
45#include <string>
46
47using namespace llvm;
48using namespace PatternMatch;
49
50#define DEBUG_TYPE "constraint-elimination"
51
52STATISTIC(NumCondsRemoved, "Number of instructions removed");
53DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
54 "Controls which conditions are eliminated");
55
57 MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
58 cl::desc("Maximum number of rows to keep in constraint system"));
59
61 "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
62 cl::desc("Dump IR to reproduce successful transformations."));
63
64static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
65static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
66
67// A helper to multiply 2 signed integers where overflowing is allowed.
68static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
69 int64_t Result;
70 MulOverflow(A, B, Result);
71 return Result;
72}
73
74// A helper to add 2 signed integers where overflowing is allowed.
75static int64_t addWithOverflow(int64_t A, int64_t B) {
76 int64_t Result;
77 AddOverflow(A, B, Result);
78 return Result;
79}
80
82 Instruction *UserI = cast<Instruction>(U.getUser());
83 if (auto *Phi = dyn_cast<PHINode>(UserI))
84 UserI = Phi->getIncomingBlock(U)->getTerminator();
85 return UserI;
86}
87
88namespace {
89/// Struct to express a condition of the form %Op0 Pred %Op1.
90struct ConditionTy {
91 CmpPredicate Pred;
92 Value *Op0 = nullptr;
93 Value *Op1 = nullptr;
94
95 ConditionTy() = default;
96 ConditionTy(CmpPredicate Pred, Value *Op0, Value *Op1)
97 : Pred(Pred), Op0(Op0), Op1(Op1) {}
98};
99
100/// Represents either
101/// * a condition that holds on entry to a block (=condition fact)
102/// * an assume (=assume fact)
103/// * a use of a compare instruction to simplify.
104/// It also tracks the Dominator DFS in and out numbers for each entry.
105struct FactOrCheck {
106 enum class EntryTy {
107 ConditionFact, /// A condition that holds on entry to a block.
108 InstFact, /// A fact that holds after Inst executed (e.g. an assume or
109 /// min/mix intrinsic.
110 InstCheck, /// An instruction to simplify (e.g. an overflow math
111 /// intrinsics).
112 UseCheck /// An use of a compare instruction to simplify.
113 };
114
115 union {
116 Instruction *Inst;
117 Use *U;
119 };
120
121 /// A pre-condition that must hold for the current fact to be added to the
122 /// system.
123 ConditionTy DoesHold;
124
125 unsigned NumIn;
126 unsigned NumOut;
127 EntryTy Ty;
128
129 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst)
130 : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
131 Ty(Ty) {}
132
133 FactOrCheck(DomTreeNode *DTN, Use *U)
134 : U(U), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
135 Ty(EntryTy::UseCheck) {}
136
137 FactOrCheck(DomTreeNode *DTN, CmpPredicate Pred, Value *Op0, Value *Op1,
138 ConditionTy Precond = {})
139 : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
140 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
141
142 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpPredicate Pred,
143 Value *Op0, Value *Op1,
144 ConditionTy Precond = {}) {
145 return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
146 }
147
148 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
149 return FactOrCheck(EntryTy::InstFact, DTN, Inst);
150 }
151
152 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
153 return FactOrCheck(DTN, U);
154 }
155
156 static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) {
157 return FactOrCheck(EntryTy::InstCheck, DTN, CI);
158 }
159
160 bool isCheck() const {
161 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
162 }
163
164 Instruction *getContextInst() const {
165 assert(!isConditionFact());
166 if (Ty == EntryTy::UseCheck)
167 return getContextInstForUse(*U);
168 return Inst;
169 }
170
171 Instruction *getInstructionToSimplify() const {
172 assert(isCheck());
173 if (Ty == EntryTy::InstCheck)
174 return Inst;
175 // The use may have been simplified to a constant already.
176 return dyn_cast<Instruction>(*U);
177 }
178
179 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
180};
181
182/// Keep state required to build worklist.
183struct State {
184 DominatorTree &DT;
185 LoopInfo &LI;
186 ScalarEvolution &SE;
188
189 State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE)
190 : DT(DT), LI(LI), SE(SE) {}
191
192 /// Process block \p BB and add known facts to work-list.
193 void addInfoFor(BasicBlock &BB);
194
195 /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
196 /// controlling the loop header.
197 void addInfoForInductions(BasicBlock &BB);
198
199 /// Returns true if we can add a known condition from BB to its successor
200 /// block Succ.
201 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
202 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
203 }
204};
205
206class ConstraintInfo;
207
208struct StackEntry {
209 unsigned NumIn;
210 unsigned NumOut;
211 bool IsSigned = false;
212 /// Variables that can be removed from the system once the stack entry gets
213 /// removed.
214 SmallVector<Value *, 2> ValuesToRelease;
215
216 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
217 SmallVector<Value *, 2> ValuesToRelease)
218 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
219 ValuesToRelease(ValuesToRelease) {}
220};
221
222struct ConstraintTy {
223 SmallVector<int64_t, 8> Coefficients;
224 SmallVector<ConditionTy, 2> Preconditions;
225
227
228 bool IsSigned = false;
229
230 ConstraintTy() = default;
231
232 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq,
233 bool IsNe)
234 : Coefficients(std::move(Coefficients)), IsSigned(IsSigned), IsEq(IsEq),
235 IsNe(IsNe) {}
236
237 unsigned size() const { return Coefficients.size(); }
238
239 unsigned empty() const { return Coefficients.empty(); }
240
241 /// Returns true if all preconditions for this list of constraints are
242 /// satisfied given \p CS and the corresponding \p Value2Index mapping.
243 bool isValid(const ConstraintInfo &Info) const;
244
245 bool isEq() const { return IsEq; }
246
247 bool isNe() const { return IsNe; }
248
249 /// Check if the current constraint is implied by the given ConstraintSystem.
250 ///
251 /// \return true or false if the constraint is proven to be respectively true,
252 /// or false. When the constraint cannot be proven to be either true or false,
253 /// std::nullopt is returned.
254 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
255
256private:
257 bool IsEq = false;
258 bool IsNe = false;
259};
260
261/// Wrapper encapsulating separate constraint systems and corresponding value
262/// mappings for both unsigned and signed information. Facts are added to and
263/// conditions are checked against the corresponding system depending on the
264/// signed-ness of their predicates. While the information is kept separate
265/// based on signed-ness, certain conditions can be transferred between the two
266/// systems.
267class ConstraintInfo {
268
269 ConstraintSystem UnsignedCS;
270 ConstraintSystem SignedCS;
271
272 const DataLayout &DL;
273
274public:
275 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
276 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
277 auto &Value2Index = getValue2Index(false);
278 // Add Arg > -1 constraints to unsigned system for all function arguments.
279 for (Value *Arg : FunctionArgs) {
280 ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
281 false, false, false);
282 VarPos.Coefficients[Value2Index[Arg]] = -1;
283 UnsignedCS.addVariableRow(VarPos.Coefficients);
284 }
285 }
286
287 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
288 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
289 }
290 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
291 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
292 }
293
294 ConstraintSystem &getCS(bool Signed) {
295 return Signed ? SignedCS : UnsignedCS;
296 }
297 const ConstraintSystem &getCS(bool Signed) const {
298 return Signed ? SignedCS : UnsignedCS;
299 }
300
301 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
302 void popLastNVariables(bool Signed, unsigned N) {
303 getCS(Signed).popLastNVariables(N);
304 }
305
306 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
307
308 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
309 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
310
311 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
312 /// constraints, using indices from the corresponding constraint system.
313 /// New variables that need to be added to the system are collected in
314 /// \p NewVariables.
315 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
316 SmallVectorImpl<Value *> &NewVariables) const;
317
318 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
319 /// constraints using getConstraint. Returns an empty constraint if the result
320 /// cannot be used to query the existing constraint system, e.g. because it
321 /// would require adding new variables. Also tries to convert signed
322 /// predicates to unsigned ones if possible to allow using the unsigned system
323 /// which increases the effectiveness of the signed <-> unsigned transfer
324 /// logic.
325 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
326 Value *Op1) const;
327
328 /// Try to add information from \p A \p Pred \p B to the unsigned/signed
329 /// system if \p Pred is signed/unsigned.
330 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
331 unsigned NumIn, unsigned NumOut,
332 SmallVectorImpl<StackEntry> &DFSInStack);
333};
334
335/// Represents a (Coefficient * Variable) entry after IR decomposition.
336struct DecompEntry {
337 int64_t Coefficient;
338 Value *Variable;
339 /// True if the variable is known positive in the current constraint.
340 bool IsKnownNonNegative;
341
342 DecompEntry(int64_t Coefficient, Value *Variable,
343 bool IsKnownNonNegative = false)
344 : Coefficient(Coefficient), Variable(Variable),
345 IsKnownNonNegative(IsKnownNonNegative) {}
346};
347
348/// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
349struct Decomposition {
350 int64_t Offset = 0;
352
353 Decomposition(int64_t Offset) : Offset(Offset) {}
354 Decomposition(Value *V, bool IsKnownNonNegative = false) {
355 Vars.emplace_back(1, V, IsKnownNonNegative);
356 }
357 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
358 : Offset(Offset), Vars(Vars) {}
359
360 void add(int64_t OtherOffset) {
361 Offset = addWithOverflow(Offset, OtherOffset);
362 }
363
364 void add(const Decomposition &Other) {
365 add(Other.Offset);
366 append_range(Vars, Other.Vars);
367 }
368
369 void sub(const Decomposition &Other) {
370 Decomposition Tmp = Other;
371 Tmp.mul(-1);
372 add(Tmp.Offset);
373 append_range(Vars, Tmp.Vars);
374 }
375
376 void mul(int64_t Factor) {
377 Offset = multiplyWithOverflow(Offset, Factor);
378 for (auto &Var : Vars)
379 Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
380 }
381};
382
383// Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
384struct OffsetResult {
385 Value *BasePtr;
386 APInt ConstantOffset;
387 SmallMapVector<Value *, APInt, 4> VariableOffsets;
389
390 OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
391
392 OffsetResult(GEPOperator &GEP, const DataLayout &DL)
393 : BasePtr(GEP.getPointerOperand()), NW(GEP.getNoWrapFlags()) {
394 ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
395 }
396};
397} // namespace
398
399// Try to collect variable and constant offsets for \p GEP, partly traversing
400// nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
401// the offset fails.
402static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL) {
403 OffsetResult Result(GEP, DL);
404 unsigned BitWidth = Result.ConstantOffset.getBitWidth();
405 if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
406 Result.ConstantOffset))
407 return {};
408
409 // If we have a nested GEP, check if we can combine the constant offset of the
410 // inner GEP with the outer GEP.
411 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
412 SmallMapVector<Value *, APInt, 4> VariableOffsets2;
413 APInt ConstantOffset2(BitWidth, 0);
414 bool CanCollectInner = InnerGEP->collectOffset(
415 DL, BitWidth, VariableOffsets2, ConstantOffset2);
416 // TODO: Support cases with more than 1 variable offset.
417 if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
418 VariableOffsets2.size() > 1 ||
419 (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
420 // More than 1 variable index, use outer result.
421 return Result;
422 }
423 Result.BasePtr = InnerGEP->getPointerOperand();
424 Result.ConstantOffset += ConstantOffset2;
425 if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
426 Result.VariableOffsets = VariableOffsets2;
427 Result.NW &= InnerGEP->getNoWrapFlags();
428 }
429 return Result;
430}
431
432static Decomposition decompose(Value *V,
433 SmallVectorImpl<ConditionTy> &Preconditions,
434 bool IsSigned, const DataLayout &DL);
435
436static bool canUseSExt(ConstantInt *CI) {
437 const APInt &Val = CI->getValue();
439}
440
441static Decomposition decomposeGEP(GEPOperator &GEP,
442 SmallVectorImpl<ConditionTy> &Preconditions,
443 bool IsSigned, const DataLayout &DL) {
444 // Do not reason about pointers where the index size is larger than 64 bits,
445 // as the coefficients used to encode constraints are 64 bit integers.
446 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
447 return &GEP;
448
449 assert(!IsSigned && "The logic below only supports decomposition for "
450 "unsigned predicates at the moment.");
451 const auto &[BasePtr, ConstantOffset, VariableOffsets, NW] =
453 // We support either plain gep nuw, or gep nusw with non-negative offset,
454 // which implies gep nuw.
455 if (!BasePtr || NW == GEPNoWrapFlags::none())
456 return &GEP;
457
458 Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
459 for (auto [Index, Scale] : VariableOffsets) {
460 auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
461 IdxResult.mul(Scale.getSExtValue());
462 Result.add(IdxResult);
463
464 if (!NW.hasNoUnsignedWrap()) {
465 // Try to prove nuw from nusw and nneg.
466 assert(NW.hasNoUnsignedSignedWrap() && "Must have nusw flag");
467 if (!isKnownNonNegative(Index, DL))
468 Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
469 ConstantInt::get(Index->getType(), 0));
470 }
471 }
472 return Result;
473}
474
475// Decomposes \p V into a constant offset + list of pairs { Coefficient,
476// Variable } where Coefficient * Variable. The sum of the constant offset and
477// pairs equals \p V.
478static Decomposition decompose(Value *V,
479 SmallVectorImpl<ConditionTy> &Preconditions,
480 bool IsSigned, const DataLayout &DL) {
481
482 auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
483 bool IsSignedB) {
484 auto ResA = decompose(A, Preconditions, IsSigned, DL);
485 auto ResB = decompose(B, Preconditions, IsSignedB, DL);
486 ResA.add(ResB);
487 return ResA;
488 };
489
490 Type *Ty = V->getType()->getScalarType();
491 if (Ty->isPointerTy() && !IsSigned) {
492 if (auto *GEP = dyn_cast<GEPOperator>(V))
493 return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
494 if (isa<ConstantPointerNull>(V))
495 return int64_t(0);
496
497 return V;
498 }
499
500 // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
501 // coefficient add/mul may wrap, while the operation in the full bit width
502 // would not.
503 if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
504 return V;
505
506 bool IsKnownNonNegative = false;
507
508 // Decompose \p V used with a signed predicate.
509 if (IsSigned) {
510 if (auto *CI = dyn_cast<ConstantInt>(V)) {
511 if (canUseSExt(CI))
512 return CI->getSExtValue();
513 }
514 Value *Op0;
515 Value *Op1;
516
517 if (match(V, m_SExt(m_Value(Op0))))
518 V = Op0;
519 else if (match(V, m_NNegZExt(m_Value(Op0)))) {
520 V = Op0;
521 IsKnownNonNegative = true;
522 } else if (match(V, m_NSWTrunc(m_Value(Op0)))) {
523 if (Op0->getType()->getScalarSizeInBits() <= 64)
524 V = Op0;
525 }
526
527 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
528 return MergeResults(Op0, Op1, IsSigned);
529
530 if (match(V, m_NSWSub(m_Value(Op0), m_Value(Op1)))) {
531 auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
532 auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
533 ResA.sub(ResB);
534 return ResA;
535 }
536
537 ConstantInt *CI;
538 if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
539 auto Result = decompose(Op0, Preconditions, IsSigned, DL);
540 Result.mul(CI->getSExtValue());
541 return Result;
542 }
543
544 // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of
545 // shift == bw-1.
546 if (match(V, m_NSWShl(m_Value(Op0), m_ConstantInt(CI)))) {
547 uint64_t Shift = CI->getValue().getLimitedValue();
548 if (Shift < Ty->getIntegerBitWidth() - 1) {
549 assert(Shift < 64 && "Would overflow");
550 auto Result = decompose(Op0, Preconditions, IsSigned, DL);
551 Result.mul(int64_t(1) << Shift);
552 return Result;
553 }
554 }
555
556 return {V, IsKnownNonNegative};
557 }
558
559 if (auto *CI = dyn_cast<ConstantInt>(V)) {
560 if (CI->uge(MaxConstraintValue))
561 return V;
562 return int64_t(CI->getZExtValue());
563 }
564
565 Value *Op0;
566 if (match(V, m_ZExt(m_Value(Op0)))) {
567 IsKnownNonNegative = true;
568 V = Op0;
569 } else if (match(V, m_SExt(m_Value(Op0)))) {
570 V = Op0;
571 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
572 ConstantInt::get(Op0->getType(), 0));
573 } else if (auto *Trunc = dyn_cast<TruncInst>(V)) {
574 if (Trunc->getSrcTy()->getScalarSizeInBits() <= 64) {
575 if (Trunc->hasNoUnsignedWrap() || Trunc->hasNoSignedWrap()) {
576 V = Trunc->getOperand(0);
577 if (!Trunc->hasNoUnsignedWrap())
578 Preconditions.emplace_back(CmpInst::ICMP_SGE, V,
579 ConstantInt::get(V->getType(), 0));
580 }
581 }
582 }
583
584 Value *Op1;
585 ConstantInt *CI;
586 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
587 return MergeResults(Op0, Op1, IsSigned);
588 }
589 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
590 if (!isKnownNonNegative(Op0, DL))
591 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
592 ConstantInt::get(Op0->getType(), 0));
593 if (!isKnownNonNegative(Op1, DL))
594 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
595 ConstantInt::get(Op1->getType(), 0));
596
597 return MergeResults(Op0, Op1, IsSigned);
598 }
599
600 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
601 canUseSExt(CI)) {
602 Preconditions.emplace_back(
604 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
605 return MergeResults(Op0, CI, true);
606 }
607
608 // Decompose or as an add if there are no common bits between the operands.
609 if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI))))
610 return MergeResults(Op0, CI, IsSigned);
611
612 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
613 if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
614 return {V, IsKnownNonNegative};
615 auto Result = decompose(Op1, Preconditions, IsSigned, DL);
616 Result.mul(int64_t{1} << CI->getSExtValue());
617 return Result;
618 }
619
620 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
621 (!CI->isNegative())) {
622 auto Result = decompose(Op1, Preconditions, IsSigned, DL);
623 Result.mul(CI->getSExtValue());
624 return Result;
625 }
626
627 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) {
628 auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
629 auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
630 ResA.sub(ResB);
631 return ResA;
632 }
633
634 return {V, IsKnownNonNegative};
635}
636
637ConstraintTy
638ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
639 SmallVectorImpl<Value *> &NewVariables) const {
640 assert(NewVariables.empty() && "NewVariables must be empty when passed in");
641 bool IsEq = false;
642 bool IsNe = false;
643
644 // Try to convert Pred to one of ULE/SLT/SLE/SLT.
645 switch (Pred) {
649 case CmpInst::ICMP_SGE: {
650 Pred = CmpInst::getSwappedPredicate(Pred);
651 std::swap(Op0, Op1);
652 break;
653 }
654 case CmpInst::ICMP_EQ:
655 if (match(Op1, m_Zero())) {
656 Pred = CmpInst::ICMP_ULE;
657 } else {
658 IsEq = true;
659 Pred = CmpInst::ICMP_ULE;
660 }
661 break;
662 case CmpInst::ICMP_NE:
663 if (match(Op1, m_Zero())) {
665 std::swap(Op0, Op1);
666 } else {
667 IsNe = true;
668 Pred = CmpInst::ICMP_ULE;
669 }
670 break;
671 default:
672 break;
673 }
674
675 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
676 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
677 return {};
678
679 SmallVector<ConditionTy, 4> Preconditions;
680 bool IsSigned = CmpInst::isSigned(Pred);
681 auto &Value2Index = getValue2Index(IsSigned);
683 Preconditions, IsSigned, DL);
685 Preconditions, IsSigned, DL);
686 int64_t Offset1 = ADec.Offset;
687 int64_t Offset2 = BDec.Offset;
688 Offset1 *= -1;
689
690 auto &VariablesA = ADec.Vars;
691 auto &VariablesB = BDec.Vars;
692
693 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
694 // new entry to NewVariables.
696 auto GetOrAddIndex = [&Value2Index, &NewVariables,
697 &NewIndexMap](Value *V) -> unsigned {
698 auto V2I = Value2Index.find(V);
699 if (V2I != Value2Index.end())
700 return V2I->second;
701 auto Insert =
702 NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
703 if (Insert.second)
704 NewVariables.push_back(V);
705 return Insert.first->second;
706 };
707
708 // Make sure all variables have entries in Value2Index or NewVariables.
709 for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
710 GetOrAddIndex(KV.Variable);
711
712 // Build result constraint, by first adding all coefficients from A and then
713 // subtracting all coefficients from B.
714 ConstraintTy Res(
715 SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
716 IsSigned, IsEq, IsNe);
717 // Collect variables that are known to be positive in all uses in the
718 // constraint.
719 SmallDenseMap<Value *, bool> KnownNonNegativeVariables;
720 auto &R = Res.Coefficients;
721 for (const auto &KV : VariablesA) {
722 R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
723 auto I =
724 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
725 I.first->second &= KV.IsKnownNonNegative;
726 }
727
728 for (const auto &KV : VariablesB) {
729 if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
730 R[GetOrAddIndex(KV.Variable)]))
731 return {};
732 auto I =
733 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
734 I.first->second &= KV.IsKnownNonNegative;
735 }
736
737 int64_t OffsetSum;
738 if (AddOverflow(Offset1, Offset2, OffsetSum))
739 return {};
740 if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
741 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
742 return {};
743 R[0] = OffsetSum;
744 Res.Preconditions = std::move(Preconditions);
745
746 // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
747 // variables.
748 while (!NewVariables.empty()) {
749 int64_t Last = R.back();
750 if (Last != 0)
751 break;
752 R.pop_back();
753 Value *RemovedV = NewVariables.pop_back_val();
754 NewIndexMap.erase(RemovedV);
755 }
756
757 // Add extra constraints for variables that are known positive.
758 for (auto &KV : KnownNonNegativeVariables) {
759 if (!KV.second ||
760 (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
761 continue;
762 SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
763 C[GetOrAddIndex(KV.first)] = -1;
764 Res.ExtraInfo.push_back(C);
765 }
766 return Res;
767}
768
769ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
770 Value *Op0,
771 Value *Op1) const {
772 Constant *NullC = Constant::getNullValue(Op0->getType());
773 // Handle trivially true compares directly to avoid adding V UGE 0 constraints
774 // for all variables in the unsigned system.
775 if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
776 (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
777 auto &Value2Index = getValue2Index(false);
778 // Return constraint that's trivially true.
779 return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
780 false, false);
781 }
782
783 // If both operands are known to be non-negative, change signed predicates to
784 // unsigned ones. This increases the reasoning effectiveness in combination
785 // with the signed <-> unsigned transfer logic.
786 if (CmpInst::isSigned(Pred) &&
787 isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
790
791 SmallVector<Value *> NewVariables;
792 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
793 if (!NewVariables.empty())
794 return {};
795 return R;
796}
797
798bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
799 return Coefficients.size() > 0 &&
800 all_of(Preconditions, [&Info](const ConditionTy &C) {
801 return Info.doesHold(C.Pred, C.Op0, C.Op1);
802 });
803}
804
805std::optional<bool>
806ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
807 bool IsConditionImplied = CS.isConditionImplied(Coefficients);
808
809 if (IsEq || IsNe) {
810 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
811 bool IsNegatedOrEqualImplied =
812 !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
813
814 // In order to check that `%a == %b` is true (equality), both conditions `%a
815 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
816 // is true), we return true if they both hold, false in the other cases.
817 if (IsConditionImplied && IsNegatedOrEqualImplied)
818 return IsEq;
819
820 auto Negated = ConstraintSystem::negate(Coefficients);
821 bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
822
823 auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
824 bool IsStrictLessThanImplied =
825 !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
826
827 // In order to check that `%a != %b` is true (non-equality), either
828 // condition `%a > %b` or `%a < %b` must hold true. When checking for
829 // non-equality (`IsNe` is true), we return true if one of the two holds,
830 // false in the other cases.
831 if (IsNegatedImplied || IsStrictLessThanImplied)
832 return IsNe;
833
834 return std::nullopt;
835 }
836
837 if (IsConditionImplied)
838 return true;
839
840 auto Negated = ConstraintSystem::negate(Coefficients);
841 auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
842 if (IsNegatedImplied)
843 return false;
844
845 // Neither the condition nor its negated holds, did not prove anything.
846 return std::nullopt;
847}
848
849bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
850 Value *B) const {
851 auto R = getConstraintForSolving(Pred, A, B);
852 return R.isValid(*this) &&
853 getCS(R.IsSigned).isConditionImplied(R.Coefficients);
854}
855
856void ConstraintInfo::transferToOtherSystem(
857 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
858 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
859 auto IsKnownNonNegative = [this](Value *V) {
860 return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
862 };
863 // Check if we can combine facts from the signed and unsigned systems to
864 // derive additional facts.
865 if (!A->getType()->isIntegerTy())
866 return;
867 // FIXME: This currently depends on the order we add facts. Ideally we
868 // would first add all known facts and only then try to add additional
869 // facts.
870 switch (Pred) {
871 default:
872 break;
875 // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
876 if (IsKnownNonNegative(B)) {
877 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
878 NumOut, DFSInStack);
879 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
880 DFSInStack);
881 }
882 break;
885 // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
886 if (IsKnownNonNegative(A)) {
887 addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
888 NumOut, DFSInStack);
889 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
890 DFSInStack);
891 }
892 break;
894 if (IsKnownNonNegative(A))
895 addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
896 break;
897 case CmpInst::ICMP_SGT: {
898 if (doesHold(CmpInst::ICMP_SGE, B, Constant::getAllOnesValue(B->getType())))
899 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
900 NumOut, DFSInStack);
901 if (IsKnownNonNegative(B))
902 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
903
904 break;
905 }
907 if (IsKnownNonNegative(B))
908 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
909 break;
910 }
911}
912
913#ifndef NDEBUG
914
916 const DenseMap<Value *, unsigned> &Value2Index) {
917 ConstraintSystem CS(Value2Index);
919 CS.dump();
920}
921#endif
922
923void State::addInfoForInductions(BasicBlock &BB) {
924 auto *L = LI.getLoopFor(&BB);
925 if (!L || L->getHeader() != &BB)
926 return;
927
928 Value *A;
929 Value *B;
930 CmpPredicate Pred;
931
932 if (!match(BB.getTerminator(),
933 m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
934 return;
935 PHINode *PN = dyn_cast<PHINode>(A);
936 if (!PN) {
937 Pred = CmpInst::getSwappedPredicate(Pred);
938 std::swap(A, B);
939 PN = dyn_cast<PHINode>(A);
940 }
941
942 if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
943 !SE.isSCEVable(PN->getType()))
944 return;
945
946 BasicBlock *InLoopSucc = nullptr;
947 if (Pred == CmpInst::ICMP_NE)
948 InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
949 else if (Pred == CmpInst::ICMP_EQ)
950 InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
951 else
952 return;
953
954 if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
955 return;
956
957 auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
958 BasicBlock *LoopPred = L->getLoopPredecessor();
959 if (!AR || AR->getLoop() != L || !LoopPred)
960 return;
961
962 const SCEV *StartSCEV = AR->getStart();
963 Value *StartValue = nullptr;
964 if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
965 StartValue = C->getValue();
966 } else {
967 StartValue = PN->getIncomingValueForBlock(LoopPred);
968 assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
969 }
970
971 DomTreeNode *DTN = DT.getNode(InLoopSucc);
972 auto IncUnsigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
973 auto IncSigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_SGT);
974 bool MonotonicallyIncreasingUnsigned =
975 IncUnsigned && *IncUnsigned == ScalarEvolution::MonotonicallyIncreasing;
976 bool MonotonicallyIncreasingSigned =
977 IncSigned && *IncSigned == ScalarEvolution::MonotonicallyIncreasing;
978 // If SCEV guarantees that AR does not wrap, PN >= StartValue can be added
979 // unconditionally.
980 if (MonotonicallyIncreasingUnsigned)
981 WorkList.push_back(
982 FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
983 if (MonotonicallyIncreasingSigned)
984 WorkList.push_back(
985 FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGE, PN, StartValue));
986
987 APInt StepOffset;
988 if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
989 StepOffset = C->getAPInt();
990 else
991 return;
992
993 // Make sure the bound B is loop-invariant.
994 if (!L->isLoopInvariant(B))
995 return;
996
997 // Handle negative steps.
998 if (StepOffset.isNegative()) {
999 // TODO: Extend to allow steps > -1.
1000 if (!(-StepOffset).isOne())
1001 return;
1002
1003 // AR may wrap.
1004 // Add StartValue >= PN conditional on B <= StartValue which guarantees that
1005 // the loop exits before wrapping with a step of -1.
1006 WorkList.push_back(FactOrCheck::getConditionFact(
1007 DTN, CmpInst::ICMP_UGE, StartValue, PN,
1008 ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
1009 WorkList.push_back(FactOrCheck::getConditionFact(
1010 DTN, CmpInst::ICMP_SGE, StartValue, PN,
1011 ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
1012 // Add PN > B conditional on B <= StartValue which guarantees that the loop
1013 // exits when reaching B with a step of -1.
1014 WorkList.push_back(FactOrCheck::getConditionFact(
1015 DTN, CmpInst::ICMP_UGT, PN, B,
1016 ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
1017 WorkList.push_back(FactOrCheck::getConditionFact(
1018 DTN, CmpInst::ICMP_SGT, PN, B,
1019 ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
1020 return;
1021 }
1022
1023 // Make sure AR either steps by 1 or that the value we compare against is a
1024 // GEP based on the same start value and all offsets are a multiple of the
1025 // step size, to guarantee that the induction will reach the value.
1026 if (StepOffset.isZero() || StepOffset.isNegative())
1027 return;
1028
1029 if (!StepOffset.isOne()) {
1030 // Check whether B-Start is known to be a multiple of StepOffset.
1031 const SCEV *BMinusStart = SE.getMinusSCEV(SE.getSCEV(B), StartSCEV);
1032 if (isa<SCEVCouldNotCompute>(BMinusStart) ||
1033 !SE.getConstantMultiple(BMinusStart).urem(StepOffset).isZero())
1034 return;
1035 }
1036
1037 // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
1038 // guarantees that the loop exits before wrapping in combination with the
1039 // restrictions on B and the step above.
1040 if (!MonotonicallyIncreasingUnsigned)
1041 WorkList.push_back(FactOrCheck::getConditionFact(
1042 DTN, CmpInst::ICMP_UGE, PN, StartValue,
1043 ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
1044 if (!MonotonicallyIncreasingSigned)
1045 WorkList.push_back(FactOrCheck::getConditionFact(
1046 DTN, CmpInst::ICMP_SGE, PN, StartValue,
1047 ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
1048
1049 WorkList.push_back(FactOrCheck::getConditionFact(
1050 DTN, CmpInst::ICMP_ULT, PN, B,
1051 ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
1052 WorkList.push_back(FactOrCheck::getConditionFact(
1053 DTN, CmpInst::ICMP_SLT, PN, B,
1054 ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
1055
1056 // Try to add condition from header to the dedicated exit blocks. When exiting
1057 // either with EQ or NE in the header, we know that the induction value must
1058 // be u<= B, as other exits may only exit earlier.
1059 assert(!StepOffset.isNegative() && "induction must be increasing");
1060 assert((Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) &&
1061 "unsupported predicate");
1062 ConditionTy Precond = {CmpInst::ICMP_ULE, StartValue, B};
1064 L->getExitBlocks(ExitBBs);
1065 for (BasicBlock *EB : ExitBBs) {
1066 // Bail out on non-dedicated exits.
1067 if (DT.dominates(&BB, EB)) {
1068 WorkList.emplace_back(FactOrCheck::getConditionFact(
1069 DT.getNode(EB), CmpInst::ICMP_ULE, A, B, Precond));
1070 }
1071 }
1072}
1073
1074void State::addInfoFor(BasicBlock &BB) {
1075 addInfoForInductions(BB);
1076
1077 // True as long as long as the current instruction is guaranteed to execute.
1078 bool GuaranteedToExecute = true;
1079 // Queue conditions and assumes.
1080 for (Instruction &I : BB) {
1081 if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
1082 for (Use &U : Cmp->uses()) {
1083 auto *UserI = getContextInstForUse(U);
1084 auto *DTN = DT.getNode(UserI->getParent());
1085 if (!DTN)
1086 continue;
1087 WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1088 }
1089 continue;
1090 }
1091
1092 auto *II = dyn_cast<IntrinsicInst>(&I);
1093 Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1094 switch (ID) {
1095 case Intrinsic::assume: {
1096 Value *A, *B;
1097 CmpPredicate Pred;
1098 if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1099 break;
1100 if (GuaranteedToExecute) {
1101 // The assume is guaranteed to execute when BB is entered, hence Cond
1102 // holds on entry to BB.
1103 WorkList.emplace_back(FactOrCheck::getConditionFact(
1104 DT.getNode(I.getParent()), Pred, A, B));
1105 } else {
1106 WorkList.emplace_back(
1107 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1108 }
1109 break;
1110 }
1111 // Enqueue ssub_with_overflow for simplification.
1112 case Intrinsic::ssub_with_overflow:
1113 case Intrinsic::ucmp:
1114 case Intrinsic::scmp:
1115 WorkList.push_back(
1116 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1117 break;
1118 // Enqueue the intrinsics to add extra info.
1119 case Intrinsic::umin:
1120 case Intrinsic::umax:
1121 case Intrinsic::smin:
1122 case Intrinsic::smax:
1123 // TODO: handle llvm.abs as well
1124 WorkList.push_back(
1125 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1126 // TODO: Check if it is possible to instead only added the min/max facts
1127 // when simplifying uses of the min/max intrinsics.
1129 break;
1130 [[fallthrough]];
1131 case Intrinsic::abs:
1132 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1133 break;
1134 }
1135
1136 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1137 }
1138
1139 if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1140 for (auto &Case : Switch->cases()) {
1141 BasicBlock *Succ = Case.getCaseSuccessor();
1142 Value *V = Case.getCaseValue();
1143 if (!canAddSuccessor(BB, Succ))
1144 continue;
1145 WorkList.emplace_back(FactOrCheck::getConditionFact(
1146 DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1147 }
1148 return;
1149 }
1150
1151 auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1152 if (!Br || !Br->isConditional())
1153 return;
1154
1155 Value *Cond = Br->getCondition();
1156
1157 // If the condition is a chain of ORs/AND and the successor only has the
1158 // current block as predecessor, queue conditions for the successor.
1159 Value *Op0, *Op1;
1160 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1161 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1162 bool IsOr = match(Cond, m_LogicalOr());
1163 bool IsAnd = match(Cond, m_LogicalAnd());
1164 // If there's a select that matches both AND and OR, we need to commit to
1165 // one of the options. Arbitrarily pick OR.
1166 if (IsOr && IsAnd)
1167 IsAnd = false;
1168
1169 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1170 if (canAddSuccessor(BB, Successor)) {
1171 SmallVector<Value *> CondWorkList;
1172 SmallPtrSet<Value *, 8> SeenCond;
1173 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1174 if (SeenCond.insert(V).second)
1175 CondWorkList.push_back(V);
1176 };
1177 QueueValue(Op1);
1178 QueueValue(Op0);
1179 while (!CondWorkList.empty()) {
1180 Value *Cur = CondWorkList.pop_back_val();
1181 if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
1182 WorkList.emplace_back(FactOrCheck::getConditionFact(
1183 DT.getNode(Successor),
1184 IsOr ? Cmp->getInverseCmpPredicate() : Cmp->getCmpPredicate(),
1185 Cmp->getOperand(0), Cmp->getOperand(1)));
1186 continue;
1187 }
1188 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1189 QueueValue(Op1);
1190 QueueValue(Op0);
1191 continue;
1192 }
1193 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1194 QueueValue(Op1);
1195 QueueValue(Op0);
1196 continue;
1197 }
1198 }
1199 }
1200 return;
1201 }
1202
1203 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1204 if (!CmpI)
1205 return;
1206 if (canAddSuccessor(BB, Br->getSuccessor(0)))
1207 WorkList.emplace_back(FactOrCheck::getConditionFact(
1208 DT.getNode(Br->getSuccessor(0)), CmpI->getCmpPredicate(),
1209 CmpI->getOperand(0), CmpI->getOperand(1)));
1210 if (canAddSuccessor(BB, Br->getSuccessor(1)))
1211 WorkList.emplace_back(FactOrCheck::getConditionFact(
1212 DT.getNode(Br->getSuccessor(1)), CmpI->getInverseCmpPredicate(),
1213 CmpI->getOperand(0), CmpI->getOperand(1)));
1214}
1215
1216#ifndef NDEBUG
1218 Value *LHS, Value *RHS) {
1219 OS << "icmp " << Pred << ' ';
1220 LHS->printAsOperand(OS, /*PrintType=*/true);
1221 OS << ", ";
1222 RHS->printAsOperand(OS, /*PrintType=*/false);
1223}
1224#endif
1225
1226namespace {
1227/// Helper to keep track of a condition and if it should be treated as negated
1228/// for reproducer construction.
1229/// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1230/// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1231struct ReproducerEntry {
1233 Value *LHS;
1234 Value *RHS;
1235
1236 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1237 : Pred(Pred), LHS(LHS), RHS(RHS) {}
1238};
1239} // namespace
1240
1241/// Helper function to generate a reproducer function for simplifying \p Cond.
1242/// The reproducer function contains a series of @llvm.assume calls, one for
1243/// each condition in \p Stack. For each condition, the operand instruction are
1244/// cloned until we reach operands that have an entry in \p Value2Index. Those
1245/// will then be added as function arguments. \p DT is used to order cloned
1246/// instructions. The reproducer function will get added to \p M, if it is
1247/// non-null. Otherwise no reproducer function is generated.
1250 ConstraintInfo &Info, DominatorTree &DT) {
1251 if (!M)
1252 return;
1253
1254 LLVMContext &Ctx = Cond->getContext();
1255
1256 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1257
1258 ValueToValueMapTy Old2New;
1261 // Traverse Cond and its operands recursively until we reach a value that's in
1262 // Value2Index or not an instruction, or not a operation that
1263 // ConstraintElimination can decompose. Such values will be considered as
1264 // external inputs to the reproducer, they are collected and added as function
1265 // arguments later.
1266 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1267 auto &Value2Index = Info.getValue2Index(IsSigned);
1268 SmallVector<Value *, 4> WorkList(Ops);
1269 while (!WorkList.empty()) {
1270 Value *V = WorkList.pop_back_val();
1271 if (!Seen.insert(V).second)
1272 continue;
1273 if (Old2New.find(V) != Old2New.end())
1274 continue;
1275 if (isa<Constant>(V))
1276 continue;
1277
1278 auto *I = dyn_cast<Instruction>(V);
1279 if (Value2Index.contains(V) || !I ||
1280 !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
1281 Old2New[V] = V;
1282 Args.push_back(V);
1283 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n");
1284 } else {
1285 append_range(WorkList, I->operands());
1286 }
1287 }
1288 };
1289
1290 for (auto &Entry : Stack)
1291 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1292 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1293 CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
1294
1295 SmallVector<Type *> ParamTys;
1296 for (auto *P : Args)
1297 ParamTys.push_back(P->getType());
1298
1299 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1300 /*isVarArg=*/false);
1301 Function *F = Function::Create(FTy, Function::ExternalLinkage,
1302 Cond->getModule()->getName() +
1303 Cond->getFunction()->getName() + "repro",
1304 M);
1305 // Add arguments to the reproducer function for each external value collected.
1306 for (unsigned I = 0; I < Args.size(); ++I) {
1307 F->getArg(I)->setName(Args[I]->getName());
1308 Old2New[Args[I]] = F->getArg(I);
1309 }
1310
1311 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1312 IRBuilder<> Builder(Entry);
1313 Builder.CreateRet(Builder.getTrue());
1314 Builder.SetInsertPoint(Entry->getTerminator());
1315
1316 // Clone instructions in \p Ops and their operands recursively until reaching
1317 // an value in Value2Index (external input to the reproducer). Update Old2New
1318 // mapping for the original and cloned instructions. Sort instructions to
1319 // clone by dominance, then insert the cloned instructions in the function.
1320 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1321 SmallVector<Value *, 4> WorkList(Ops);
1323 auto &Value2Index = Info.getValue2Index(IsSigned);
1324 while (!WorkList.empty()) {
1325 Value *V = WorkList.pop_back_val();
1326 if (Old2New.find(V) != Old2New.end())
1327 continue;
1328
1329 auto *I = dyn_cast<Instruction>(V);
1330 if (!Value2Index.contains(V) && I) {
1331 Old2New[V] = nullptr;
1332 ToClone.push_back(I);
1333 append_range(WorkList, I->operands());
1334 }
1335 }
1336
1337 sort(ToClone,
1338 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1339 for (Instruction *I : ToClone) {
1340 Instruction *Cloned = I->clone();
1341 Old2New[I] = Cloned;
1342 Old2New[I]->setName(I->getName());
1343 Cloned->insertBefore(&*Builder.GetInsertPoint());
1345 Cloned->setDebugLoc({});
1346 }
1347 };
1348
1349 // Materialize the assumptions for the reproducer using the entries in Stack.
1350 // That is, first clone the operands of the condition recursively until we
1351 // reach an external input to the reproducer and add them to the reproducer
1352 // function. Then add an ICmp for the condition (with the inverse predicate if
1353 // the entry is negated) and an assert using the ICmp.
1354 for (auto &Entry : Stack) {
1355 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1356 continue;
1357
1358 LLVM_DEBUG(dbgs() << " Materializing assumption ";
1359 dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
1360 dbgs() << "\n");
1361 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1362
1363 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1364 Builder.CreateAssumption(Cmp);
1365 }
1366
1367 // Finally, clone the condition to reproduce and remap instruction operands in
1368 // the reproducer using Old2New.
1369 CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1370 Entry->getTerminator()->setOperand(0, Cond);
1371 remapInstructionsInBlocks({Entry}, Old2New);
1372
1373 assert(!verifyFunction(*F, &dbgs()));
1374}
1375
1376static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
1377 Value *B, Instruction *CheckInst,
1378 ConstraintInfo &Info) {
1379 LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1380
1381 auto R = Info.getConstraintForSolving(Pred, A, B);
1382 if (R.empty() || !R.isValid(Info)){
1383 LLVM_DEBUG(dbgs() << " failed to decompose condition\n");
1384 return std::nullopt;
1385 }
1386
1387 auto &CSToUse = Info.getCS(R.IsSigned);
1388
1389 // If there was extra information collected during decomposition, apply
1390 // it now and remove it immediately once we are done with reasoning
1391 // about the constraint.
1392 for (auto &Row : R.ExtraInfo)
1393 CSToUse.addVariableRow(Row);
1394 auto InfoRestorer = make_scope_exit([&]() {
1395 for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1396 CSToUse.popLastConstraint();
1397 });
1398
1399 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1400 if (!DebugCounter::shouldExecute(EliminatedCounter))
1401 return std::nullopt;
1402
1403 LLVM_DEBUG({
1404 dbgs() << "Condition ";
1406 dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred),
1407 A, B);
1408 dbgs() << " implied by dominating constraints\n";
1409 CSToUse.dump();
1410 });
1411 return ImpliedCondition;
1412 }
1413
1414 return std::nullopt;
1415}
1416
1418 CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1419 Instruction *ContextInst, Module *ReproducerModule,
1420 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1422 auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1423 generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1424 Constant *ConstantC = ConstantInt::getBool(
1425 CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1426 Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
1427 ContextInst](Use &U) {
1428 auto *UserI = getContextInstForUse(U);
1429 auto *DTN = DT.getNode(UserI->getParent());
1430 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1431 return false;
1432 if (UserI->getParent() == ContextInst->getParent() &&
1433 UserI->comesBefore(ContextInst))
1434 return false;
1435
1436 // Conditions in an assume trivially simplify to true. Skip uses
1437 // in assume calls to not destroy the available information.
1438 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1439 return !II || II->getIntrinsicID() != Intrinsic::assume;
1440 });
1441 NumCondsRemoved++;
1442 if (Cmp->use_empty())
1443 ToRemove.push_back(Cmp);
1444 return true;
1445 };
1446
1447 if (auto ImpliedCondition =
1448 checkCondition(Cmp->getPredicate(), Cmp->getOperand(0),
1449 Cmp->getOperand(1), Cmp, Info))
1450 return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1451 return false;
1452}
1453
1454static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
1456 auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
1457 // TODO: generate reproducer for min/max.
1458 MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
1459 ToRemove.push_back(MinMax);
1460 return true;
1461 };
1462
1463 ICmpInst::Predicate Pred =
1464 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1465 if (auto ImpliedCondition = checkCondition(
1466 Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
1467 return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
1468 if (auto ImpliedCondition = checkCondition(
1469 Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
1470 return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
1471 return false;
1472}
1473
1474static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
1476 Value *LHS = I->getOperand(0);
1477 Value *RHS = I->getOperand(1);
1478 if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1479 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
1480 ToRemove.push_back(I);
1481 return true;
1482 }
1483 if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1484 I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
1485 ToRemove.push_back(I);
1486 return true;
1487 }
1488 if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
1489 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
1490 ToRemove.push_back(I);
1491 return true;
1492 }
1493 return false;
1494}
1495
1496static void
1497removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1498 Module *ReproducerModule,
1499 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1500 SmallVectorImpl<StackEntry> &DFSInStack) {
1501 Info.popLastConstraint(E.IsSigned);
1502 // Remove variables in the system that went out of scope.
1503 auto &Mapping = Info.getValue2Index(E.IsSigned);
1504 for (Value *V : E.ValuesToRelease)
1505 Mapping.erase(V);
1506 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1507 DFSInStack.pop_back();
1508 if (ReproducerModule)
1509 ReproducerCondStack.pop_back();
1510}
1511
1512/// Check if either the first condition of an AND or OR is implied by the
1513/// (negated in case of OR) second condition or vice versa.
1515 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1516 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1517 SmallVectorImpl<StackEntry> &DFSInStack) {
1518 Instruction *JoinOp = CB.getContextInst();
1519 CmpInst *CmpToCheck = cast<CmpInst>(CB.getInstructionToSimplify());
1520 unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
1521
1522 // Don't try to simplify the first condition of a select by the second, as
1523 // this may make the select more poisonous than the original one.
1524 // TODO: check if the first operand may be poison.
1525 if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
1526 return false;
1527
1528 unsigned OldSize = DFSInStack.size();
1529 auto InfoRestorer = make_scope_exit([&]() {
1530 // Remove entries again.
1531 while (OldSize < DFSInStack.size()) {
1532 StackEntry E = DFSInStack.back();
1533 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1534 DFSInStack);
1535 }
1536 });
1537 bool IsOr = match(JoinOp, m_LogicalOr());
1538 SmallVector<Value *, 4> Worklist({JoinOp->getOperand(OtherOpIdx)});
1539 // Do a traversal of the AND/OR tree to add facts from leaf compares.
1540 while (!Worklist.empty()) {
1541 Value *Val = Worklist.pop_back_val();
1542 Value *LHS, *RHS;
1543 CmpPredicate Pred;
1544 if (match(Val, m_ICmp(Pred, m_Value(LHS), m_Value(RHS)))) {
1545 // For OR, check if the negated condition implies CmpToCheck.
1546 if (IsOr)
1547 Pred = CmpInst::getInversePredicate(Pred);
1548 // Optimistically add fact from the other compares in the AND/OR.
1549 Info.addFact(Pred, LHS, RHS, CB.NumIn, CB.NumOut, DFSInStack);
1550 continue;
1551 }
1552 if (IsOr ? match(Val, m_LogicalOr(m_Value(LHS), m_Value(RHS)))
1553 : match(Val, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
1554 Worklist.push_back(LHS);
1555 Worklist.push_back(RHS);
1556 }
1557 }
1558 if (OldSize == DFSInStack.size())
1559 return false;
1560
1561 // Check if the second condition can be simplified now.
1562 if (auto ImpliedCondition =
1563 checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
1564 CmpToCheck->getOperand(1), CmpToCheck, Info)) {
1565 if (IsOr && isa<SelectInst>(JoinOp)) {
1566 JoinOp->setOperand(
1567 OtherOpIdx == 0 ? 2 : 0,
1568 ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1569 } else
1570 JoinOp->setOperand(
1571 1 - OtherOpIdx,
1572 ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1573
1574 return true;
1575 }
1576
1577 return false;
1578}
1579
1580void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1581 unsigned NumIn, unsigned NumOut,
1582 SmallVectorImpl<StackEntry> &DFSInStack) {
1583 // If the constraint has a pre-condition, skip the constraint if it does not
1584 // hold.
1585 SmallVector<Value *> NewVariables;
1586 auto R = getConstraint(Pred, A, B, NewVariables);
1587
1588 // TODO: Support non-equality for facts as well.
1589 if (!R.isValid(*this) || R.isNe())
1590 return;
1591
1592 LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
1593 dbgs() << "'\n");
1594 bool Added = false;
1595 auto &CSToUse = getCS(R.IsSigned);
1596 if (R.Coefficients.empty())
1597 return;
1598
1599 Added |= CSToUse.addVariableRowFill(R.Coefficients);
1600
1601 // If R has been added to the system, add the new variables and queue it for
1602 // removal once it goes out-of-scope.
1603 if (Added) {
1604 SmallVector<Value *, 2> ValuesToRelease;
1605 auto &Value2Index = getValue2Index(R.IsSigned);
1606 for (Value *V : NewVariables) {
1607 Value2Index.insert({V, Value2Index.size() + 1});
1608 ValuesToRelease.push_back(V);
1609 }
1610
1611 LLVM_DEBUG({
1612 dbgs() << " constraint: ";
1613 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1614 dbgs() << "\n";
1615 });
1616
1617 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1618 std::move(ValuesToRelease));
1619
1620 if (!R.IsSigned) {
1621 for (Value *V : NewVariables) {
1622 ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
1623 false, false, false);
1624 VarPos.Coefficients[Value2Index[V]] = -1;
1625 CSToUse.addVariableRow(VarPos.Coefficients);
1626 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1628 }
1629 }
1630
1631 if (R.isEq()) {
1632 // Also add the inverted constraint for equality constraints.
1633 for (auto &Coeff : R.Coefficients)
1634 Coeff *= -1;
1635 CSToUse.addVariableRowFill(R.Coefficients);
1636
1637 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1639 }
1640 }
1641}
1642
1645 bool Changed = false;
1646 IRBuilder<> Builder(II->getParent(), II->getIterator());
1647 Value *Sub = nullptr;
1648 for (User *U : make_early_inc_range(II->users())) {
1649 if (match(U, m_ExtractValue<0>(m_Value()))) {
1650 if (!Sub)
1651 Sub = Builder.CreateSub(A, B);
1652 U->replaceAllUsesWith(Sub);
1653 Changed = true;
1654 } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1655 U->replaceAllUsesWith(Builder.getFalse());
1656 Changed = true;
1657 } else
1658 continue;
1659
1660 if (U->use_empty()) {
1661 auto *I = cast<Instruction>(U);
1662 ToRemove.push_back(I);
1663 I->setOperand(0, PoisonValue::get(II->getType()));
1664 Changed = true;
1665 }
1666 }
1667
1668 if (II->use_empty()) {
1669 II->eraseFromParent();
1670 Changed = true;
1671 }
1672 return Changed;
1673}
1674
1675static bool
1678 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1679 ConstraintInfo &Info) {
1680 auto R = Info.getConstraintForSolving(Pred, A, B);
1681 if (R.size() < 2 || !R.isValid(Info))
1682 return false;
1683
1684 auto &CSToUse = Info.getCS(R.IsSigned);
1685 return CSToUse.isConditionImplied(R.Coefficients);
1686 };
1687
1688 bool Changed = false;
1689 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1690 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1691 // can be simplified to a regular sub.
1692 Value *A = II->getArgOperand(0);
1693 Value *B = II->getArgOperand(1);
1694 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1695 !DoesConditionHold(CmpInst::ICMP_SGE, B,
1696 ConstantInt::get(A->getType(), 0), Info))
1697 return false;
1698 Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1699 }
1700 return Changed;
1701}
1702
1704 ScalarEvolution &SE,
1706 bool Changed = false;
1707 DT.updateDFSNumbers();
1708 SmallVector<Value *> FunctionArgs;
1709 for (Value &Arg : F.args())
1710 FunctionArgs.push_back(&Arg);
1711 ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
1712 State S(DT, LI, SE);
1713 std::unique_ptr<Module> ReproducerModule(
1714 DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1715
1716 // First, collect conditions implied by branches and blocks with their
1717 // Dominator DFS in and out numbers.
1718 for (BasicBlock &BB : F) {
1719 if (!DT.getNode(&BB))
1720 continue;
1721 S.addInfoFor(BB);
1722 }
1723
1724 // Next, sort worklist by dominance, so that dominating conditions to check
1725 // and facts come before conditions and facts dominated by them. If a
1726 // condition to check and a fact have the same numbers, conditional facts come
1727 // first. Assume facts and checks are ordered according to their relative
1728 // order in the containing basic block. Also make sure conditions with
1729 // constant operands come before conditions without constant operands. This
1730 // increases the effectiveness of the current signed <-> unsigned fact
1731 // transfer logic.
1732 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1733 auto HasNoConstOp = [](const FactOrCheck &B) {
1734 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
1735 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
1736 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1737 };
1738 // If both entries have the same In numbers, conditional facts come first.
1739 // Otherwise use the relative order in the basic block.
1740 if (A.NumIn == B.NumIn) {
1741 if (A.isConditionFact() && B.isConditionFact()) {
1742 bool NoConstOpA = HasNoConstOp(A);
1743 bool NoConstOpB = HasNoConstOp(B);
1744 return NoConstOpA < NoConstOpB;
1745 }
1746 if (A.isConditionFact())
1747 return true;
1748 if (B.isConditionFact())
1749 return false;
1750 auto *InstA = A.getContextInst();
1751 auto *InstB = B.getContextInst();
1752 return InstA->comesBefore(InstB);
1753 }
1754 return A.NumIn < B.NumIn;
1755 });
1756
1758
1759 // Finally, process ordered worklist and eliminate implied conditions.
1760 SmallVector<StackEntry, 16> DFSInStack;
1761 SmallVector<ReproducerEntry> ReproducerCondStack;
1762 for (FactOrCheck &CB : S.WorkList) {
1763 // First, pop entries from the stack that are out-of-scope for CB. Remove
1764 // the corresponding entry from the constraint system.
1765 while (!DFSInStack.empty()) {
1766 auto &E = DFSInStack.back();
1767 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1768 << "\n");
1769 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1770 assert(E.NumIn <= CB.NumIn);
1771 if (CB.NumOut <= E.NumOut)
1772 break;
1773 LLVM_DEBUG({
1774 dbgs() << "Removing ";
1775 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1776 Info.getValue2Index(E.IsSigned));
1777 dbgs() << "\n";
1778 });
1779 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1780 DFSInStack);
1781 }
1782
1783 // For a block, check if any CmpInsts become known based on the current set
1784 // of constraints.
1785 if (CB.isCheck()) {
1786 Instruction *Inst = CB.getInstructionToSimplify();
1787 if (!Inst)
1788 continue;
1789 LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
1790 << "\n");
1791 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1792 Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1793 } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1795 Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1796 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1797 if (!Simplified &&
1798 match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
1799 Simplified =
1800 checkOrAndOpImpliedByOther(CB, Info, ReproducerModule.get(),
1801 ReproducerCondStack, DFSInStack);
1802 }
1803 Changed |= Simplified;
1804 } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
1805 Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
1806 } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
1807 Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
1808 }
1809 continue;
1810 }
1811
1812 auto AddFact = [&](CmpPredicate Pred, Value *A, Value *B) {
1813 LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
1814 dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
1815 if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1816 LLVM_DEBUG(
1817 dbgs()
1818 << "Skip adding constraint because system has too many rows.\n");
1819 return;
1820 }
1821
1822 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1823 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1824 ReproducerCondStack.emplace_back(Pred, A, B);
1825
1826 if (ICmpInst::isRelational(Pred)) {
1827 // If samesign is present on the ICmp, simply flip the sign of the
1828 // predicate, transferring the information from the signed system to the
1829 // unsigned system, and viceversa.
1830 if (Pred.hasSameSign())
1832 CB.NumIn, CB.NumOut, DFSInStack);
1833 else
1834 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut,
1835 DFSInStack);
1836 }
1837
1838 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1839 // Add dummy entries to ReproducerCondStack to keep it in sync with
1840 // DFSInStack.
1841 for (unsigned I = 0,
1842 E = (DFSInStack.size() - ReproducerCondStack.size());
1843 I < E; ++I) {
1844 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1845 nullptr, nullptr);
1846 }
1847 }
1848 };
1849
1850 CmpPredicate Pred;
1851 if (!CB.isConditionFact()) {
1852 Value *X;
1853 if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
1854 // If is_int_min_poison is true then we may assume llvm.abs >= 0.
1855 if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
1856 AddFact(CmpInst::ICMP_SGE, CB.Inst,
1857 ConstantInt::get(CB.Inst->getType(), 0));
1858 AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
1859 continue;
1860 }
1861
1862 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1863 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1864 AddFact(Pred, MinMax, MinMax->getLHS());
1865 AddFact(Pred, MinMax, MinMax->getRHS());
1866 continue;
1867 }
1868 }
1869
1870 Value *A = nullptr, *B = nullptr;
1871 if (CB.isConditionFact()) {
1872 Pred = CB.Cond.Pred;
1873 A = CB.Cond.Op0;
1874 B = CB.Cond.Op1;
1875 if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
1876 !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
1877 LLVM_DEBUG({
1878 dbgs() << "Not adding fact ";
1879 dumpUnpackedICmp(dbgs(), Pred, A, B);
1880 dbgs() << " because precondition ";
1881 dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
1882 CB.DoesHold.Op1);
1883 dbgs() << " does not hold.\n";
1884 });
1885 continue;
1886 }
1887 } else {
1888 bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
1889 m_ICmp(Pred, m_Value(A), m_Value(B))));
1890 (void)Matched;
1891 assert(Matched && "Must have an assume intrinsic with a icmp operand");
1892 }
1893 AddFact(Pred, A, B);
1894 }
1895
1896 if (ReproducerModule && !ReproducerModule->functions().empty()) {
1897 std::string S;
1898 raw_string_ostream StringS(S);
1899 ReproducerModule->print(StringS, nullptr);
1900 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1901 Rem << ore::NV("module") << S;
1902 ORE.emit(Rem);
1903 }
1904
1905#ifndef NDEBUG
1906 unsigned SignedEntries =
1907 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1908 assert(Info.getCS(false).size() - FunctionArgs.size() ==
1909 DFSInStack.size() - SignedEntries &&
1910 "updates to CS and DFSInStack are out of sync");
1911 assert(Info.getCS(true).size() == SignedEntries &&
1912 "updates to CS and DFSInStack are out of sync");
1913#endif
1914
1915 for (Instruction *I : ToRemove)
1916 I->eraseFromParent();
1917 return Changed;
1918}
1919
1922 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1923 auto &LI = AM.getResult<LoopAnalysis>(F);
1924 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1926 if (!eliminateConstraints(F, DT, LI, SE, ORE))
1927 return PreservedAnalyses::all();
1928
1931 PA.preserve<LoopAnalysis>();
1934 return PA;
1935}
ReachingDefAnalysis InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
std::pair< ICmpInst *, unsigned > ConditionTy
static int64_t MaxConstraintValue
static int64_t MinSignedConstraintValue
static Instruction * getContextInstForUse(Use &U)
static Decomposition decomposeGEP(GEPOperator &GEP, SmallVectorImpl< ConditionTy > &Preconditions, bool IsSigned, const DataLayout &DL)
static bool canUseSExt(ConstantInt *CI)
static int64_t multiplyWithOverflow(int64_t A, int64_t B)
static void dumpConstraint(ArrayRef< int64_t > C, const DenseMap< Value *, unsigned > &Value2Index)
static void removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack)
static std::optional< bool > checkCondition(CmpInst::Predicate Pred, Value *A, Value *B, Instruction *CheckInst, ConstraintInfo &Info)
static cl::opt< unsigned > MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, cl::desc("Maximum number of rows to keep in constraint system"))
static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, OptimizationRemarkEmitter &ORE)
static int64_t addWithOverflow(int64_t A, int64_t B)
static cl::opt< bool > DumpReproducers("constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, cl::desc("Dump IR to reproduce successful transformations."))
static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL)
static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static void generateReproducer(CmpInst *Cond, Module *M, ArrayRef< ReproducerEntry > Stack, ConstraintInfo &Info, DominatorTree &DT)
Helper function to generate a reproducer function for simplifying Cond.
static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
static bool checkOrAndOpImpliedByOther(FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack)
Check if either the first condition of an AND or OR is implied by the (negated in case of OR) second ...
static Decomposition decompose(Value *V, SmallVectorImpl< ConditionTy > &Preconditions, bool IsSigned, const DataLayout &DL)
static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, SmallVectorImpl< Instruction * > &ToRemove)
static bool tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
#define DEBUG_TYPE
static bool checkAndReplaceCondition(CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, Instruction *ContextInst, Module *ReproducerModule, ArrayRef< ReproducerEntry > ReproducerCondStack, DominatorTree &DT, SmallVectorImpl< Instruction * > &ToRemove)
static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Definition: DebugCounter.h:190
#define LLVM_DEBUG(...)
Definition: Debug.h:106
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1313
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
const SmallVectorImpl< MachineOperand > & Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1201
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:380
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1640
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:329
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:475
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1130
bool isOne() const
Determine if this is a value of 1.
Definition: APInt.h:389
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:212
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:661
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:988
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:702
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:703
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:697
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:696
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:700
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:698
@ ICMP_EQ
equal
Definition: InstrTypes.h:694
@ ICMP_NE
not equal
Definition: InstrTypes.h:695
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:701
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:699
bool isSigned() const
Definition: InstrTypes.h:928
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:825
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:787
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:763
This class represents a ucmp/scmp intrinsic.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Definition: CmpPredicate.h:22
bool hasSameSign() const
Query samesign information, for optimizations.
Definition: CmpPredicate.h:42
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
bool isNegative() const
Definition: Constants.h:203
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:126
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:163
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:148
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:880
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:420
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
DenseMap< Value *, unsigned > & getValue2Index()
static SmallVector< int64_t, 8 > negate(SmallVector< int64_t, 8 > R)
bool isConditionImplied(SmallVector< int64_t, 8 > R) const
static SmallVector< int64_t, 8 > toStrictLessThan(SmallVector< int64_t, 8 > R)
Converts the given vector to form a strict less than inequality.
bool addVariableRow(ArrayRef< int64_t > R)
static SmallVector< int64_t, 8 > negateOrEqual(SmallVector< int64_t, 8 > R)
Multiplies each coefficient in the given vector by -1.
bool addVariableRowFill(ArrayRef< int64_t > R)
void dump() const
Print the constraints in the system.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:87
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
bool erase(const KeyT &Val)
Definition: DenseMap.h:321
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:147
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
unsigned getDFSNumOut() const
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:173
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
CallInst * CreateAssumption(Value *Cond, ArrayRef< OperandBundleDef > OpBundles={})
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Definition: IRBuilder.cpp:521
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:463
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:172
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition: IRBuilder.h:1119
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1367
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:468
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:177
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2383
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2697
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:97
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1633
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:468
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:566
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
size_type size() const
Definition: MapVector.h:60
This class represents min/max intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
The optimization diagnostic interface.
Diagnostic information for applied optimization remarks.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
This class represents an analyzed expression in the program.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
APInt getConstantMultiple(const SCEV *S)
Returns the max constant multiple of S.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:937
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
void setOperand(unsigned i, Value *Val)
Definition: User.h:233
Value * getOperand(unsigned i) const
Definition: User.h:228
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator end()
Definition: ValueMap.h:135
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:5144
const Value * stripPointerCastsSameRepresentation() const
Strip off pointer casts, all-zero GEPs and address space casts but ensures the representation of the ...
Definition: Value.cpp:702
const ParentTy * getParent() const
Definition: ilist_node.h:32
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
NNegZExt_match< OpTy > m_NNegZExt(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:612
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::enable_if_t< std::is_signed_v< T >, T > MulOverflow(T X, T Y, T &Result)
Multiply two signed integers, computing the two's complement truncated result, returning true if an o...
Definition: MathExtras.h:753
void stable_sort(R &&Range)
Definition: STLExtras.h:2037
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1739
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1697
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7293
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:657
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:44
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1945
std::enable_if_t< std::is_signed_v< T >, T > AddOverflow(T X, T Y, T &Result)
Add two signed integers, computing the two's complement truncated result, returning true if overflow ...
Definition: MathExtras.h:701
std::enable_if_t< std::is_signed_v< T >, T > SubOverflow(T X, T Y, T &Result)
Subtract two signed integers, computing the two's complement truncated result, returning true if an o...
Definition: MathExtras.h:727
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
#define N
A MapVector that performs no allocations if smaller than a certain size.
Definition: MapVector.h:254