LLVM 24.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 "ScalarOptions.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/Statistic.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Module.h"
40#include "llvm/IR/Verifier.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/Debug.h"
48
49#include <optional>
50#include <string>
51
52using namespace llvm;
53using namespace PatternMatch;
54using namespace SCEVPatternMatch;
55
56#define DEBUG_TYPE "constraint-elimination"
57
58STATISTIC(NumCondsRemoved, "Number of instructions removed");
59STATISTIC(NumDoesHoldDepthLimitHit,
60 "Number of doesHold queries cut off by the nesting depth limit");
61DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
62 "Controls which conditions are eliminated");
63
64static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
65static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
66
68 Instruction *UserI = cast<Instruction>(U.getUser());
69 if (auto *Phi = dyn_cast<PHINode>(UserI))
70 UserI = Phi->getIncomingBlock(U)->getTerminator();
71 return UserI;
72}
73
74/// Returns the closest program point dominating all uses of \p I.
76 DominatorTree &DT) {
77 Instruction *CommonDom = nullptr;
78 unsigned NumUses = 0;
79 for (Use &U : I.uses()) {
80 // Conservatively use original instruction, if there are too many uses.
81 if (++NumUses == 16)
82 return &I;
84 CommonDom =
85 CommonDom ? DT.findNearestCommonDominator(CommonDom, UserI) : UserI;
86 }
87 if (!CommonDom)
88 return &I;
89 // Uses in unreachable blocks are not in the dominator tree.
90 return DT.getNode(CommonDom->getParent()) ? CommonDom : &I;
91}
92
93namespace {
94using Entry = ConstraintSystem::Entry;
95using RowTy = ConstraintSystem::RowTy;
96
97/// Struct to express a condition of the form %Op0 Pred %Op1.
98struct ConditionTy {
99 CmpPredicate Pred;
100 Value *Op0 = nullptr;
101 Value *Op1 = nullptr;
102
103 ConditionTy() = default;
104 ConditionTy(CmpPredicate Pred, Value *Op0, Value *Op1)
105 : Pred(Pred), Op0(Op0), Op1(Op1) {}
106};
107
108/// Represents either
109/// * a condition that holds on entry to a block (=condition fact)
110/// * an assume (=assume fact)
111/// * a use of a compare instruction to simplify.
112/// It also tracks the Dominator DFS in and out numbers for each entry.
113struct FactOrCheck {
114 enum class EntryTy {
115 ConditionFact, /// A condition that holds on entry to a block.
116 InstFact, /// A fact that holds after Inst executed (e.g. an assume or
117 /// min/mix intrinsic.
118 InstCheck, /// An instruction to simplify (e.g. an overflow math
119 /// intrinsics) or whose flags may be strengthened.
120 UseCheck /// An use of a compare instruction to simplify.
121 };
122
123 union {
124 Instruction *Inst;
125 Use *U;
127 };
128
129 union {
130 /// A pre-condition that must hold for the current fact to be added to the
131 /// system. Only used by condition facts.
132 ConditionTy DoesHold;
133
134 /// Context instruction for the point where conditions are checked for
135 /// InstCheck simplifications.
136 Instruction *ContextInst;
137 };
138
139 unsigned NumIn;
140 unsigned NumOut;
141 EntryTy Ty;
142
143 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst,
144 Instruction *ContextInst = nullptr)
145 : Inst(Inst), ContextInst(ContextInst ? ContextInst : Inst),
146 NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), Ty(Ty) {}
147
148 FactOrCheck(DomTreeNode *DTN, Use *U)
149 : U(U), ContextInst(nullptr), NumIn(DTN->getDFSNumIn()),
150 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::UseCheck) {}
151
152 FactOrCheck(DomTreeNode *DTN, CmpPredicate Pred, Value *Op0, Value *Op1,
153 ConditionTy Precond = {})
154 : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
155 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
156
157 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpPredicate Pred,
158 Value *Op0, Value *Op1,
159 ConditionTy Precond = {}) {
160 return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
161 }
162
163 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
164 return FactOrCheck(EntryTy::InstFact, DTN, Inst);
165 }
166
167 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
168 return FactOrCheck(DTN, U);
169 }
170
171 static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *I,
172 Instruction *ContextInst = nullptr) {
173 assert((ContextInst ? ContextInst : I)->getParent() == DTN->getBlock() &&
174 "anchoring instruction must be in DTN's block");
175 return FactOrCheck(EntryTy::InstCheck, DTN, I, ContextInst);
176 }
177
178 bool isCheck() const {
179 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
180 }
181
182 Instruction *getContextInst() const {
183 assert(!isConditionFact());
184 if (Ty == EntryTy::UseCheck)
185 return getContextInstForUse(*U);
186 return ContextInst;
187 }
188
189 Instruction *getInstructionToSimplify() const {
190 assert(isCheck());
191 if (Ty == EntryTy::InstCheck)
192 return Inst;
193 // The use may have been simplified to a constant already.
194 return dyn_cast<Instruction>(*U);
195 }
196
197 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
198};
199
200/// The senses in which an induction phi is monotonic, together with the
201/// direction it moves in.
202struct MonotonicInfo {
203 /// True if the phi steps by a negative constant.
204 bool Decreasing = false;
205 /// True if the phi is monotonic in the unsigned sense.
206 bool Unsigned = false;
207 /// True if the phi is monotonic in the signed sense.
208 bool Signed = false;
209};
210
211/// Keep state required to build worklist.
212struct State {
213 DominatorTree &DT;
214 LoopInfo &LI;
215 /// Only available for functions with loops.
216 ScalarEvolution *SE;
217 TargetLibraryInfo &TLI;
219
220 State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE,
221 TargetLibraryInfo &TLI)
222 : DT(DT), LI(LI), SE(SE), TLI(TLI) {}
223
224 /// Process block \p BB and add known facts to work-list.
225 void addInfoFor(BasicBlock &BB);
226
227 /// If \p BB is a loop header, bound each induction phi in it by its start
228 /// value.
229 void addBoundsForHeaderInductions(BasicBlock &BB);
230
231 /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
232 /// controlling the loop header.
233 void addInfoForInductions(BasicBlock &BB);
234
235 /// Returns the direction the induction phi \p PN with backedge value \p Step
236 /// moves in, and the senses in which it is monotonic in that direction.
237 MonotonicInfo getMonotonicityInfo(PHINode &PN, Value *Step);
238
239 /// Returns true if we can add a known condition from BB to its successor
240 /// block Succ.
241 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
242 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
243 }
244};
245
246class ConstraintInfo;
247
248struct StackEntry {
249 unsigned NumIn;
250 unsigned NumOut;
251 bool IsSigned = false;
252 /// Variables that can be removed from the system once the stack entry gets
253 /// removed.
254 SmallVector<Value *, 2> ValuesToRelease;
255
256 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
257 SmallVector<Value *, 2> ValuesToRelease)
258 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
259 ValuesToRelease(std::move(ValuesToRelease)) {}
260};
261
262struct ConstraintTy {
263 RowTy Coefficients;
264
265 /// Number of variables the constraint is defined over.
266 unsigned NumVars = 0;
267
268 bool IsSigned = false;
269
270 ConstraintTy() = default;
271
272 ConstraintTy(RowTy Coefficients, unsigned NumVars, bool IsSigned, bool IsEq,
273 bool IsNe)
274 : Coefficients(std::move(Coefficients)), NumVars(NumVars),
275 IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) {}
276
277 bool empty() const { return Coefficients.empty(); }
278
279 bool isEq() const { return IsEq; }
280
281 bool isNe() const { return IsNe; }
282
283 /// Check if the current constraint is implied by the given ConstraintSystem.
284 ///
285 /// \return true or false if the constraint is proven to be respectively true,
286 /// or false. When the constraint cannot be proven to be either true or false,
287 /// std::nullopt is returned.
288 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
289
290private:
291 bool IsEq = false;
292 bool IsNe = false;
293};
294
295/// Represents a (Coefficient * Variable) entry after IR decomposition.
296struct DecompEntry {
297 int64_t Coefficient;
298 Value *Variable;
299
300 DecompEntry(int64_t Coefficient, Value *Variable)
301 : Coefficient(Coefficient), Variable(Variable) {}
302};
303
304/// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
305struct Decomposition {
306 int64_t Offset = 0;
308
309 Decomposition(int64_t Offset) : Offset(Offset) {}
310 Decomposition(Value *V) { Vars.emplace_back(1, V); }
311 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
312 : Offset(Offset), Vars(Vars) {}
313
314 /// Add \p OtherOffset and return true if the operation overflows, i.e. the
315 /// new decomposition is invalid.
316 [[nodiscard]] bool add(int64_t OtherOffset) {
317 return AddOverflow(Offset, OtherOffset, Offset);
318 }
319
320 /// Add \p Other and return true if the operation overflows, i.e. the new
321 /// decomposition is invalid.
322 [[nodiscard]] bool add(const Decomposition &Other) {
323 if (add(Other.Offset))
324 return true;
325 append_range(Vars, Other.Vars);
326 return false;
327 }
328
329 /// Subtract \p Other and return true if the operation overflows, i.e. the new
330 /// decomposition is invalid.
331 [[nodiscard]] bool sub(const Decomposition &Other) {
332 Decomposition Tmp = Other;
333 if (Tmp.mul(-1))
334 return true;
335 if (add(Tmp.Offset))
336 return true;
337 append_range(Vars, Tmp.Vars);
338 return false;
339 }
340
341 /// Multiply all coefficients by \p Factor and return true if the operation
342 /// overflows, i.e. the new decomposition is invalid.
343 [[nodiscard]] bool mul(int64_t Factor) {
344 if (MulOverflow(Offset, Factor, Offset))
345 return true;
346 for (auto &Var : Vars)
347 if (MulOverflow(Var.Coefficient, Factor, Var.Coefficient))
348 return true;
349 return false;
350 }
351};
352
353/// Wrapper encapsulating separate constraint systems and corresponding value
354/// mappings for both unsigned and signed information. Facts are added to and
355/// conditions are checked against the corresponding system depending on the
356/// signed-ness of their predicates. While the information is kept separate
357/// based on signed-ness, certain conditions can be transferred between the two
358/// systems.
359class ConstraintInfo {
360
361 ConstraintSystem UnsignedCS;
362 ConstraintSystem SignedCS;
363
364 const DataLayout &DL;
365
366public:
367 /// Maximum nesting of doesHold queries. Deeper queries conservatively return
368 /// false.
369 static constexpr unsigned MaxDoesHoldDepth = 2;
370
371private:
372 /// Decompositions computed against the current state of the systems. Must be
373 /// cleared when the system changes.
374 DenseMap<PointerIntPair<Value *, 1, bool>, Decomposition> DecomposeCache;
375
376 /// Current nesting depth of doesHold.
377 unsigned DoesHoldDepth = 0;
378
379 /// Number of doesHold queries that have been cut off by MaxDoesHoldDepth so
380 /// far.
381 unsigned NumDepthLimitHits = 0;
382
383public:
384 DenseMap<PointerIntPair<Value *, 1, bool>, Decomposition> &
385 getDecomposeCache() {
386 return DecomposeCache;
387 }
388
389 unsigned getNumDepthLimitHits() const { return NumDepthLimitHits; }
390
391 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
392 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
393 auto &Value2Index = getValue2Index(false);
394 // Add Arg > -1 constraints to unsigned system for all function arguments.
395 for (Value *Arg : FunctionArgs)
396 UnsignedCS.addRow({Entry(0, 0), Entry(-1, Value2Index.at(Arg))},
397 Value2Index.size());
398 }
399
400 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
401 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
402 }
403 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
404 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
405 }
406
407 ConstraintSystem &getCS(bool Signed) {
408 return Signed ? SignedCS : UnsignedCS;
409 }
410 const ConstraintSystem &getCS(bool Signed) const {
411 return Signed ? SignedCS : UnsignedCS;
412 }
413
414 void popLastConstraint(bool Signed) {
415 assert(DecomposeCache.empty() && "Cache must be cleared");
416 getCS(Signed).popLastConstraint();
417 }
418 void popLastNVariables(bool Signed, unsigned N) {
419 assert(DecomposeCache.empty() && "Cache must be cleared");
420 getCS(Signed).popLastNVariables(N);
421 }
422
423 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B);
424
425 /// Returns the result of \p Solve. If it does not return a value, retries
426 /// after adding A == decompose(A) and B == decompose(B) to the system of \p
427 /// C, if needed, and removes them afterwards.
428 std::optional<bool>
429 tryWithLinkRows(Value *A, Value *B, const ConstraintTy &C,
430 function_ref<std::optional<bool>()> Solve);
431
432 /// Returns true if \p V is known to be non-negative, either because the
433 /// signed system implies it or because ValueTracking can prove it.
435
436 /// Returns true if \p V is known to be positive, either because the signed
437 /// system implies it or because ValueTracking can prove it.
438 bool isKnownPositive(Value *V);
439
440 /// Returns true if \p V is known to be negative, false if \p V is known to be
441 /// nonnegative, or std::nullopt if neither the signed system nor
442 /// ValueTracking can prove it.
443 std::optional<bool> getKnownSign(Value *V);
444
445 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
446 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
447
448 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
449 /// constraints, using indices from the corresponding constraint system.
450 /// New variables that need to be added to the system are collected in
451 /// \p NewVariables.
452 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
453 SmallVectorImpl<Value *> &NewVariables,
454 bool ForceSignedSystem = false);
455
456 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
457 /// constraints using getConstraint. Returns an empty constraint if the result
458 /// cannot be used to query the existing constraint system, e.g. because it
459 /// would require adding new variables. Also tries to convert signed
460 /// predicates to unsigned ones if possible to allow using the unsigned system
461 /// which increases the effectiveness of the signed <-> unsigned transfer
462 /// logic.
463 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
464 Value *Op1);
465
466 /// Try to add information from \p A \p Pred \p B to the unsigned/signed
467 /// system if \p Pred is signed/unsigned.
468 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
469 unsigned NumIn, unsigned NumOut,
470 SmallVectorImpl<StackEntry> &DFSInStack);
471
472private:
473 /// Adds facts into constraint system. \p ForceSignedSystem can be set when
474 /// the \p Pred is eq/ne, and signed constraint system is used when it's
475 /// specified.
476 void addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
477 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack,
478 bool ForceSignedSystem);
479
480 /// Try to use the inequality \p A != \p B to tighten a non-strict bound the
481 /// system already implies to the corresponding strict bound.
482 void tightenBoundUsingNe(Value *A, Value *B, unsigned NumIn, unsigned NumOut,
483 SmallVectorImpl<StackEntry> &DFSInStack);
484};
485
486// Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
487struct OffsetResult {
488 Value *BasePtr;
489 APInt ConstantOffset;
490 SmallMapVector<Value *, APInt, 4> VariableOffsets;
491 GEPNoWrapFlags NW;
492
493 OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
494
495 OffsetResult(GEPOperator &GEP, const DataLayout &DL)
496 : BasePtr(GEP.getPointerOperand()), NW(GEP.getNoWrapFlags()) {
497 ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
498 }
499};
500} // namespace
501
502// Try to collect variable and constant offsets for \p GEP, partly traversing
503// nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
504// the offset fails.
506 OffsetResult Result(GEP, DL);
507 unsigned BitWidth = Result.ConstantOffset.getBitWidth();
508 if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
509 Result.ConstantOffset))
510 return {};
511
512 // If we have a nested GEP, check if we can combine the constant offset of the
513 // inner GEP with the outer GEP.
514 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
515 SmallMapVector<Value *, APInt, 4> VariableOffsets2;
516 APInt ConstantOffset2(BitWidth, 0);
517 bool CanCollectInner = InnerGEP->collectOffset(
518 DL, BitWidth, VariableOffsets2, ConstantOffset2);
519 // TODO: Support cases with more than 1 variable offset.
520 if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
521 VariableOffsets2.size() > 1 ||
522 (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
523 // More than 1 variable index, use outer result.
524 return Result;
525 }
526 // The GEPs' wrap flags do not prevent the sum of the offsets from
527 // sign-wrapping.
528 bool Overflow = false;
529 APInt CombinedOffset =
530 Result.ConstantOffset.sadd_ov(ConstantOffset2, Overflow);
531 if (Overflow)
532 return Result;
533
534 Result.BasePtr = InnerGEP->getPointerOperand();
535 Result.ConstantOffset = CombinedOffset;
536 if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
537 Result.VariableOffsets = std::move(VariableOffsets2);
538 Result.NW &= InnerGEP->getNoWrapFlags();
539 }
540 return Result;
541}
542
543static Decomposition decompose(Value *V, ConstraintInfo &Info, bool IsSigned,
544 const DataLayout &DL);
545
546static bool canUseSExt(ConstantInt *CI) {
547 const APInt &Val = CI->getValue();
549}
550
551/// Returns true if `Op <= MaxVal - Slack` holds in the system for \p Signed, by
552/// scanning it for a row of the form `Op - W <= -Slack`, where W is an integer
553/// variable no wider than \p Op. If \p Upper is false, returns true if
554/// `Op >= MinVal + Slack` holds, using rows of the form `W - Op <= -Slack`.
555static bool hasLimitWitness(const ConstraintInfo &Info, Value *Op,
556 const APInt &Slack, bool Signed, bool Upper) {
557 if (!Slack.isIntN(63))
558 return false;
559 int64_t RequiredOffset = -static_cast<int64_t>(Slack.getZExtValue());
560
561 const auto &Value2Index = Info.getValue2Index(Signed);
562 unsigned OpIdx = Value2Index.lookup(Op);
563 if (!OpIdx)
564 return false;
565
566 int64_t OpCoefficient = Upper ? 1 : -1;
567 unsigned OpSize = Op->getType()->getScalarSizeInBits();
568
569 for (ArrayRef<Entry> Row : Info.getCS(Signed).getConstraints()) {
570 // Match `OpCoefficient * (Op - W) <= C` with C <= -Slack.
571 if (Row.size() != 3 || Row[0].Id != 0 ||
572 Row[0].Coefficient > RequiredOffset)
573 continue;
574 bool OpFirst = Row[1].Id == OpIdx;
575 const Entry &OpE = Row[OpFirst ? 1 : 2];
576 const Entry &WitnessE = Row[OpFirst ? 2 : 1];
577 if (OpE.Id != OpIdx || OpE.Coefficient != OpCoefficient ||
578 WitnessE.Coefficient != -OpCoefficient)
579 continue;
580
581 auto Witness = find_if(
582 Value2Index, [&](const auto &KV) { return KV.second == WitnessE.Id; });
583 assert(Witness != Value2Index.end() && "row variables must be mapped");
584 Type *WitnessTy = Witness->first->getType();
585 if (WitnessTy->isIntegerTy() && WitnessTy->getIntegerBitWidth() <= OpSize)
586 return true;
587 }
588 return false;
589}
590
591/// Returns true if \p Info implies that \p Op is in \p R, interpreting \p R as
592/// a signed range if \p Signed is set and as an unsigned range otherwise.
593static bool doesHoldInRange(ConstraintInfo &Info, Value *Op,
594 const ConstantRange &R, bool Signed) {
595 if (R.isEmptySet() || (Signed ? R.isSignWrappedSet() : R.isWrappedSet()))
596 return false;
597
598 if (R.isFullSet())
599 return true;
600
601 unsigned BitWidth = R.getBitWidth();
602 APInt Min = Signed ? R.getSignedMin() : R.getUnsignedMin();
603 APInt Max = Signed ? R.getSignedMax() : R.getUnsignedMax();
608 // What a witness has to bridge; computed before Max is clamped below.
609 APInt UpperSlack = MaxVal - Max;
610 // Replace bound too large to be decomposed by the largest usable one.
611 if (!Signed && Max.uge(MaxConstraintValue))
613
614 Type *Ty = Op->getType();
615 if (Min != MinVal &&
616 !Info.doesHold(Signed ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE, Op,
617 ConstantInt::get(Ty, Min)) &&
618 !hasLimitWitness(Info, Op, Min - MinVal, Signed, /*Upper=*/false))
619 return false;
620 if (Max != MaxVal &&
621 !Info.doesHold(Signed ? CmpInst::ICMP_SLE : CmpInst::ICMP_ULE, Op,
622 ConstantInt::get(Ty, Max)) &&
623 !hasLimitWitness(Info, Op, UpperSlack, Signed, /*Upper=*/true))
624 return false;
625 return true;
626}
627
628/// Returns true if \p Opcode applied to \p Op0 and \p Op1 with \p NoWrapFlags
629/// is known to not wrap in signed or unsigned, depending on \p Signed.
630static bool isKnownNoWrap(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
631 unsigned NoWrapFlags, ConstraintInfo &Info,
632 bool Signed) {
633 using OBO = OverflowingBinaryOperator;
634
635 if (NoWrapFlags & (Signed ? OBO::NoSignedWrap : OBO::NoUnsignedWrap))
636 return true;
637
638 if (Opcode == Instruction::Sub) {
639 // Op0 - Op1 does not wrap unsigned if Op0 >=u Op1.
640 if (!Signed)
641 return Info.doesHold(CmpInst::ICMP_UGE, Op0, Op1);
642
643 // Op0 - Op1 does not wrap signed if 0 <=s Op1 <=s Op0.
644 if (Info.isKnownNonNegative(Op1) &&
645 Info.doesHold(CmpInst::ICMP_SGE, Op0, Op1))
646 return true;
647 }
648
649 if (!Signed && (NoWrapFlags & OBO::NoSignedWrap) &&
650 (Opcode == Instruction::Shl || Info.isKnownNonNegative(Op1)) &&
651 Info.isKnownNonNegative(Op0))
652 return true;
653
654 // For a constant Op1, the ranges of Op0 for which the operation does not
655 // wrap are known exactly; check if the systems imply one of them.
656 auto *C = dyn_cast<ConstantInt>(Op1);
657 if (!C)
658 return false;
659
660 return doesHoldInRange(Info, Op0,
662 Opcode, C->getValue(),
663 Signed ? OBO::NoSignedWrap : OBO::NoUnsignedWrap),
664 Signed);
665}
666
667/// Returns true if \p V is known to not wrap in signed or unsigned, depending
668/// on \p Signed.
669static bool isKnownNoWrap(Value *V, ConstraintInfo &Info, bool Signed) {
670 if (match(V, m_DisjointOr(m_Value(), m_Value())))
671 return true;
672
673 if (auto *WO = dyn_cast<WithOverflowInst>(V))
674 return isKnownNoWrap(WO->getBinaryOp(), WO->getLHS(), WO->getRHS(),
675 /*NoWrapFlags=*/0, Info, Signed);
676
677 if (auto *Trunc = dyn_cast<TruncInst>(V)) {
678 if (Signed)
679 return Trunc->hasNoSignedWrap();
680
681 // A trunc nsw only truncates without unsigned wrap if its operand is
682 // non-negative.
683 return Trunc->hasNoUnsignedWrap() ||
684 (Trunc->hasNoSignedWrap() &&
685 Info.isKnownNonNegative(Trunc->getOperand(0)));
686 }
687
689 return BO &&
690 isKnownNoWrap(static_cast<Instruction::BinaryOps>(BO->getOpcode()),
691 BO->getOperand(0), BO->getOperand(1),
692 BO->getNoWrapKind(), Info, Signed);
693}
694
695static Decomposition decomposeGEP(GEPOperator &GEP, ConstraintInfo &Info,
696 bool IsSigned, const DataLayout &DL) {
697 // Do not reason about pointers where the index size is larger than 64 bits,
698 // as the coefficients used to encode constraints are 64 bit integers.
699 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
700 return &GEP;
701
702 assert(!IsSigned && "The logic below only supports decomposition for "
703 "unsigned predicates at the moment.");
704 const auto &[BasePtr, ConstantOffset, VariableOffsets, NW] =
706 // We support either plain gep nuw, or gep nusw with non-negative offset,
707 // which implies gep nuw.
708 if (!BasePtr || NW == GEPNoWrapFlags::none())
709 return &GEP;
710
711 // For a nuw-only GEP (nuw without nusw/inbounds), the offset must be
712 // interpreted as unsigned.
713 if (!NW.hasNoUnsignedSignedWrap() && ConstantOffset.isNegative())
714 return &GEP;
715
716 Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
717 for (auto [Index, Scale] : VariableOffsets) {
718 // Indices narrower or wider than the index type are implicitly
719 // sign-extended or truncated. Don't reason about them.
720 if (Index->getType()->getScalarSizeInBits() != Scale.getBitWidth())
721 return &GEP;
722 if (!NW.hasNoUnsignedWrap()) {
723 // Try to prove nuw from nusw and nneg. If the index cannot be proven
724 // non-negative, keep the GEP as-is instead of decomposing it.
725 assert(NW.hasNoUnsignedSignedWrap() && "Must have nusw flag");
726 if (!Info.isKnownNonNegative(Index))
727 return &GEP;
728 } else if (!NW.hasNoUnsignedSignedWrap()) {
729 // For a nuw-only GEP, the scale is unsigned and must fit in the signed
730 // coefficient.
731 if (Scale.isNegative())
732 return &GEP;
733 }
734
735 auto IdxResult = decompose(Index, Info, IsSigned, DL);
736 if (IdxResult.mul(Scale.getSExtValue()))
737 return &GEP;
738 if (Result.add(IdxResult))
739 return &GEP;
740 }
741 return Result;
742}
743
744// Decomposes \p V into a constant offset + list of pairs { Coefficient,
745// Variable } where Coefficient * Variable. The sum of the constant offset and
746// pairs equals \p V.
747//
748// Looking through certain expressions is only valid if a pre-condition holds.
749// Pre-conditions are checked against \p Info as needed.
750static Decomposition decomposeImpl(Value *V, ConstraintInfo &Info,
751 bool IsSigned, const DataLayout &DL);
752
753/// Returns true if \p V is an operation decomposeImpl can look through.
754static bool mayLookThrough(Value *V) {
755 auto *Op = dyn_cast<Operator>(V);
756 if (!Op)
757 return false;
758 switch (Op->getOpcode()) {
759 case Instruction::GetElementPtr:
760 case Instruction::Add:
761 case Instruction::Sub:
762 case Instruction::Mul:
763 case Instruction::Shl:
764 case Instruction::LShr:
765 case Instruction::AShr:
766 case Instruction::ZExt:
767 case Instruction::SExt:
768 case Instruction::Trunc:
769 case Instruction::Or:
770 case Instruction::Xor:
771 return true;
772 default:
773 return false;
774 }
775}
776
777static Decomposition decompose(Value *V, ConstraintInfo &Info, bool IsSigned,
778 const DataLayout &DL) {
779 if (!mayLookThrough(V))
780 return decomposeImpl(V, Info, IsSigned, DL);
781
783 auto &Cache = Info.getDecomposeCache();
784 auto It = Cache.find(Key);
785 if (It != Cache.end())
786 return It->second;
787
788 unsigned HitsBefore = Info.getNumDepthLimitHits();
789 Decomposition Result = decomposeImpl(V, Info, IsSigned, DL);
790 // If a doesHold query was cut off while decomposing, the result may be less
791 // precise than what a shallower query could compute, so don't cache it.
792 if (Info.getNumDepthLimitHits() == HitsBefore)
793 Info.getDecomposeCache().insert({Key, Result});
794 return Result;
795}
796
797static Decomposition decomposeImpl(Value *V, ConstraintInfo &Info,
798 bool IsSigned, const DataLayout &DL) {
799 auto MergeResults = [&Info, IsSigned,
800 &DL](Value *A, Value *B,
801 bool IsSignedB) -> std::optional<Decomposition> {
802 auto ResA = decompose(A, Info, IsSigned, DL);
803 auto ResB = decompose(B, Info, IsSignedB, DL);
804 if (ResA.add(ResB))
805 return std::nullopt;
806 return ResA;
807 };
808
809 Type *Ty = V->getType()->getScalarType();
810 if (Ty->isPointerTy() && !IsSigned) {
811 if (auto *GEP = dyn_cast<GEPOperator>(V))
812 return decomposeGEP(*GEP, Info, IsSigned, DL);
814 return int64_t(0);
815
816 return V;
817 }
818
819 // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
820 // coefficient add/mul may wrap, while the operation in the full bit width
821 // would not.
822 if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
823 return V;
824
825 if (auto *CI = dyn_cast<ConstantInt>(V)) {
826 if (IsSigned) {
827 if (canUseSExt(CI))
828 return CI->getSExtValue();
829 } else if (!CI->uge(MaxConstraintValue)) {
830 return int64_t(CI->getZExtValue());
831 }
832 return V;
833 }
834
835 Value *Op0;
836 Value *Op1;
837 ConstantInt *CI;
838
839 if (match(V, m_ZExt(m_Value(Op0)))) {
840 // In the signed system, the ZExt must be non-negative.
841 if (IsSigned && !cast<ZExtInst>(V)->hasNonNeg())
842 return V;
843 V = Op0;
844 } else if (match(V, m_SExt(m_Value(Op0)))) {
845 // In the unsigned system, the SExt operand must be non-negative.
846 if (!IsSigned && !Info.isKnownNonNegative(Op0))
847 return V;
848 V = Op0;
849 } else if (auto *Trunc = dyn_cast<TruncInst>(V)) {
850 if (Trunc->getSrcTy()->getScalarSizeInBits() <= 64 &&
851 isKnownNoWrap(Trunc, Info, IsSigned))
852 V = Trunc->getOperand(0);
853 }
854
855 if (match(V, m_AddLike(m_Value(Op0), m_Value(Op1)))) {
856 if (isKnownNoWrap(V, Info, IsSigned)) {
857 if (auto Decomp = MergeResults(Op0, Op1, IsSigned))
858 return *Decomp;
859 return V;
860 }
861 // In the unsigned system, adding a negative constant only wraps if Op0 is
862 // smaller than it.
863 if (!IsSigned && match(Op1, m_ConstantInt(CI)) && CI->isNegative() &&
864 canUseSExt(CI) &&
865 Info.doesHold(CmpInst::ICMP_UGE, Op0,
866 ConstantInt::get(Op0->getType(), -CI->getSExtValue())))
867 if (auto Decomp = MergeResults(Op0, CI, /*IsSignedB=*/true))
868 return *Decomp;
869 return V;
870 }
871
872 // `xor %x, -1` is equivalent to `sub nsw -1, %x`.
873 if (IsSigned && match(V, m_Not(m_Value(Op0)))) {
874 Decomposition Result(-1);
875 if (!Result.sub(decompose(Op0, Info, IsSigned, DL)))
876 return Result;
877 return V;
878 }
879
880 if (match(V, m_Sub(m_Value(Op0), m_Value(Op1)))) {
881 if (isKnownNoWrap(V, Info, IsSigned)) {
882 auto ResA = decompose(Op0, Info, IsSigned, DL);
883 auto ResB = decompose(Op1, Info, IsSigned, DL);
884 if (!ResA.sub(ResB))
885 return ResA;
886 }
887 return V;
888 }
889
890 if (match(V, m_Mul(m_Value(Op0), m_ConstantInt(CI)))) {
891 // A negative constant is only a valid coefficient in the signed system; in
892 // the unsigned system the multiplier is the constant's unsigned value.
893 if (canUseSExt(CI) && (IsSigned || !CI->isNegative()) &&
894 isKnownNoWrap(V, Info, IsSigned)) {
895 auto Result = decompose(Op0, Info, IsSigned, DL);
896 if (!Result.mul(CI->getSExtValue()))
897 return Result;
898 }
899 return V;
900 }
901
902 if (match(V, m_Exact(m_Shr(m_Value(Op0), m_ConstantInt(CI))))) {
903 bool IsAShr = cast<Operator>(V)->getOpcode() == Instruction::AShr;
904 if (CI->getValue().ult(std::min(63u, CI->getBitWidth())) &&
905 (IsSigned == IsAShr || Info.isKnownNonNegative(Op0))) {
906 int64_t Factor = int64_t(1) << CI->getZExtValue();
907 auto Result = decompose(Op0, Info, IsSigned, DL);
908 if (Result.Offset % Factor == 0 &&
909 all_of(Result.Vars, [Factor](const DecompEntry &E) {
910 return E.Coefficient % Factor == 0;
911 })) {
912 Result.Offset /= Factor;
913 for (auto &E : Result.Vars)
914 E.Coefficient /= Factor;
915 return Result;
916 }
917 }
918 return V;
919 }
920
921 if (match(V, m_Shl(m_Value(Op0), m_ConstantInt(CI)))) {
922 // (shl x, shift) is (mul x, 1 << shift). The scale must fit in the signed
923 // coefficient, so reject shifts >= 63. Also reject a shift of bw-1, for
924 // which the product is not representable.
925 int64_t MaxShift = IsSigned ? Ty->getIntegerBitWidth() - 1 : 63;
926 if (!CI->isNegative() && CI->getSExtValue() < MaxShift &&
927 isKnownNoWrap(V, Info, IsSigned)) {
928 auto Result = decompose(Op0, Info, IsSigned, DL);
929 if (!Result.mul(int64_t{1} << CI->getSExtValue()))
930 return Result;
931 }
932 return V;
933 }
934
935 return V;
936}
937
938/// Build the row for 'ADec <= BDec', using the indices from \p Value2Index.
939/// Variables not in \p Value2Index are appended to \p NewVariables and get the
940/// indices following the ones in \p Value2Index. Returns an empty row if the
941/// coefficients overflow.
942static RowTy getRowForLessEqual(const Decomposition &ADec,
943 const Decomposition &BDec,
944 const DenseMap<Value *, unsigned> &Value2Index,
945 SmallVectorImpl<Value *> &NewVariables) {
946 // Build the row, by first adding all coefficients from A and then subtracting
947 // all coefficients from B.
948 int64_t OffsetSum;
949 if (SubOverflow(BDec.Offset, ADec.Offset, OffsetSum))
950 return {};
951 RowTy R(1, Entry(OffsetSum, 0));
952 auto GetCoefficient = [&R](unsigned Idx) -> int64_t & {
953 // The entry for Idx, or the place to insert it at, is the first entry with
954 // an index >= Idx.
955 Entry *I =
956 find_if(drop_begin(R), [Idx](const Entry &E) { return E.Id >= Idx; });
957 if (I == R.end() || I->Id != Idx)
958 I = R.insert(I, Entry(0, Idx));
959 return I->Coefficient;
960 };
961 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
962 // new entry to NewVariables.
963 auto GetOrAddIndex = [&Value2Index, &NewVariables](Value *V) -> unsigned {
964 auto V2I = Value2Index.find(V);
965 if (V2I != Value2Index.end())
966 return V2I->second;
967 unsigned Idx = find(NewVariables, V) - NewVariables.begin();
968 if (Idx == NewVariables.size())
969 NewVariables.push_back(V);
970 return Value2Index.size() + Idx + 1;
971 };
972 for (const DecompEntry &KV : ADec.Vars)
973 GetCoefficient(GetOrAddIndex(KV.Variable)) += KV.Coefficient;
974
975 for (const DecompEntry &KV : BDec.Vars) {
976 auto &Coeff = GetCoefficient(GetOrAddIndex(KV.Variable));
977 if (SubOverflow(Coeff, KV.Coefficient, Coeff))
978 return {};
979 }
980
981 // Drop coefficients that cancelled out.
982 erase_if(R, [](const Entry &E) { return E.Id != 0 && E.Coefficient == 0; });
983 return R;
984}
985
986ConstraintTy
987ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
988 SmallVectorImpl<Value *> &NewVariables,
989 bool ForceSignedSystem) {
990 assert(NewVariables.empty() && "NewVariables must be empty when passed in");
991 assert((!ForceSignedSystem || CmpInst::isEquality(Pred)) &&
992 "signed system can only be forced on eq/ne");
993
994 bool IsEq = false;
995 bool IsNe = false;
996
997 // Try to convert Pred to one of ULE/ULT/SLE/SLT.
998 switch (Pred) {
1000 case CmpInst::ICMP_UGE:
1001 case CmpInst::ICMP_SGT:
1002 case CmpInst::ICMP_SGE: {
1004 std::swap(Op0, Op1);
1005 break;
1006 }
1007 case CmpInst::ICMP_EQ:
1008 if (!ForceSignedSystem && match(Op1, m_Zero())) {
1010 } else {
1011 IsEq = true;
1013 }
1014 break;
1015 case CmpInst::ICMP_NE:
1016 if (!ForceSignedSystem && match(Op1, m_Zero())) {
1018 std::swap(Op0, Op1);
1019 } else {
1020 IsNe = true;
1022 }
1023 break;
1024 default:
1025 break;
1026 }
1027
1030 return {};
1031
1032 bool IsSigned = ForceSignedSystem || CmpInst::isSigned(Pred);
1033 auto &Value2Index = getValue2Index(IsSigned);
1034 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), *this,
1035 IsSigned, DL);
1036 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), *this,
1037 IsSigned, DL);
1038 RowTy R = getRowForLessEqual(ADec, BDec, Value2Index, NewVariables);
1039 if (R.empty())
1040 return {};
1041
1043 if (AddOverflow(R[0].Coefficient, int64_t(-1), R[0].Coefficient))
1044 return {};
1045
1046 // Remove any new variable without a coefficient in the row.
1047 unsigned NumV2I = Value2Index.size();
1048 NewVariables.truncate(R.back().Id > NumV2I ? R.back().Id - NumV2I : 0);
1049
1050 return ConstraintTy(std::move(R), Value2Index.size() + NewVariables.size(),
1051 IsSigned, IsEq, IsNe);
1052}
1053
1054ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
1055 Value *Op0, Value *Op1) {
1056 Constant *NullC = Constant::getNullValue(Op0->getType());
1057 // Handle trivially true compares directly to avoid adding V UGE 0 constraints
1058 // for all variables in the unsigned system.
1059 if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
1060 (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
1061 // Return constraint that's trivially true.
1062 return ConstraintTy(RowTy(1, Entry(0, 0)), /*NumVars=*/0,
1063 /*IsSigned=*/false, /*IsEq=*/false, /*IsNe=*/false);
1064 }
1065
1066 // If both operands are known to be non-negative, change signed predicates to
1067 // unsigned ones. This increases the reasoning effectiveness in combination
1068 // with the signed <-> unsigned transfer logic.
1069 if (CmpInst::isSigned(Pred) &&
1070 ::isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
1073
1074 SmallVector<Value *> NewVariables;
1075 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
1076 if (!NewVariables.empty())
1077 return {};
1078 return R;
1079}
1080
1081std::optional<bool>
1082ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
1083 const auto &[SubCS, NewCoefficients] = CS.getSubSystem(Coefficients);
1084 bool IsConditionImplied = SubCS.isConditionImplied(NewCoefficients);
1085
1086 if (IsEq || IsNe) {
1087 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(NewCoefficients);
1088 bool IsNegatedOrEqualImplied =
1089 !NegatedOrEqual.empty() && SubCS.isConditionImplied(NegatedOrEqual);
1090
1091 // In order to check that `%a == %b` is true (equality), both conditions `%a
1092 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
1093 // is true), we return true if they both hold, false in the other cases.
1094 if (IsConditionImplied && IsNegatedOrEqualImplied)
1095 return IsEq;
1096
1097 auto Negated = ConstraintSystem::negate(NewCoefficients);
1098 bool IsNegatedImplied =
1099 !Negated.empty() && SubCS.isConditionImplied(Negated);
1100
1101 auto StrictLessThan = ConstraintSystem::toStrictLessThan(NewCoefficients);
1102 bool IsStrictLessThanImplied =
1103 !StrictLessThan.empty() && SubCS.isConditionImplied(StrictLessThan);
1104
1105 // In order to check that `%a != %b` is true (non-equality), either
1106 // condition `%a > %b` or `%a < %b` must hold true. When checking for
1107 // non-equality (`IsNe` is true), we return true if one of the two holds,
1108 // false in the other cases.
1109 if (IsNegatedImplied || IsStrictLessThanImplied)
1110 return IsNe;
1111
1112 return std::nullopt;
1113 }
1114
1115 if (IsConditionImplied)
1116 return true;
1117
1118 auto Negated = ConstraintSystem::negate(NewCoefficients);
1119 auto IsNegatedImplied = !Negated.empty() && SubCS.isConditionImplied(Negated);
1120 if (IsNegatedImplied)
1121 return false;
1122
1123 // Neither the condition nor its negated holds, did not prove anything.
1124 return std::nullopt;
1125}
1126
1127static RowTy getDecompositionLinkRow(Value *V, const ConstraintTy &C,
1128 ConstraintInfo &Info,
1129 const DataLayout &DL);
1130
1131std::optional<bool>
1132ConstraintInfo::tryWithLinkRows(Value *A, Value *B, const ConstraintTy &C,
1133 function_ref<std::optional<bool>()> Solve) {
1134 if (std::optional<bool> Res = Solve())
1135 return Res;
1136 if (C.empty())
1137 return std::nullopt;
1138
1139 auto &CS = getCS(C.IsSigned);
1140 unsigned NumVars = getValue2Index(C.IsSigned).size();
1141 unsigned NumPushed = 0;
1142 for (Value *V : {A, B}) {
1143 RowTy Row = getDecompositionLinkRow(V, C, *this, DL);
1144 RowTy Negated = ConstraintSystem::negateOrEqual(Row);
1145 if (Row.empty() || Negated.empty())
1146 continue;
1147 NumPushed += CS.addRow(Row, NumVars);
1148 NumPushed += CS.addRow(Negated, NumVars);
1149 }
1150 if (NumPushed == 0)
1151 return std::nullopt;
1152#ifndef NDEBUG
1153 unsigned NumRows = CS.size();
1154#endif
1155 std::optional<bool> Res = Solve();
1156 assert(CS.size() == NumRows && "rows added while link rows are pushed");
1157 while (NumPushed--)
1158 CS.popLastConstraint();
1159 return Res;
1160}
1161
1162bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, Value *B) {
1163 // Decomposing A and B may itself call doesHold, once per level of a chain of
1164 // operations. Cut off deep nesting to bound stack usage and compile time.
1165 if (DoesHoldDepth >= MaxDoesHoldDepth) {
1166 ++NumDoesHoldDepthLimitHit;
1167 ++NumDepthLimitHits;
1168 return false;
1169 }
1170 SaveAndRestore DepthScope(DoesHoldDepth, DoesHoldDepth + 1);
1171
1172 auto R = getConstraintForSolving(Pred, A, B);
1173 if (R.empty())
1174 return false;
1175 auto &CS = getCS(R.IsSigned);
1176 return tryWithLinkRows(A, B, R,
1177 [&]() -> std::optional<bool> {
1178 if (CS.isConditionImpliedInSubSystem(R.Coefficients))
1179 return true;
1180 return std::nullopt;
1181 })
1182 .value_or(false);
1183}
1184
1185bool ConstraintInfo::isKnownNonNegative(Value *V) {
1186 if (auto *CI = dyn_cast<ConstantInt>(V))
1187 return !CI->isNegative();
1188 return ::isKnownNonNegative(V, DL) ||
1189 doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0));
1190}
1191
1192bool ConstraintInfo::isKnownPositive(Value *V) {
1193 if (auto *CI = dyn_cast<ConstantInt>(V))
1194 return CI->getValue().isStrictlyPositive();
1195 return ::isKnownPositive(V, DL) ||
1196 doesHold(CmpInst::ICMP_SGT, V, ConstantInt::get(V->getType(), 0));
1197}
1198
1199std::optional<bool> ConstraintInfo::getKnownSign(Value *V) {
1200 KnownBits Known = computeKnownBits(V, DL);
1201 if (Known.isNonNegative())
1202 return false;
1203 if (Known.isNegative())
1204 return true;
1205 Constant *Zero = ConstantInt::get(V->getType(), 0);
1206 if (doesHold(CmpInst::ICMP_SGE, V, Zero))
1207 return false;
1208 if (doesHold(CmpInst::ICMP_SLT, V, Zero))
1209 return true;
1210 return std::nullopt;
1211}
1212
1213void ConstraintInfo::transferToOtherSystem(
1214 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
1215 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
1216 // Check if we can combine facts from the signed and unsigned systems to
1217 // derive additional facts.
1218 if (!A->getType()->isIntegerTy())
1219 return;
1220 // FIXME: This currently depends on the order we add facts. Ideally we
1221 // would first add all known facts and only then try to add additional
1222 // facts.
1223 switch (Pred) {
1224 default:
1225 break;
1226 case CmpInst::ICMP_ULT:
1227 case CmpInst::ICMP_ULE:
1228 // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
1229 if (isKnownNonNegative(B)) {
1230 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
1231 NumOut, DFSInStack);
1232 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
1233 DFSInStack);
1234 }
1235 break;
1236 case CmpInst::ICMP_UGE:
1237 case CmpInst::ICMP_UGT:
1238 // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
1239 if (isKnownNonNegative(A)) {
1240 addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
1241 NumOut, DFSInStack);
1242 addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
1243 DFSInStack);
1244 }
1245 break;
1246 case CmpInst::ICMP_SLT:
1247 case CmpInst::ICMP_SLE:
1248 if (isKnownNonNegative(A))
1249 addFact(ICmpInst::getUnsignedPredicate(Pred), A, B, NumIn, NumOut,
1250 DFSInStack);
1251 break;
1252 case CmpInst::ICMP_SGT: {
1253 if (doesHold(CmpInst::ICMP_SGE, B, Constant::getAllOnesValue(B->getType())))
1254 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
1255 NumOut, DFSInStack);
1256 if (isKnownNonNegative(B))
1257 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
1258
1259 break;
1260 }
1261 case CmpInst::ICMP_SGE:
1262 if (isKnownNonNegative(B))
1263 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
1264 break;
1265 }
1266}
1267
1268#ifndef NDEBUG
1269
1271 const DenseMap<Value *, unsigned> &Value2Index) {
1272 ConstraintSystem CS(Value2Index);
1273 CS.addRow(C, Value2Index.size());
1274 CS.dump();
1275}
1276#endif
1277
1278/// Splits the induction phi \p PN into the start value, coming from the loop
1279/// predecessor \p LoopPred, and the backedge value, coming from inside the
1280/// loop. Returns {nullptr, nullptr} if \p PN has other incoming values.
1281static std::pair<Value *, Value *>
1282getStartAndBackedgeValue(const PHINode &PN, const BasicBlock *LoopPred) {
1283 assert(PN.getBasicBlockIndex(LoopPred) >= 0 &&
1284 "LoopPred must be a predecessor of the phi's block");
1285 if (PN.getNumIncomingValues() != 2)
1286 return {nullptr, nullptr};
1287 unsigned StartIdx = PN.getIncomingBlock(0) == LoopPred ? 0 : 1;
1288 return {PN.getIncomingValue(StartIdx), PN.getIncomingValue(1 - StartIdx)};
1289}
1290
1291/// Matches an increment of \p PhiM by a constant offset, captured in \p Off.
1292/// The increment must be a plain IR add or [u|s]add.with.overflow.
1293template <typename PhiMatchTy>
1294static auto m_IncrementOf(const PhiMatchTy &PhiM, const APInt *&Off) {
1295 return m_CombineOr(
1296 m_c_Add(PhiM, m_APInt(Off)),
1300}
1301
1302MonotonicInfo State::getMonotonicityInfo(PHINode &PN, Value *Step) {
1303 MonotonicInfo Info;
1304 const APInt *StepOffset = nullptr;
1305 if (match(Step, m_IncrementOf(m_Specific(&PN), StepOffset))) {
1306 Info.Decreasing = StepOffset->isNegative();
1307 if (const auto *Add = dyn_cast<OverflowingBinaryOperator>(Step)) {
1308 Info.Unsigned = !Info.Decreasing && Add->hasNoUnsignedWrap();
1309 Info.Signed = Add->hasNoSignedWrap();
1310 }
1311 } else if (const auto *GEP = dyn_cast<GEPOperator>(Step)) {
1312 // TODO: Handle the non-increasing direction, which needs a nusw GEP with a
1313 // negative constant offset.
1314 const DataLayout &DL = PN.getDataLayout();
1315 APInt GEPOffset(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
1316 Info.Unsigned = GEP->getPointerOperand() == &PN &&
1317 (GEP->hasNoUnsignedWrap() ||
1318 ((GEP->hasNoUnsignedSignedWrap() &&
1319 GEP->accumulateConstantOffset(DL, GEPOffset) &&
1320 !GEPOffset.isNegative())));
1321 }
1322
1323 // Forming the SCEV of a phi is expensive, so only consult it for a PN + C
1324 // step whose no-wrap flags prove nothing.
1325 if (Info.Unsigned || Info.Signed || !StepOffset)
1326 return Info;
1327
1328 const auto *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&PN));
1329 if (!AR)
1330 return Info;
1334 auto IsMonotonic = [&](CmpInst::Predicate Pred) {
1335 return SE->getMonotonicPredicateType(AR, Pred) == Expected;
1336 };
1337 Info.Signed = IsMonotonic(CmpInst::ICMP_SGT);
1338 Info.Unsigned = !Info.Decreasing && IsMonotonic(CmpInst::ICMP_UGT);
1339 return Info;
1340}
1341
1342void State::addBoundsForHeaderInductions(BasicBlock &BB) {
1343 Loop *L = LI.getLoopFor(&BB);
1344 if (!L || L->getHeader() != &BB)
1345 return;
1346 BasicBlock *LoopPred = L->getLoopPredecessor();
1347 if (!LoopPred)
1348 return;
1349
1350 DomTreeNode *DTN = DT.getNode(&BB);
1351 for (PHINode &PN : BB.phis()) {
1352 if (!PN.getType()->isIntegerTy() && !PN.getType()->isPointerTy())
1353 continue;
1354
1355 auto [Start, Step] = getStartAndBackedgeValue(PN, LoopPred);
1356 if (!Start)
1357 continue;
1358
1359 MonotonicInfo Info = getMonotonicityInfo(PN, Step);
1360 // Every variable in the unsigned system already has a `V >= 0` row, so a
1361 // zero start value would just duplicate it.
1362 if (match(Start, m_Zero()))
1363 Info.Unsigned = false;
1364 if (!Info.Unsigned && !Info.Signed)
1365 continue;
1366
1367 // A non-decreasing induction cannot step below its start value, and a
1368 // non-increasing one cannot step above it.
1369 Value *LHS = &PN, *RHS = Start;
1370 if (Info.Decreasing)
1371 std::swap(LHS, RHS);
1372 CmpPredicate Pred(Info.Unsigned ? CmpInst::ICMP_UGE : CmpInst::ICMP_SGE,
1373 /*HasSameSign=*/Info.Unsigned && Info.Signed);
1374 WorkList.push_back(FactOrCheck::getConditionFact(DTN, Pred, LHS, RHS));
1375 }
1376}
1377
1378void State::addInfoForInductions(BasicBlock &BB) {
1379 auto *L = LI.getLoopFor(&BB);
1380 if (!L)
1381 return;
1382
1383 BasicBlock *Header = L->getHeader();
1384 BasicBlock *Latch = L->getLoopLatch();
1385 if (Header != &BB && Latch != &BB)
1386 return;
1387
1388 // A is either a phi or a post-increment PN + C with constant step. For the
1389 // latter, extract the constant IncStep.
1390 Value *A;
1391 Value *B;
1392 PHINode *PN = nullptr;
1393 const APInt *IncStep = nullptr;
1394 CmpPredicate Pred;
1395 auto IndValue =
1396 m_Value(A, m_CombineOr(m_Phi(PN), m_IncrementOf(m_Phi(PN), IncStep)));
1397
1398 auto *Br = dyn_cast<CondBrInst>(BB.getTerminator());
1399 if (!Br)
1400 return;
1401
1402 auto CountingCmp = m_c_ICmp(Pred, IndValue, m_Value(B));
1403 std::optional<bool> PeeledOnEdge;
1404 if (!match(Br->getCondition(), CountingCmp)) {
1405 // Look through AND/OR, and remember which edge requires all operands to be
1406 // true.
1407 if (match(Br->getCondition(), m_c_LogicalAnd(CountingCmp, m_Value())))
1408 PeeledOnEdge = true;
1409 else if (match(Br->getCondition(), m_c_LogicalOr(CountingCmp, m_Value())))
1410 PeeledOnEdge = false;
1411 else
1412 return;
1413 }
1414
1415 if (PN->getParent() != Header || PN->getNumIncomingValues() != 2 ||
1416 !SE->isSCEVable(PN->getType()))
1417 return;
1418
1419 bool ContinueOnTrue =
1421 CmpInst::Predicate ContinuePred =
1422 ContinueOnTrue ? Pred.dropSameSign() : CmpInst::getInversePredicate(Pred);
1423 BasicBlock *InLoopSucc = Br->getSuccessor(ContinueOnTrue ? 0 : 1);
1424
1425 // The peeled condition only implies the compare on the edge where the
1426 // combined condition forces its operands, which must be the in-loop edge.
1427 if (PeeledOnEdge && *PeeledOnEdge != ContinueOnTrue)
1428 return;
1429
1430 if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB))
1431 return;
1432
1433 BasicBlock *LoopPred = L->getLoopPredecessor();
1434 if (!LoopPred || !L->isLoopInvariant(B))
1435 return;
1436
1437 auto [StartValue, Backedge] = getStartAndBackedgeValue(*PN, LoopPred);
1438 DomTreeNode *DTN = DT.getNode(InLoopSucc);
1439 DomTreeNode *HeaderDTN = DT.getNode(Header);
1440
1441 // BB is the header or the latch, so every iteration taking the backedge
1442 // checked PN ContinuePred B, which guarantees PN != B for NE and LT
1443 // predicates. For an increment by one, PN != B together with StartValue <= B
1444 // (added precondition) imply PN <= B.
1445 const APInt *Step;
1446 bool HasHeaderBound =
1447 !IncStep && match(Backedge, m_IncrementOf(m_Specific(PN), Step)) &&
1448 Step->isOne() &&
1449 (ContinuePred == CmpInst::ICMP_NE || ICmpInst::isLT(ContinuePred));
1450 if (HasHeaderBound) {
1452 WorkList.push_back(FactOrCheck::getConditionFact(
1453 HeaderDTN, BoundPred, PN, B, ConditionTy(BoundPred, StartValue, B)));
1454 }
1455
1456 // For latch conditions, we need to inject the condition that holds for the
1457 // next iteration into the header. We limit to post-inc conditions, for which
1458 // an original PN + Step != B condition results in a PN < B constraint in the
1459 // header, which also holds for the next loop iteration. This would no longer
1460 // be correct if the post-inc handling would inject a more precise PN + Step <
1461 // B constraint instead.
1462 if (&BB == Latch && !IncStep)
1463 return;
1464
1465 if (ICmpInst::isRelational(ContinuePred)) {
1466 if (A != Backedge)
1467 return;
1468
1469 // The condition ensures ContinuePred holds in the header on each iteration
1470 // other than the first. Together with a precondition on the start value
1471 // (StartValue ContinuePred B), we can add B as bound of PN.
1472 WorkList.push_back(FactOrCheck::getConditionFact(
1473 HeaderDTN, ContinuePred, PN, B,
1474 ConditionTy(ContinuePred, StartValue, B)));
1475
1476 // A signed bound can be translated to the unsigned system if PN is signed
1477 // non-decreasing (StartValue s<= PN s< B) and StartValue u< B holds.
1478 // Then StartValue, PN and B must all have the same sign.
1479 if (ICmpInst::isSigned(ContinuePred)) {
1480 assert((ContinuePred == CmpInst::ICMP_SLT ||
1481 ContinuePred == CmpInst::ICMP_SLE) &&
1482 "Expected a signed less-than continuation predicate");
1483 MonotonicInfo Info = getMonotonicityInfo(*PN, Backedge);
1484 if (Info.Signed && !Info.Decreasing) {
1486 WorkList.push_back(FactOrCheck::getConditionFact(
1487 HeaderDTN, UPred, PN, B, ConditionTy(UPred, StartValue, B)));
1488 }
1489 }
1490
1491 // A relational latch steps past B rather than landing on it, so none of the
1492 // reasoning below applies.
1493 return;
1494 }
1495
1496 const APInt *StepOffset = nullptr;
1497 const SCEV *StartSCEV = nullptr;
1498 if (match(Backedge, m_c_Add(m_Specific(PN), m_APInt(StepOffset)))) {
1499 if (StepOffset->isZero())
1500 return;
1501 } else {
1502 const SCEV *Expr = SE->getSCEV(PN);
1503 if (!match(Expr,
1504 m_scev_AffineAddRec(m_SCEV(StartSCEV), m_scev_APInt(StepOffset),
1505 m_SpecificLoop(L))))
1506 return;
1507 }
1508
1509 // If we looked through `PN + C`, only derive facts when that add is
1510 // really the induction's post-increment or post-decrement.
1511 if (IncStep && *IncStep != *StepOffset)
1512 return;
1513
1514 MonotonicInfo Info = getMonotonicityInfo(*PN, Backedge);
1515
1516 // Handle negative steps.
1517 if (StepOffset->isNegative()) {
1518 // TODO: Extend to allow steps > -1.
1519 if (!(-*StepOffset).isOne())
1520 return;
1521
1522 // AR may wrap.
1523 // The loop exits once the compared value reaches B, that is at PN == B when
1524 // comparing the phi, and at PN == B + 1 for a post-decrement. Use
1525 // non-strict predicate for the former, and a strict one for the latter to
1526 // ensure the loop exits before wrapping.
1527 CmpInst::Predicate UPrecond =
1529 ConditionTy BBeforeStartUnsigned = {UPrecond, B, StartValue};
1530 ConditionTy BBeforeStartSigned = {ICmpInst::getSignedPredicate(UPrecond), B,
1531 StartValue};
1532
1533 // AR may wrap, so both facts are conditional on B being below StartValue.
1534 // Add StartValue >= PN, which holds as the loop exits before wrapping.
1535 WorkList.push_back(FactOrCheck::getConditionFact(
1536 DTN, CmpInst::ICMP_UGE, StartValue, PN, BBeforeStartUnsigned));
1537 if (!(Info.Decreasing && Info.Signed))
1538 WorkList.push_back(FactOrCheck::getConditionFact(
1539 DTN, CmpInst::ICMP_SGE, StartValue, PN, BBeforeStartSigned));
1540 // Add PN > B, which holds as the loop exits when reaching B.
1541 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGT, PN,
1542 B, BBeforeStartUnsigned));
1543 WorkList.push_back(FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGT, PN,
1544 B, BBeforeStartSigned));
1545 return;
1546 }
1547
1548 // Make sure AR either steps by 1 or that the value we compare against is a
1549 // GEP based on the same start value and all offsets are a multiple of the
1550 // step size, to guarantee that the induction will reach the value.
1551 if (StepOffset->isZero() || StepOffset->isNegative())
1552 return;
1553
1554 if (!StepOffset->isOne()) {
1555 // Check whether B-Start is known to be a multiple of StepOffset.
1556 if (!StartSCEV)
1557 StartSCEV = SE->getSCEV(StartValue);
1558 const SCEV *BMinusStart = SE->getMinusSCEV(SE->getSCEV(B), StartSCEV);
1559 if (isa<SCEVCouldNotCompute>(BMinusStart) ||
1560 !SE->getConstantMultiple(BMinusStart).urem(*StepOffset).isZero())
1561 return;
1562 }
1563
1564 // We already established that B - Start is a multiple of Step above. The loop
1565 // exits once the compared value reaches B, that is at PN == B when comparing
1566 // the phi, and at PN + Step == B for a post-increment. Together with the
1567 // added precondition StartValue <= B for the former and the strict
1568 // StartValue < B for the latter (which implies StartValue + Step <= B),
1569 // neither PN nor the increment can wrap.
1571 ConditionTy StartBeforeBoundUnsigned = {UPrecond, StartValue, B};
1572 ConditionTy StartBeforeBoundSigned = {ICmpInst::getSignedPredicate(UPrecond),
1573 StartValue, B};
1574
1575 // Add PN >= StartValue, as the loop exits before wrapping.
1576 if (!Info.Unsigned)
1577 WorkList.push_back(FactOrCheck::getConditionFact(
1578 DTN, CmpInst::ICMP_UGE, PN, StartValue, StartBeforeBoundUnsigned));
1579 if (!Info.Signed)
1580 WorkList.push_back(FactOrCheck::getConditionFact(
1581 DTN, CmpInst::ICMP_SGE, PN, StartValue, StartBeforeBoundSigned));
1582 // Add PN < B, as the loop exits once the compared value reaches B. With a
1583 // header bound, the PN != B condition fact in InLoopSucc already tightens it
1584 // to PN < B.
1585 if (!HasHeaderBound || !canAddSuccessor(BB, InLoopSucc)) {
1586 WorkList.push_back(FactOrCheck::getConditionFact(
1587 DTN, CmpInst::ICMP_SLT, PN, B, StartBeforeBoundSigned));
1588 WorkList.push_back(FactOrCheck::getConditionFact(
1589 DTN, CmpInst::ICMP_ULT, PN, B, StartBeforeBoundUnsigned));
1590 }
1591
1592 // Try to add condition from the header or latch to the dedicated exit
1593 // blocks. When exiting either with EQ or NE, we know that the induction value
1594 // must be u<= B, as other exits may only exit earlier.
1595 assert(!StepOffset->isNegative() && "induction must be increasing");
1596 assert(ContinuePred == CmpInst::ICMP_NE && "unsupported predicate");
1597 // The header bound already implies PN u<= B in the exits.
1598 if (HasHeaderBound)
1599 return;
1601 L->getExitBlocks(ExitBBs);
1602 for (BasicBlock *EB : ExitBBs) {
1603 // Bail out on non-dedicated exits.
1604 if (DT.dominates(&BB, EB)) {
1605 WorkList.emplace_back(FactOrCheck::getConditionFact(
1606 DT.getNode(EB), CmpInst::ICMP_ULE, A, B, StartBeforeBoundUnsigned));
1607 }
1608 }
1609}
1610
1612 uint64_t AccessSize,
1614 Value *&B, const DataLayout &DL,
1615 const TargetLibraryInfo &TLI) {
1616 if (!GEP.hasNoUnsignedWrap())
1617 return false;
1618
1619 Value *Base = GEP.getPointerOperand();
1620 if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Base))
1621 Base = InnerGEP->getPointerOperand();
1622
1623 ObjectSizeOpts Opts;
1624 // Workaround for gep inbounds, ptr null, idx.
1625 Opts.NullIsUnknownSize = true;
1626 // Be conservative since we are not clear on whether an out of bounds access
1627 // to the padding is UB or not.
1628 Opts.RoundToAlign = true;
1629 std::optional<TypeSize> Size = getBaseObjectSize(Base, DL, &TLI, Opts);
1630 if (!Size || Size->isScalable())
1631 return false;
1632
1634 if (Offset.BasePtr != Base || !Offset.NW.hasNoUnsignedWrap())
1635 return false;
1636
1637 if (Offset.VariableOffsets.size() != 1)
1638 return false;
1639
1640 uint64_t BitWidth = Offset.ConstantOffset.getBitWidth();
1641 auto &[Index, Scale] = Offset.VariableOffsets.front();
1642 // Bail out on non-canonical GEPs.
1643 if (Index->getType()->getScalarSizeInBits() != BitWidth)
1644 return false;
1645
1646 // Index * Scale + ConstOffset + AccessSize <= AllocSize
1647 // With nuw flag, we know that the index addition doesn't have unsigned wrap.
1648 // If (AllocSize - (ConstOffset + AccessSize)) wraps around, there is no valid
1649 // value for Index.
1650 APInt MaxIndex = (APInt(BitWidth, Size->getFixedValue() - AccessSize,
1651 /*isSigned=*/false, /*implicitTrunc=*/true) -
1652 Offset.ConstantOffset)
1653 .udiv(Scale);
1655 A = Index;
1656 B = ConstantInt::get(Index->getType(), MaxIndex);
1657 return true;
1658}
1659
1660/// Returns true if \p I is a candidate whose poison-generating flags may be
1661/// strengthened using the constraint systems.
1663 if (auto *Trunc = dyn_cast<TruncInst>(I))
1664 return Trunc->getType()->isIntegerTy() && Trunc->hasNoSignedWrap() &&
1665 !Trunc->hasNoUnsignedWrap();
1666
1667 auto *BO = dyn_cast<BinaryOperator>(I);
1668 if (!BO || !BO->getType()->isIntegerTy())
1669 return false;
1670
1671 switch (BO->getOpcode()) {
1672 case Instruction::Sub:
1673 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
1674 return false;
1675 // A - B does not wrap unsigned if A >=u B, and does not wrap signed if
1676 // 0 <=s B <=s A. With a constant B, bounds on A can refine both flags.
1677 return true;
1678 case Instruction::Add:
1679 case Instruction::Mul:
1680 case Instruction::Shl:
1681 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
1682 return false;
1683 // With a constant second operand, we can use bounds on the first operand to
1684 // refine no-wrap flags. Independently, nuw can be added for nsw if the
1685 // operands are non-negative.
1686 return isa<ConstantInt>(BO->getOperand(1)) || BO->hasNoSignedWrap();
1687 default:
1688 return false;
1689 }
1690}
1691
1692/// Try to strengthen \p I's poison generating flags using \p Info. Returns
1693/// true if \p I was modified.
1694static bool tryToStrengthenFlags(Instruction *I, ConstraintInfo &Info) {
1695 assert(canStrengthenFlags(I) && "not a candidate for flag strengthening");
1696
1697 bool Changed = false;
1698 if (!I->hasNoSignedWrap() && isKnownNoWrap(I, Info, /*Signed=*/true)) {
1699 LLVM_DEBUG(dbgs() << "Adding nsw to " << *I << "\n");
1700 I->setHasNoSignedWrap();
1701 Changed = true;
1702 }
1703 if (!I->hasNoUnsignedWrap() && isKnownNoWrap(I, Info, /*Signed=*/false)) {
1704 LLVM_DEBUG(dbgs() << "Adding nuw to " << *I << "\n");
1705 I->setHasNoUnsignedWrap();
1706 Changed = true;
1707 }
1708 return Changed;
1709}
1710
1711void State::addInfoFor(BasicBlock &BB) {
1712 addBoundsForHeaderInductions(BB);
1713 addInfoForInductions(BB);
1714 auto &DL = BB.getDataLayout();
1715
1716 Value *A, *B;
1717 CmpPredicate Pred;
1718 // True as long as the current instruction is guaranteed to execute.
1719 bool GuaranteedToExecute = true;
1720 // Queue conditions and assumes.
1721 for (Instruction &I : BB) {
1722 if (match(&I, m_ICmpLike(Pred, m_Value(), m_Value()))) {
1723 for (Use &U : I.uses()) {
1724 auto *UserI = getContextInstForUse(U);
1725 auto *DTN = DT.getNode(UserI->getParent());
1726 if (!DTN)
1727 continue;
1728 WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1729 }
1730 continue;
1731 }
1732
1733 auto AddFactFromMemoryAccess = [&](Value *Ptr, Type *AccessType) {
1734 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1735 if (!GEP)
1736 return;
1737 TypeSize AccessSize = DL.getTypeStoreSize(AccessType);
1738 if (!AccessSize.isFixed())
1739 return;
1740 if (GuaranteedToExecute) {
1742 Pred, A, B, DL, TLI)) {
1743 // The memory access is guaranteed to execute when BB is entered,
1744 // hence the constraint holds on entry to BB.
1745 WorkList.emplace_back(FactOrCheck::getConditionFact(
1746 DT.getNode(I.getParent()), Pred, A, B));
1747 }
1748 } else {
1749 WorkList.emplace_back(
1750 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1751 }
1752 };
1753
1754 if (auto *LI = dyn_cast<LoadInst>(&I)) {
1755 if (!LI->isVolatile())
1756 AddFactFromMemoryAccess(LI->getPointerOperand(), LI->getAccessType());
1757 }
1758 if (auto *SI = dyn_cast<StoreInst>(&I)) {
1759 if (!SI->isVolatile())
1760 AddFactFromMemoryAccess(SI->getPointerOperand(), SI->getAccessType());
1761 }
1762
1763 auto *II = dyn_cast<IntrinsicInst>(&I);
1764 Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1765 switch (ID) {
1766 case Intrinsic::assume: {
1767 if (!match(I.getOperand(0), m_ICmpLike(Pred, m_Value(A), m_Value(B))))
1768 break;
1769 if (GuaranteedToExecute) {
1770 // The assume is guaranteed to execute when BB is entered, hence Cond
1771 // holds on entry to BB.
1772 WorkList.emplace_back(FactOrCheck::getConditionFact(
1773 DT.getNode(I.getParent()), Pred, A, B));
1774 } else {
1775 WorkList.emplace_back(
1776 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1777 }
1778 break;
1779 }
1780 // Enqueue intrinsics for simplification.
1781 case Intrinsic::uadd_with_overflow:
1782 case Intrinsic::sadd_with_overflow:
1783 case Intrinsic::usub_with_overflow:
1784 case Intrinsic::ssub_with_overflow:
1785 case Intrinsic::umul_with_overflow:
1786 case Intrinsic::smul_with_overflow:
1787 case Intrinsic::ucmp:
1788 case Intrinsic::scmp:
1789 WorkList.push_back(
1790 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1791 break;
1792 // Enqueue the intrinsics to add extra info.
1793 case Intrinsic::umin:
1794 case Intrinsic::umax:
1795 case Intrinsic::smin:
1796 case Intrinsic::smax:
1797 case Intrinsic::usub_sat:
1798 // TODO: handle llvm.abs as well
1799 WorkList.push_back(
1800 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1801 [[fallthrough]];
1802 case Intrinsic::uadd_sat:
1803 // TODO: Check if it is possible to instead only added the min/max facts
1804 // when simplifying uses of the min/max intrinsics.
1806 break;
1807 [[fallthrough]];
1808 case Intrinsic::abs:
1809 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1810 break;
1811 }
1812
1813 // Add facts from unsigned division, remainder and logical shift right, and
1814 // from signed division and remainder.
1815 // urem x, n: result < n and result <= x
1816 // udiv x, n: result <= x
1817 // lshr x, n: result <= x
1818 // srem x, n: result >= 0 and result <= x, if x >= 0
1819 // result < n, if n > 0
1820 // sdiv x, n: result >= 0 and result <= x, if x >= 0 and n > 0
1821 // result >= 0 and result < x, if x > 0 and n > 1
1822 if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1823 if ((BO->getOpcode() == Instruction::URem ||
1824 BO->getOpcode() == Instruction::UDiv ||
1825 BO->getOpcode() == Instruction::LShr ||
1826 BO->getOpcode() == Instruction::SRem ||
1827 BO->getOpcode() == Instruction::SDiv) &&
1829 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), BO));
1830 }
1831
1832 // Queue instructions whose flags may be strengthened, checked at the
1833 // closest point dominating all uses.
1834 if (canStrengthenFlags(&I)) {
1835 Instruction *CommonDom = findCommonDominatorOfUses(I, DT);
1836 WorkList.push_back(FactOrCheck::getCheck(
1837 DT.getNode(CommonDom->getParent()), &I, CommonDom));
1838 }
1839
1840 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1841 }
1842
1843 if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1844 for (auto &Case : Switch->cases()) {
1845 BasicBlock *Succ = Case.getCaseSuccessor();
1846 Value *V = Case.getCaseValue();
1847 if (!canAddSuccessor(BB, Succ))
1848 continue;
1849 WorkList.emplace_back(FactOrCheck::getConditionFact(
1850 DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1851 }
1852 return;
1853 }
1854
1855 auto *Br = dyn_cast<CondBrInst>(BB.getTerminator());
1856 if (!Br)
1857 return;
1858
1859 Value *Cond = Br->getCondition();
1860
1861 // If the condition is a chain of ORs/AND and the successor only has the
1862 // current block as predecessor, queue conditions for the successor.
1863 Value *Op0, *Op1;
1864 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1865 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1866 bool IsOr = match(Cond, m_LogicalOr());
1867 bool IsAnd = match(Cond, m_LogicalAnd());
1868 // If there's a select that matches both AND and OR, we need to commit to
1869 // one of the options. Arbitrarily pick OR.
1870 if (IsOr && IsAnd)
1871 IsAnd = false;
1872
1873 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1874 if (canAddSuccessor(BB, Successor)) {
1875 SmallVector<Value *> CondWorkList;
1876 SmallPtrSet<Value *, 8> SeenCond;
1877 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1878 if (SeenCond.insert(V).second)
1879 CondWorkList.push_back(V);
1880 };
1881 QueueValue(Op1);
1882 QueueValue(Op0);
1883 while (!CondWorkList.empty()) {
1884 Value *Cur = CondWorkList.pop_back_val();
1885 if (match(Cur, m_ICmpLike(Pred, m_Value(A), m_Value(B)))) {
1886 WorkList.emplace_back(FactOrCheck::getConditionFact(
1887 DT.getNode(Successor),
1888 IsOr ? CmpPredicate::getInverse(Pred) : Pred, A, B));
1889 continue;
1890 }
1891 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1892 QueueValue(Op1);
1893 QueueValue(Op0);
1894 continue;
1895 }
1896 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1897 QueueValue(Op1);
1898 QueueValue(Op0);
1899 continue;
1900 }
1901 }
1902 }
1903 return;
1904 }
1905
1906 if (!match(Br->getCondition(), m_ICmpLike(Pred, m_Value(A), m_Value(B))))
1907 return;
1908 if (canAddSuccessor(BB, Br->getSuccessor(0)))
1909 WorkList.emplace_back(FactOrCheck::getConditionFact(
1910 DT.getNode(Br->getSuccessor(0)), Pred, A, B));
1911 if (canAddSuccessor(BB, Br->getSuccessor(1)))
1912 WorkList.emplace_back(FactOrCheck::getConditionFact(
1913 DT.getNode(Br->getSuccessor(1)), CmpPredicate::getInverse(Pred), A, B));
1914}
1915
1916#ifndef NDEBUG
1918 Value *LHS, Value *RHS) {
1919 OS << "icmp " << Pred << ' ';
1920 LHS->printAsOperand(OS, /*PrintType=*/true);
1921 OS << ", ";
1922 RHS->printAsOperand(OS, /*PrintType=*/false);
1923}
1924#endif
1925
1926namespace {
1927/// Helper to keep track of a condition and if it should be treated as negated
1928/// for reproducer construction.
1929/// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1930/// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1931struct ReproducerEntry {
1932 ICmpInst::Predicate Pred;
1933 Value *LHS;
1934 Value *RHS;
1935
1936 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1937 : Pred(Pred), LHS(LHS), RHS(RHS) {}
1938};
1939} // namespace
1940
1941/// Helper function to generate a reproducer function for simplifying \p Cond.
1942/// The reproducer function contains a series of @llvm.assume calls, one for
1943/// each condition in \p Stack. For each condition, the operand instruction are
1944/// cloned until we reach operands that have an entry in \p Value2Index. Those
1945/// will then be added as function arguments. \p DT is used to order cloned
1946/// instructions. The reproducer function will get added to \p M, if it is
1947/// non-null. Otherwise no reproducer function is generated.
1948static void generateReproducer(Instruction *Cond, bool IsSigned, Module *M,
1950 ConstraintInfo &Info, DominatorTree &DT) {
1951 if (!M)
1952 return;
1953
1954 LLVMContext &Ctx = Cond->getContext();
1955
1956 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1957
1958 ValueToValueMapTy Old2New;
1961 // Traverse Cond and its operands recursively until we reach a value that's in
1962 // Value2Index or not an instruction, or not a operation that
1963 // ConstraintElimination can decompose. Such values will be considered as
1964 // external inputs to the reproducer, they are collected and added as function
1965 // arguments later.
1966 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1967 auto &Value2Index = Info.getValue2Index(IsSigned);
1968 SmallVector<Value *, 4> WorkList(Ops);
1969 while (!WorkList.empty()) {
1970 Value *V = WorkList.pop_back_val();
1971 if (!Seen.insert(V).second)
1972 continue;
1973 if (Old2New.find(V) != Old2New.end())
1974 continue;
1975 if (isa<Constant>(V))
1976 continue;
1977
1978 auto *I = dyn_cast<Instruction>(V);
1979 if (Value2Index.contains(V) || !I ||
1981 Old2New[V] = V;
1982 Args.push_back(V);
1983 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n");
1984 } else {
1985 append_range(WorkList, I->operands());
1986 }
1987 }
1988 };
1989
1990 for (auto &Entry : Stack)
1991 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1992 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1993 CollectArguments(Cond, IsSigned);
1994
1995 SmallVector<Type *> ParamTys;
1996 for (auto *P : Args)
1997 ParamTys.push_back(P->getType());
1998
1999 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
2000 /*isVarArg=*/false);
2002 Cond->getModule()->getName() +
2003 Cond->getFunction()->getName() + "repro",
2004 M);
2005 // Add arguments to the reproducer function for each external value collected.
2006 for (unsigned I = 0; I < Args.size(); ++I) {
2007 F->getArg(I)->setName(Args[I]->getName());
2008 Old2New[Args[I]] = F->getArg(I);
2009 }
2010
2011 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
2012 IRBuilder<> Builder(Entry);
2013 Builder.CreateRet(Builder.getTrue());
2014 Builder.SetInsertPoint(Entry->getTerminator());
2015
2016 // Clone instructions in \p Ops and their operands recursively until reaching
2017 // an value in Value2Index (external input to the reproducer). Update Old2New
2018 // mapping for the original and cloned instructions. Sort instructions to
2019 // clone by dominance, then insert the cloned instructions in the function.
2020 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
2021 SmallVector<Value *, 4> WorkList(Ops);
2023 auto &Value2Index = Info.getValue2Index(IsSigned);
2024 while (!WorkList.empty()) {
2025 Value *V = WorkList.pop_back_val();
2026 if (Old2New.find(V) != Old2New.end())
2027 continue;
2028
2029 auto *I = dyn_cast<Instruction>(V);
2030 if (!Value2Index.contains(V) && I) {
2031 Old2New[V] = nullptr;
2032 ToClone.push_back(I);
2033 append_range(WorkList, I->operands());
2034 }
2035 }
2036
2037 sort(ToClone,
2038 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
2039 for (Instruction *I : ToClone) {
2040 Instruction *Cloned = I->clone();
2041 Old2New[I] = Cloned;
2042 Old2New[I]->setName(I->getName());
2043 Cloned->insertBefore(Builder.GetInsertPoint());
2045 Cloned->setDebugLoc({});
2046 }
2047 };
2048
2049 // Materialize the assumptions for the reproducer using the entries in Stack.
2050 // That is, first clone the operands of the condition recursively until we
2051 // reach an external input to the reproducer and add them to the reproducer
2052 // function. Then add an ICmp for the condition (with the inverse predicate if
2053 // the entry is negated) and an assert using the ICmp.
2054 for (auto &Entry : Stack) {
2055 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
2056 continue;
2057
2058 LLVM_DEBUG(dbgs() << " Materializing assumption ";
2059 dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
2060 dbgs() << "\n");
2061 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
2062
2063 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
2064 Builder.CreateAssumption(Cmp);
2065 }
2066
2067 // Finally, clone the condition to reproduce and remap instruction operands in
2068 // the reproducer using Old2New.
2069 CloneInstructions(Cond, IsSigned);
2070 Entry->getTerminator()->setOperand(0, Cond);
2071 remapInstructionsInBlocks({Entry}, Old2New);
2072
2073 assert(!verifyFunction(*F, &dbgs()));
2074}
2075
2076/// If \p V is a variable in the system and constraint \p C does not contain \p
2077/// V, we managed to decompose \p V at this point, but likely not earlier when
2078/// the fact involving \p V was added. In that case, return a new row for
2079/// V <= decompose(V) to link the variable with the decomposition result.
2080static RowTy getDecompositionLinkRow(Value *V, const ConstraintTy &C,
2081 ConstraintInfo &Info,
2082 const DataLayout &DL) {
2083 const auto &Value2Index = Info.getValue2Index(C.IsSigned);
2084 auto It = Value2Index.find(V);
2085 if (It == Value2Index.end() ||
2086 any_of(C.Coefficients,
2087 [Id = It->second](const Entry &E) { return E.Id == Id; }))
2088 return {};
2089
2090 SmallVector<Value *> NewVariables;
2091 RowTy Row =
2092 getRowForLessEqual(Decomposition(V), decompose(V, Info, C.IsSigned, DL),
2093 Value2Index, NewVariables);
2094 return NewVariables.empty() ? Row : RowTy();
2095}
2096
2097static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
2098 Value *B, Instruction *CheckInst,
2099 ConstraintInfo &Info) {
2100 LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
2101
2102 auto TryWithConstraint = [&](const ConstraintTy &R) -> std::optional<bool> {
2103 if (R.empty()) {
2104 LLVM_DEBUG(dbgs() << " failed to decompose condition\n");
2105 return std::nullopt;
2106 }
2107
2108 auto &CSToUse = Info.getCS(R.IsSigned);
2109 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
2110 if (!DebugCounter::shouldExecute(EliminatedCounter))
2111 return std::nullopt;
2112 LLVM_DEBUG({
2113 dbgs() << "Condition ";
2115 *ImpliedCondition ? Pred
2117 A, B);
2118 dbgs() << " implied by dominating constraints\n";
2119 CSToUse.dump();
2120 });
2121 return ImpliedCondition;
2122 }
2123 return std::nullopt;
2124 };
2125
2126 // Retry the query after adding additional facts for A == decompose(A) and B
2127 // == decompose(B), if needed.
2128 auto TryWithLinkedDecomposition =
2129 [&](const ConstraintTy &C) -> std::optional<bool> {
2130 return Info.tryWithLinkRows(A, B, C, [&] { return TryWithConstraint(C); });
2131 };
2132
2133 auto R = Info.getConstraintForSolving(Pred, A, B);
2134 if (auto ImpliedCondition = TryWithLinkedDecomposition(R))
2135 return ImpliedCondition;
2136
2137 // For non-negative operands unsigned queries can also be checked against the
2138 // signed system.
2139 if (CmpInst::isUnsigned(Pred) && A->getType()->isIntegerTy()) {
2140 SmallVector<Value *> NewVariables;
2141 auto SR = Info.getConstraint(ICmpInst::getSignedPredicate(Pred), A, B,
2142 NewVariables);
2143 if (NewVariables.empty() && !SR.empty() && Info.isKnownNonNegative(A) &&
2144 Info.isKnownNonNegative(B))
2145 if (auto ImpliedCondition = TryWithConstraint(SR))
2146 return ImpliedCondition;
2147 }
2148
2149 // Additionally, query the signed system for eq/ne predicates if we know about
2150 // A or B.
2152 const auto &Value2Index = Info.getValue2Index(/*Signed=*/true);
2153 if (!Value2Index.contains(A) && !Value2Index.contains(B))
2154 return std::nullopt;
2155
2156 SmallVector<Value *> NewVariables;
2157 auto SR = Info.getConstraint(Pred, A, B, NewVariables,
2158 /*ForceSignedSystem=*/true);
2159 if (NewVariables.empty()) {
2160 if (auto ImpliedCondition = TryWithLinkedDecomposition(SR))
2161 return ImpliedCondition;
2162 }
2163 }
2164 return std::nullopt;
2165}
2166
2168 CmpPredicate Pred, Value *A, Value *B, Instruction *CheckInst,
2169 ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
2170 Instruction *ContextInst, Module *ReproducerModule,
2171 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
2173 auto ReplaceCmpWithConstant = [&](Instruction *CheckInst, bool IsTrue) {
2174 generateReproducer(CheckInst, ICmpInst::isSigned(Pred), ReproducerModule,
2175 ReproducerCondStack, Info, DT);
2176 Constant *ConstantC = ConstantInt::getBool(
2177 CmpInst::makeCmpResultType(CheckInst->getType()), IsTrue);
2178 bool Changed = CheckInst->replaceUsesWithIf(ConstantC, [&](Use &U) {
2179 auto *UserI = getContextInstForUse(U);
2180 auto *DTN = DT.getNode(UserI->getParent());
2181 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
2182 return false;
2183 if (UserI->getParent() == ContextInst->getParent() &&
2184 UserI->comesBefore(ContextInst))
2185 return false;
2186
2187 // Conditions in an assume trivially simplify to true. Skip uses
2188 // in assume calls to not destroy the available information.
2189 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
2190 return !II || II->getIntrinsicID() != Intrinsic::assume;
2191 });
2192 NumCondsRemoved++;
2193
2194 // Update the debug value records that satisfy the same condition used
2195 // in replaceUsesWithIf.
2197 findDbgUsers(CheckInst, DVRUsers);
2198
2199 for (auto *DVR : DVRUsers) {
2200 auto *DTN = DT.getNode(DVR->getParent());
2201 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
2202 continue;
2203
2204 auto *MarkedI = DVR->getInstruction();
2205 if (MarkedI->getParent() == ContextInst->getParent() &&
2206 MarkedI->comesBefore(ContextInst))
2207 continue;
2208
2209 DVR->replaceVariableLocationOp(CheckInst, ConstantC);
2210 }
2211
2212 if (CheckInst->use_empty())
2213 ToRemove.push_back(CheckInst);
2214
2215 return Changed;
2216 };
2217
2218 if (auto ImpliedCondition = checkCondition(Pred, A, B, CheckInst, Info))
2219 return ReplaceCmpWithConstant(CheckInst, *ImpliedCondition);
2220
2221 // When the predicate is samesign and unsigned, we can also make use of the
2222 // signed predicate information.
2223 if (Pred.hasSameSign() && ICmpInst::isUnsigned(Pred))
2224 if (auto ImpliedCondition = checkCondition(
2225 ICmpInst::getSignedPredicate(Pred), A, B, CheckInst, Info))
2226 return ReplaceCmpWithConstant(CheckInst, *ImpliedCondition);
2227
2228 return false;
2229}
2230
2231static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
2233 auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
2234 // TODO: generate reproducer for min/max.
2235 MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
2236 ToRemove.push_back(MinMax);
2237 return true;
2238 };
2239
2241 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
2242 if (auto ImpliedCondition = checkCondition(
2243 Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
2244 return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
2245 if (auto ImpliedCondition = checkCondition(
2246 Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
2247 return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
2248 return false;
2249}
2250
2251static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
2253 Value *LHS = I->getOperand(0);
2254 Value *RHS = I->getOperand(1);
2255 if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
2256 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
2257 ToRemove.push_back(I);
2258 return true;
2259 }
2260 if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
2261 I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
2262 ToRemove.push_back(I);
2263 return true;
2264 }
2265 if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
2266 I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
2267 ToRemove.push_back(I);
2268 return true;
2269 }
2270 return false;
2271}
2272
2273/// Try to replace \p USub by a plain subtract, if \p Info proves it cannot
2274/// saturate. Returns true if \p USub was replaced.
2275static bool checkAndReplaceUSubSat(SaturatingInst *USub, ConstraintInfo &Info,
2277 // usub.sat(A, B) is A - B exactly when A >=u B.
2278 Value *A = USub->getLHS();
2279 Value *B = USub->getRHS();
2280 if (!checkCondition(CmpInst::ICMP_UGE, A, B, USub, Info).value_or(false))
2281 return false;
2282
2283 IRBuilder<> Builder(USub);
2284 Value *Sub = Builder.CreateSub(A, B, "", /*HasNUW=*/true,
2285 /*HasNSW=*/Info.isKnownNonNegative(A));
2286 USub->replaceAllUsesWith(Sub);
2287 Sub->takeName(USub);
2288 ToRemove.push_back(USub);
2289 return true;
2290}
2291
2292static void
2293removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
2294 Module *ReproducerModule,
2295 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
2296 SmallVectorImpl<StackEntry> &DFSInStack) {
2297 Info.getDecomposeCache().clear();
2298 Info.popLastConstraint(E.IsSigned);
2299 // Remove variables in the system that went out of scope.
2300 auto &Mapping = Info.getValue2Index(E.IsSigned);
2301 for (Value *V : E.ValuesToRelease)
2302 Mapping.erase(V);
2303 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
2304 DFSInStack.pop_back();
2305 if (ReproducerModule)
2306 ReproducerCondStack.pop_back();
2307}
2308
2309/// Check if either the first condition of an AND or OR is implied by the
2310/// (negated in case of OR) second condition or vice versa.
2312 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
2313 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
2314 SmallVectorImpl<StackEntry> &DFSInStack,
2316 Instruction *JoinOp = CB.getContextInst();
2317 if (JoinOp->use_empty())
2318 return false;
2319
2320 Instruction *CmpToCheck = cast<Instruction>(CB.getInstructionToSimplify());
2321 unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
2322
2323 // Don't try to simplify the first condition of a select by the second, as
2324 // this may make the select more poisonous than the original one.
2325 // TODO: check if the first operand may be poison.
2326 if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
2327 return false;
2328
2329 unsigned OldSize = DFSInStack.size();
2330 llvm::scope_exit InfoRestorer([&]() {
2331 // Remove entries again.
2332 while (OldSize < DFSInStack.size()) {
2333 StackEntry E = DFSInStack.back();
2334 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
2335 DFSInStack);
2336 }
2337 });
2338 bool IsOr = match(JoinOp, m_LogicalOr());
2339 SmallVector<Value *, 4> Worklist({JoinOp->getOperand(OtherOpIdx)});
2340 // Do a traversal of the AND/OR tree to add facts from leaf compares.
2341 while (!Worklist.empty()) {
2342 Value *Val = Worklist.pop_back_val();
2343 Value *LHS, *RHS;
2345 if (match(Val, m_ICmpLike(Pred, m_Value(LHS), m_Value(RHS)))) {
2346 // For OR, check if the negated condition implies CmpToCheck.
2347 if (IsOr)
2349 // Optimistically add fact from the other compares in the AND/OR.
2350 Info.addFact(Pred, LHS, RHS, CB.NumIn, CB.NumOut, DFSInStack);
2351 continue;
2352 }
2353 if (IsOr ? match(Val, m_LogicalOr(m_Value(LHS), m_Value(RHS)))
2354 : match(Val, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
2355 Worklist.push_back(LHS);
2356 Worklist.push_back(RHS);
2357 }
2358 }
2359 if (OldSize == DFSInStack.size())
2360 return false;
2361
2362 Value *A, *B;
2364 [[maybe_unused]] bool Matched =
2365 match(CmpToCheck, m_ICmpLike(Pred, m_Value(A), m_Value(B)));
2366 assert(Matched && "expected icmp-like match");
2367 // Check if the second condition can be simplified now.
2368 if (auto ImpliedCondition = checkCondition(Pred, A, B, CmpToCheck, Info)) {
2369 if (IsOr == *ImpliedCondition)
2370 JoinOp->replaceAllUsesWith(
2371 ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
2372 else
2373 JoinOp->replaceAllUsesWith(JoinOp->getOperand(OtherOpIdx));
2374 ToRemove.push_back(JoinOp);
2375 return true;
2376 }
2377
2378 return false;
2379}
2380
2381void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
2382 unsigned NumIn, unsigned NumOut,
2383 SmallVectorImpl<StackEntry> &DFSInStack) {
2384 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, false);
2385 // If the Pred is eq/ne, also add the fact to signed system.
2387 addFactImpl(Pred, A, B, NumIn, NumOut, DFSInStack, true);
2388 if (Pred == CmpInst::ICMP_NE)
2389 tightenBoundUsingNe(A, B, NumIn, NumOut, DFSInStack);
2390}
2391
2392void ConstraintInfo::tightenBoundUsingNe(
2393 Value *A, Value *B, unsigned NumIn, unsigned NumOut,
2394 SmallVectorImpl<StackEntry> &DFSInStack) {
2395 if (!A->getType()->isIntOrPtrTy())
2396 return;
2397
2398 for (bool IsSigned : {false, true}) {
2399 // In the unsigned system `A u>= 0` holds for every A, so getConstraint
2400 // already turned `A != 0` into `A u> 0`.
2401 if (!IsSigned && match(B, m_Zero()))
2402 continue;
2403
2404 // Skip if there are any unknown variables.
2405 const auto &Value2Index = getValue2Index(IsSigned);
2406 if (any_of(decompose(A, *this, IsSigned, DL).Vars,
2407 [&Value2Index](const DecompEntry &E) {
2408 return !Value2Index.contains(E.Variable);
2409 }))
2410 continue;
2411
2412 // If the system implies `A >= B` then together with `A != B` we get the
2413 // strict `A > B`; symmetrically `A <= B` becomes `A < B`.
2414 CmpInst::Predicate GEPred =
2416 CmpInst::Predicate LEPred =
2418 for (CmpInst::Predicate NonStrict : {GEPred, LEPred}) {
2419 if (!doesHold(NonStrict, A, B))
2420 continue;
2422 LLVM_DEBUG(dbgs() << "Tightening '";
2423 dumpUnpackedICmp(dbgs(), NonStrict, A, B); dbgs() << "' to '";
2425 dbgs() << "' using inequality\n");
2426 addFactImpl(Strict, A, B, NumIn, NumOut, DFSInStack,
2427 /*ForceSignedSystem=*/false);
2428 break;
2429 }
2430 }
2431}
2432
2433void ConstraintInfo::addFactImpl(CmpInst::Predicate Pred, Value *A, Value *B,
2434 unsigned NumIn, unsigned NumOut,
2435 SmallVectorImpl<StackEntry> &DFSInStack,
2436 bool ForceSignedSystem) {
2437 SmallVector<Value *> NewVariables;
2438 auto R = getConstraint(Pred, A, B, NewVariables, ForceSignedSystem);
2439
2440 // TODO: Support non-equality for facts as well.
2441 if (R.empty() || R.isNe())
2442 return;
2443
2444 auto &CSToUse = getCS(R.IsSigned);
2445 // A row implied by a single existing row adds no information. Rows in the
2446 // system are removed in reverse order, so the existing row outlives R. Rows
2447 // in the system are normalized, so normalize R before comparing.
2448 if (!R.isEq() && NewVariables.empty()) {
2449 ConstraintSystem::normalizeByGCD(R.Coefficients);
2450 if (CSToUse.isImpliedBySingleRow(R.Coefficients))
2451 return;
2452 }
2453 LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
2454 dbgs() << "'\n");
2455 bool Added = CSToUse.addRow(R.Coefficients, R.NumVars);
2456 if (!Added)
2457 return;
2458
2459 DecomposeCache.clear();
2460
2461 // If R has been added to the system, add the new variables and queue it for
2462 // removal once it goes out-of-scope.
2463 SmallVector<Value *, 2> ValuesToRelease;
2464 auto &Value2Index = getValue2Index(R.IsSigned);
2465 for (Value *V : NewVariables) {
2466 Value2Index.try_emplace(V, Value2Index.size() + 1);
2467 ValuesToRelease.push_back(V);
2468 }
2469
2470 LLVM_DEBUG({
2471 dbgs() << " constraint: ";
2472 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
2473 dbgs() << "\n";
2474 });
2475
2476 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2477 std::move(ValuesToRelease));
2478
2479 if (!R.IsSigned) {
2480 for (Value *V : NewVariables) {
2481 // Add V > -1 constraints for all new variables.
2482 CSToUse.addRow({Entry(0, 0), Entry(-1, Value2Index.at(V))},
2483 Value2Index.size());
2484 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2485 SmallVector<Value *, 2>());
2486 }
2487 }
2488
2489 if (R.isEq()) {
2490 // Also add the inverted constraint for equality constraints.
2491 for (Entry &E : R.Coefficients)
2492 if (MulOverflow(E.Coefficient, int64_t(-1), E.Coefficient))
2493 return;
2494 CSToUse.addRow(R.Coefficients, R.NumVars);
2495
2496 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
2497 SmallVector<Value *, 2>());
2498 }
2499}
2500
2501/// Replace the uses of \p II, which is known not to overflow, by the
2502/// corresponding plain binary operation and a false overflow flag.
2505 bool Changed = false;
2506 IRBuilder<> Builder(II->getIterator());
2507 Value *Res = nullptr;
2508 for (User *U : make_early_inc_range(II->users())) {
2509 if (match(U, m_ExtractValue<0>(m_Value()))) {
2510 if (!Res)
2511 Res = Builder.CreateNoWrapBinOp(II->getBinaryOp(), II->getLHS(),
2512 II->getRHS(),
2513 /*IsNUW=*/!II->isSigned(),
2514 /*IsNSW=*/II->isSigned());
2515 U->replaceAllUsesWith(Res);
2516 Changed = true;
2517 } else if (match(U, m_ExtractValue<1>(m_Value()))) {
2518 U->replaceAllUsesWith(ConstantInt::getFalse(U->getType()));
2519 Changed = true;
2520 } else
2521 continue;
2522
2523 if (U->use_empty()) {
2524 auto *I = cast<Instruction>(U);
2525 ToRemove.push_back(I);
2526 I->setOperand(0, PoisonValue::get(II->getType()));
2527 Changed = true;
2528 }
2529 }
2530
2531 if (II->use_empty()) {
2532 // Do not erase II here: the worklist may still hold Uses of II's operands.
2533 for (Use &Arg : II->args())
2534 Arg.set(PoisonValue::get(Arg->getType()));
2535 ToRemove.push_back(II);
2536 Changed = true;
2537 }
2538 return Changed;
2539}
2540
2541static bool
2544 if (!isKnownNoWrap(II, Info, II->isSigned()))
2545 return false;
2547}
2548
2550 ScalarEvolution *SE,
2553 const ScalarOptions &Opts = getScalarOptions(F);
2554 bool Changed = false;
2555 DT.updateDFSNumbers();
2556 SmallVector<Value *> FunctionArgs(llvm::make_pointer_range(F.args()));
2557 ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
2558 State S(DT, LI, SE, TLI);
2559 std::unique_ptr<Module> ReproducerModule(
2560 Opts.constraint_elimination_dump_reproducers
2561 ? new Module(F.getName(), F.getContext())
2562 : nullptr);
2563
2564 // First, collect conditions implied by branches and blocks with their
2565 // Dominator DFS in and out numbers.
2566 for (BasicBlock &BB : F) {
2567 if (!DT.getNode(&BB))
2568 continue;
2569 S.addInfoFor(BB);
2570 }
2571
2572 // Next, sort worklist by dominance, so that dominating conditions to check
2573 // and facts come before conditions and facts dominated by them. If a
2574 // condition to check and a fact have the same numbers, conditional facts come
2575 // first. Assume facts and checks are ordered according to their relative
2576 // order in the containing basic block. Also make sure conditions with
2577 // constant operands come before conditions without constant operands. This
2578 // increases the effectiveness of the current signed <-> unsigned fact
2579 // transfer logic.
2580 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
2581 auto HasNoConstOp = [](const FactOrCheck &B) {
2582 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
2583 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
2584 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
2585 };
2586 // If both entries have the same In numbers, conditional facts come first.
2587 // Otherwise use the relative order in the basic block.
2588 if (A.NumIn == B.NumIn) {
2589 if (A.isConditionFact() && B.isConditionFact()) {
2590 bool NoConstOpA = HasNoConstOp(A);
2591 bool NoConstOpB = HasNoConstOp(B);
2592 return NoConstOpA < NoConstOpB;
2593 }
2594 if (A.isConditionFact())
2595 return true;
2596 if (B.isConditionFact())
2597 return false;
2598 auto *InstA = A.getContextInst();
2599 auto *InstB = B.getContextInst();
2600 return InstA->comesBefore(InstB);
2601 }
2602 return A.NumIn < B.NumIn;
2603 });
2604
2605 SmallVector<Instruction *> ToRemove;
2606
2607 // Finally, process ordered worklist and eliminate implied conditions.
2608 SmallVector<StackEntry, 16> DFSInStack;
2609 SmallVector<ReproducerEntry> ReproducerCondStack;
2610 for (FactOrCheck &CB : S.WorkList) {
2611 // First, pop entries from the stack that are out-of-scope for CB. Remove
2612 // the corresponding entry from the constraint system.
2613 while (!DFSInStack.empty()) {
2614 auto &E = DFSInStack.back();
2615 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
2616 << "\n");
2617 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
2618 assert(E.NumIn <= CB.NumIn);
2619 if (CB.NumOut <= E.NumOut)
2620 break;
2621 LLVM_DEBUG({
2622 dbgs() << "Removing ";
2623 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
2624 Info.getValue2Index(E.IsSigned));
2625 dbgs() << "\n";
2626 });
2627 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
2628 DFSInStack);
2629 }
2630
2631 CmpPredicate Pred;
2632 Value *A, *B;
2633 // For a block, check if any CmpInsts become known based on the current set
2634 // of constraints.
2635 if (CB.isCheck()) {
2636 Instruction *Inst = CB.getInstructionToSimplify();
2637 if (!Inst)
2638 continue;
2639 if (canStrengthenFlags(Inst)) {
2640 Changed |= tryToStrengthenFlags(Inst, Info);
2641 continue;
2642 }
2643 LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
2644 << "\n");
2645 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
2647 } else if (match(Inst, m_ICmpLike(Pred, m_Value(A), m_Value(B)))) {
2649 Pred, A, B, Inst, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
2650 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
2651 if (!Simplified &&
2652 match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
2654 CB, Info, ReproducerModule.get(), ReproducerCondStack, DFSInStack,
2655 ToRemove);
2656 }
2658 } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
2659 Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
2660 } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
2661 Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
2662 } else if (match(Inst, m_Intrinsic<Intrinsic::usub_sat>())) {
2663 Changed |=
2665 }
2666 continue;
2667 }
2668
2669 auto AddFact = [&](CmpPredicate Pred, Value *A, Value *B) {
2670 LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
2671 dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
2672 if (Info.getCS(CmpInst::isSigned(Pred)).size() >
2673 Opts.constraint_elimination_max_rows) {
2674 LLVM_DEBUG(
2675 dbgs()
2676 << "Skip adding constraint because system has too many rows.\n");
2677 return;
2678 }
2679
2680 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
2681 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
2682 ReproducerCondStack.emplace_back(Pred, A, B);
2683
2685 // If samesign is present on the ICmp, simply flip the sign of the
2686 // predicate, transferring the information from the signed system to the
2687 // unsigned system, and viceversa.
2688 if (Pred.hasSameSign()) {
2690 CB.NumIn, CB.NumOut, DFSInStack);
2691 // The operands also have the same sign: if one of them is known to
2692 // be non-negative (or negative), so is the other.
2693 if (A->getType()->isIntegerTy()) {
2694 std::optional<bool> ASign = Info.getKnownSign(A);
2695 std::optional<bool> BSign = Info.getKnownSign(B);
2696 if (ASign.has_value() != BSign.has_value()) {
2697 bool IsNegative = ASign ? *ASign : *BSign;
2698 Value *OtherOp = ASign ? B : A;
2699 Info.addFact(IsNegative ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGE,
2700 OtherOp, Constant::getNullValue(A->getType()),
2701 CB.NumIn, CB.NumOut, DFSInStack);
2702 }
2703 }
2704 } else {
2705 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut,
2706 DFSInStack);
2707 }
2708 }
2709
2710 // (X | Y) >s -1 implies X >s -1 and Y >s -1, because the sign bit of an
2711 // OR is the OR of the operand sign bits. Similarly, (X & Y) <s 0 implies
2712 // X <s 0 and Y <s 0. Look through these canonical forms produced by
2713 // InstCombine so the sign facts on the operands are available to the
2714 // solver.
2715 if ((Pred == CmpInst::ICMP_SGT && match(B, m_AllOnes())) ||
2716 (Pred == CmpInst::ICMP_SLT && match(B, m_Zero()))) {
2717 unsigned Opc =
2718 Pred == CmpInst::ICMP_SGT ? Instruction::Or : Instruction::And;
2719 SmallVector<Value *> Worklist = {A};
2720 SmallPtrSet<Value *, 4> Seen;
2721 while (!Worklist.empty()) {
2722 Value *Cur = Worklist.pop_back_val();
2723 auto *BO = dyn_cast<BinaryOperator>(Cur);
2724 if (!BO || BO->getOpcode() != Opc)
2725 continue;
2726 for (Value *Op : {BO->getOperand(0), BO->getOperand(1)}) {
2727 if (!Seen.insert(Op).second)
2728 continue;
2729 Worklist.push_back(Op);
2730 Info.addFact(Pred, Op, B, CB.NumIn, CB.NumOut, DFSInStack);
2731 }
2732 }
2733 }
2734
2735 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
2736 // Add dummy entries to ReproducerCondStack to keep it in sync with
2737 // DFSInStack.
2738 for (unsigned I = 0,
2739 E = (DFSInStack.size() - ReproducerCondStack.size());
2740 I < E; ++I) {
2741 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
2742 nullptr, nullptr);
2743 }
2744 }
2745 };
2746
2747 if (!CB.isConditionFact()) {
2748 Value *X;
2749 if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
2750 // If is_int_min_poison is true then we may assume llvm.abs >= 0.
2751 if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
2752 AddFact(CmpInst::ICMP_SGE, CB.Inst,
2753 ConstantInt::get(CB.Inst->getType(), 0));
2754 AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
2755 continue;
2756 }
2757
2758 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
2759 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
2760 AddFact(Pred, MinMax, MinMax->getLHS());
2761 AddFact(Pred, MinMax, MinMax->getRHS());
2762 continue;
2763 }
2764 if (auto *USatI = dyn_cast<SaturatingInst>(CB.Inst)) {
2765 switch (USatI->getIntrinsicID()) {
2766 default:
2767 llvm_unreachable("Unexpected intrinsic.");
2768 case Intrinsic::uadd_sat:
2769 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getLHS());
2770 AddFact(ICmpInst::ICMP_UGE, USatI, USatI->getRHS());
2771 break;
2772 case Intrinsic::usub_sat:
2773 AddFact(ICmpInst::ICMP_ULE, USatI, USatI->getLHS());
2774 break;
2775 }
2776 continue;
2777 }
2778
2779 if (auto *BO = dyn_cast<BinaryOperator>(CB.Inst)) {
2780 if (BO->getOpcode() == Instruction::URem) {
2781 // urem x, n: result < n (remainder is always less than divisor)
2782 AddFact(CmpInst::ICMP_ULT, BO, BO->getOperand(1));
2783 // urem x, n: result <= x (remainder is at most the dividend)
2784 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2785 continue;
2786 }
2787 if (BO->getOpcode() == Instruction::UDiv) {
2788 // udiv x, n: result <= x (quotient is at most the dividend)
2789 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2790 continue;
2791 }
2792 if (BO->getOpcode() == Instruction::LShr) {
2793 // lshr x, n: result <= x (right shift cannot increase the value)
2794 AddFact(CmpInst::ICMP_ULE, BO, BO->getOperand(0));
2795 continue;
2796 }
2797 if (BO->getOpcode() == Instruction::SRem) {
2798 Value *X = BO->getOperand(0);
2799 Value *N = BO->getOperand(1);
2800 Constant *Zero = Constant::getNullValue(BO->getType());
2801 if (Info.doesHold(CmpInst::ICMP_SGE, X, Zero) ||
2802 isKnownNonNegative(X, F.getDataLayout())) {
2803 // srem x, n: result >= 0, if x >= 0 (result has the sign of x)
2804 AddFact(CmpInst::ICMP_SGE, BO, Zero);
2805 // srem x, n: result <= x, if x >= 0 (|result| <= |x| and both are
2806 // non-negative)
2807 AddFact(CmpInst::ICMP_SLE, BO, X);
2808 }
2809 if (Info.doesHold(CmpInst::ICMP_SGE, N, Zero) ||
2810 isKnownPositive(N, F.getDataLayout())) {
2811 // srem x, n: result <= n, if n >= 0 (|result| < n, so result <= n -
2812 // 1
2813 AddFact(CmpInst::ICMP_SLT, BO, N);
2814 }
2815 continue;
2816 }
2817 if (BO->getOpcode() == Instruction::SDiv) {
2818 Value *X = BO->getOperand(0);
2819 Value *N = BO->getOperand(1);
2820 if (!Info.isKnownNonNegative(X) || !Info.isKnownPositive(N))
2821 continue;
2822
2823 bool IsStrict = Info.isKnownPositive(X) &&
2824 Info.doesHold(CmpInst::ICMP_SGT, N,
2825 ConstantInt::get(N->getType(), 1));
2826 AddFact(CmpInst::ICMP_SGE, BO, Constant::getNullValue(BO->getType()));
2827 AddFact(IsStrict ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, BO, X);
2828 continue;
2829 }
2830 }
2831
2832 auto &DL = F.getDataLayout();
2833 auto AddFactsAboutIndices = [&](Value *Ptr, Type *AccessType) {
2834 CmpPredicate Pred;
2835 Value *A, *B;
2838 DL.getTypeStoreSize(AccessType).getFixedValue(), Pred, A, B, DL,
2839 TLI))
2840 AddFact(Pred, A, B);
2841 };
2842
2843 if (auto *LI = dyn_cast<LoadInst>(CB.Inst)) {
2844 AddFactsAboutIndices(LI->getPointerOperand(), LI->getAccessType());
2845 continue;
2846 }
2847 if (auto *SI = dyn_cast<StoreInst>(CB.Inst)) {
2848 AddFactsAboutIndices(SI->getPointerOperand(), SI->getAccessType());
2849 continue;
2850 }
2851 }
2852
2853 if (CB.isConditionFact()) {
2854 Pred = CB.Cond.Pred;
2855 A = CB.Cond.Op0;
2856 B = CB.Cond.Op1;
2857 if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
2858 !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
2859 LLVM_DEBUG({
2860 dbgs() << "Not adding fact ";
2862 dbgs() << " because precondition ";
2863 dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
2864 CB.DoesHold.Op1);
2865 dbgs() << " does not hold.\n";
2866 });
2867 continue;
2868 }
2869 } else {
2870 [[maybe_unused]] bool Matched =
2873 assert(Matched &&
2874 "Must have an assume intrinsic with a icmp like operand");
2875 }
2876 AddFact(Pred, A, B);
2877 }
2878
2879 if (ReproducerModule && !ReproducerModule->functions().empty()) {
2880 std::string S;
2881 raw_string_ostream StringS(S);
2882 ReproducerModule->print(StringS, nullptr);
2883 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
2884 Rem << ore::NV("module") << S;
2885 ORE.emit(Rem);
2886 }
2887
2888#ifndef NDEBUG
2889 unsigned SignedEntries =
2890 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
2891 assert(Info.getCS(false).size() - FunctionArgs.size() ==
2892 DFSInStack.size() - SignedEntries &&
2893 "updates to CS and DFSInStack are out of sync");
2894 assert(Info.getCS(true).size() == SignedEntries &&
2895 "updates to CS and DFSInStack are out of sync");
2896#endif
2897
2898 for (Instruction *I : ToRemove)
2899 I->eraseFromParent();
2900 return Changed;
2901}
2902
2905 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2906 auto &LI = AM.getResult<LoopAnalysis>(F);
2907 // SCEV is only used for loops, only construct it if there are some.
2908 auto *SE = LI.empty() ? nullptr : &AM.getResult<ScalarEvolutionAnalysis>(F);
2910 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2911 if (!eliminateConstraints(F, DT, LI, SE, ORE, TLI))
2912 return PreservedAnalyses::all();
2913
2917 return PA;
2918}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
std::pair< ICmpInst *, unsigned > ConditionTy
static int64_t MaxConstraintValue
static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, ScalarEvolution *SE, OptimizationRemarkEmitter &ORE, TargetLibraryInfo &TLI)
static bool canStrengthenFlags(Instruction *I)
Returns true if I is a candidate whose poison-generating flags may be strengthened using the constrai...
static bool doesHoldInRange(ConstraintInfo &Info, Value *Op, const ConstantRange &R, bool Signed)
Returns true if Info implies that Op is in R, interpreting R as a signed range if Signed is set and a...
static RowTy getDecompositionLinkRow(Value *V, const ConstraintTy &C, ConstraintInfo &Info, const DataLayout &DL)
If V is a variable in the system and constraint C does not contain V, we managed to decompose V at th...
static int64_t MinSignedConstraintValue
static bool tryToSimplifyOverflowMath(WithOverflowInst *II, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static auto m_IncrementOf(const PhiMatchTy &PhiM, const APInt *&Off)
Matches an increment of PhiM by a constant offset, captured in Off.
static Instruction * getContextInstForUse(Use &U)
static bool isKnownNoWrap(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, unsigned NoWrapFlags, ConstraintInfo &Info, bool Signed)
Returns true if Opcode applied to Op0 and Op1 with NoWrapFlags is known to not wrap in signed or unsi...
static bool mayLookThrough(Value *V)
Returns true if V is an operation decomposeImpl can look through.
static bool canUseSExt(ConstantInt *CI)
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 Decomposition decompose(Value *V, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
static bool checkOrAndOpImpliedByOther(FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, SmallVectorImpl< ReproducerEntry > &ReproducerCondStack, SmallVectorImpl< StackEntry > &DFSInStack, SmallVectorImpl< Instruction * > &ToRemove)
Check if either the first condition of an AND or OR is implied by the (negated in case of OR) second ...
static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL)
static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static bool tryToStrengthenFlags(Instruction *I, ConstraintInfo &Info)
Try to strengthen I's poison generating flags using Info.
static RowTy getRowForLessEqual(const Decomposition &ADec, const Decomposition &BDec, const DenseMap< Value *, unsigned > &Value2Index, SmallVectorImpl< Value * > &NewVariables)
Build the row for 'ADec <= BDec', using the indices from Value2Index.
static void dumpConstraint(ArrayRef< Entry > C, const DenseMap< Value *, unsigned > &Value2Index)
static bool replaceOverflowUses(WithOverflowInst *II, SmallVectorImpl< Instruction * > &ToRemove)
Replace the uses of II, which is known not to overflow, by the corresponding plain binary operation a...
static bool getConstraintFromMemoryAccess(GetElementPtrInst &GEP, uint64_t AccessSize, CmpPredicate &Pred, Value *&A, Value *&B, const DataLayout &DL, const TargetLibraryInfo &TLI)
static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
static void generateReproducer(Instruction *Cond, bool IsSigned, Module *M, ArrayRef< ReproducerEntry > Stack, ConstraintInfo &Info, DominatorTree &DT)
Helper function to generate a reproducer function for simplifying Cond.
static bool checkAndReplaceUSubSat(SaturatingInst *USub, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
Try to replace USub by a plain subtract, if Info proves it cannot saturate.
static bool hasLimitWitness(const ConstraintInfo &Info, Value *Op, const APInt &Slack, bool Signed, bool Upper)
Returns true if Op <= MaxVal - Slack holds in the system for Signed, by scanning it for a row of the ...
static bool checkAndReplaceCondition(CmpPredicate Pred, Value *A, Value *B, Instruction *CheckInst, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, Instruction *ContextInst, Module *ReproducerModule, ArrayRef< ReproducerEntry > ReproducerCondStack, DominatorTree &DT, SmallVectorImpl< Instruction * > &ToRemove)
static Instruction * findCommonDominatorOfUses(Instruction &I, DominatorTree &DT)
Returns the closest program point dominating all uses of I.
static Decomposition decomposeImpl(Value *V, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info, SmallVectorImpl< Instruction * > &ToRemove)
static std::pair< Value *, Value * > getStartAndBackedgeValue(const PHINode &PN, const BasicBlock *LoopPred)
Splits the induction phi PN into the start value, coming from the loop predecessor LoopPred,...
static Decomposition decomposeGEP(GEPOperator &GEP, ConstraintInfo &Info, bool IsSigned, const DataLayout &DL)
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
#define DEBUG_TYPE
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.
static std::optional< bool > getKnownSign(Value *Op, const SimplifyQuery &SQ)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
This file defines the PointerIntPair class.
static StringRef getName(Value *V)
SmallVector< MachineOperand, 4 > Cond
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
This class represents a ucmp/scmp intrinsic.
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getInverse(CmpPredicate P)
Get the inverse predicate of a CmpPredicate.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isNegative() const
Definition Constants.h:214
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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:174
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
bool addRow(ArrayRef< Entry > R, size_t NumVars)
static RowTy negate(RowTy R)
unsigned size() const
Returns the number of rows in the constraint system.
LLVM_ABI std::pair< ConstraintSystem, RowTy > getSubSystem(ArrayRef< Entry > R) const
Build and return a sub-system of constraints connected (transitively) to query R, with variables comp...
static RowTy toStrictLessThan(RowTy R)
Converts the given row to form a strict less than inequality.
static LLVM_ABI void normalizeByGCD(MutableArrayRef< Entry > R)
Divide the variable coefficients of R by their greatest common divisor G and round the constant down ...
LLVM_ABI bool isConditionImpliedInSubSystem(ArrayRef< Entry > R) const
SmallVector< Entry, 8 > RowTy
A single constraint of the form 'c >= v1 * c1 + ... + vn * cn'.
static RowTy negateOrEqual(RowTy R)
Multiplies each coefficient in the given row by -1.
LLVM_ABI 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:64
static bool shouldExecute(CounterInfo &Counter)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
NodeT * getBlock() const
unsigned getDFSNumOut() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
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:122
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
static GEPNoWrapFlags none()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
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.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
size_type size() const
Definition MapVector.h:59
This class represents min/max intrinsics.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
Represents a saturating add/sub intrinsic.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
MonotonicPredicateType
A predicate is said to be monotonically increasing if may go from being false to being true as the lo...
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LLVM_ABI 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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void truncate(size_type N)
Like resize, but requires that N is less than size().
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI const Value * stripPointerCastsSameRepresentation() const
Strip off pointer casts, all-zero GEPs and address space casts but ensures the representation of the ...
Definition Value.cpp:715
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:556
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
CommutativeBinaryIntrinsic_match< IntrID, T0, T1 > m_c_Intrinsic(const T0 &Op0, const T1 &Op1)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
Exact_match< T > m_Exact(const T &SubPattern)
LogicalOp_match< LHS, RHS, Instruction::And, true > m_c_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
LogicalOp_match< LHS, RHS, Instruction::Or, true > m_c_LogicalOr(const LHS &L, const RHS &R)
Matches L || R with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
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:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:703
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI std::optional< TypeSize > getBaseObjectSize(const Value *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Like getObjectSize(), but only returns the size of base objects (like allocas, global variables and a...
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > SubOverflow(T X, T Y)
Subtract two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:740
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI bool isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
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:1933
LLVM_ABI 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:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:777
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI 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.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344