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