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