LLVM 24.0.0git
ScalarEvolutionDivision.cpp
Go to the documentation of this file.
1//===- ScalarEvolutionDivision.h - See below --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the class that knows how to divide SCEV's.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/DenseMap.h"
21#include <cassert>
22
23#define DEBUG_TYPE "scev-division"
24
25namespace llvm {
26class Type;
27} // namespace llvm
28
29using namespace llvm;
30
31static inline int sizeOfSCEV(const SCEV *S) {
32 struct FindSCEVSize {
33 int Size = 0;
34
35 FindSCEVSize() = default;
36
37 bool follow(const SCEV *S) {
38 ++Size;
39 // Keep looking at all operands of S.
40 return true;
41 }
42
43 bool isDone() const { return false; }
44 };
45
46 FindSCEVSize F;
48 ST.visitAll(S);
49 return F.Size;
50}
51
52// Computes the Quotient and Remainder of the division of Numerator by
53// Denominator.
54void SCEVDivision::divide(ScalarEvolution &SE, const SCEV *Numerator,
55 const SCEV *Denominator, const SCEV **Quotient,
56 const SCEV **Remainder) {
57 assert(Numerator && Denominator && "Uninitialized SCEV");
58 assert(Numerator->getType() == Denominator->getType() &&
59 "Numerator and Denominator must have the same type");
60
61 SCEVDivision D(SE, Numerator, Denominator);
62
63 // Check for the trivial case here to avoid having to check for it in the
64 // rest of the code.
65 if (Numerator == Denominator) {
66 *Quotient = D.One;
67 *Remainder = D.Zero;
68 return;
69 }
70
71 if (Numerator->isZero()) {
72 *Quotient = D.Zero;
73 *Remainder = D.Zero;
74 return;
75 }
76
77 // A simple case when N/1. The quotient is N.
78 if (Denominator->isOne()) {
79 *Quotient = Numerator;
80 *Remainder = D.Zero;
81 return;
82 }
83
84 // Split the Denominator when it is a product.
85 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
86 const SCEV *Q, *R;
87 *Quotient = Numerator;
88 for (const SCEV *Op : T->operands()) {
89 divide(SE, *Quotient, Op, &Q, &R);
90 *Quotient = Q;
91
92 // Bail out when the Numerator is not divisible by one of the terms of
93 // the Denominator.
94 if (!R->isZero()) {
95 *Quotient = D.Zero;
96 *Remainder = Numerator;
97 return;
98 }
99 }
100 *Remainder = D.Zero;
101 return;
102 }
103
104 D.visit(Numerator);
105 *Quotient = D.Quotient;
106 *Remainder = D.Remainder;
107}
108
110 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
111 APInt NumeratorVal = Numerator->getAPInt();
112 APInt DenominatorVal = D->getAPInt();
113 assert(NumeratorVal.getBitWidth() == DenominatorVal.getBitWidth() &&
114 "Numerator and Denominator must have the same bit width");
115
116 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
117 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
118 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
119 Quotient = SE.getConstant(QuotientVal);
120 Remainder = SE.getConstant(RemainderVal);
121 return;
122 }
123}
124
125void SCEVDivision::visitVScale(const SCEVVScale *Numerator) {
126 return cannotDivide(Numerator);
127}
128
130 const SCEV *StartQ, *StartR, *StepQ, *StepR;
131 if (!Numerator->isAffine())
132 return cannotDivide(Numerator);
133 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
134 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
135 // Bail out if the types do not match.
136 Type *Ty = Denominator->getType();
137 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
138 Ty != StepQ->getType() || Ty != StepR->getType())
139 return cannotDivide(Numerator);
140
141 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
142 SCEV::NoWrapFlags::FlagAnyWrap);
143 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
144 SCEV::NoWrapFlags::FlagAnyWrap);
145}
146
149 Type *Ty = Denominator->getType();
150
151 for (const SCEV *Op : Numerator->operands()) {
152 const SCEV *Q, *R;
153 divide(SE, Op, Denominator, &Q, &R);
154
155 // Bail out if types do not match.
156 if (Ty != Q->getType() || Ty != R->getType())
157 return cannotDivide(Numerator);
158
159 Qs.push_back(Q);
160 Rs.push_back(R);
161 }
162
163 if (Qs.size() == 1) {
164 Quotient = Qs[0];
165 Remainder = Rs[0];
166 return;
167 }
168
169 Quotient = SE.getAddExpr(Qs);
170 Remainder = SE.getAddExpr(Rs);
171}
172
175 Type *Ty = Denominator->getType();
176
177 bool FoundDenominatorTerm = false;
178 for (const SCEV *Op : Numerator->operands()) {
179 // Bail out if types do not match.
180 if (Ty != Op->getType())
181 return cannotDivide(Numerator);
182
183 if (FoundDenominatorTerm) {
184 Qs.push_back(Op);
185 continue;
186 }
187
188 // Check whether Denominator divides one of the product operands.
189 const SCEV *Q, *R;
190 divide(SE, Op, Denominator, &Q, &R);
191 if (!R->isZero()) {
192 Qs.push_back(Op);
193 continue;
194 }
195
196 // Bail out if types do not match.
197 if (Ty != Q->getType())
198 return cannotDivide(Numerator);
199
200 FoundDenominatorTerm = true;
201 Qs.push_back(Q);
202 }
203
204 if (FoundDenominatorTerm) {
205 Remainder = Zero;
206 if (Qs.size() == 1)
207 Quotient = Qs[0];
208 else
209 Quotient = SE.getMulExpr(Qs);
210 return;
211 }
212
213 if (!isa<SCEVUnknown>(Denominator))
214 return cannotDivide(Numerator);
215
216 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
217 ValueToSCEVMapTy RewriteMap;
218 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = Zero;
219 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap);
220
221 if (Remainder->isZero()) {
222 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
223 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = One;
224 Quotient = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap);
225 return;
226 }
227
228 // Quotient is (Numerator - Remainder) divided by Denominator.
229 const SCEV *Q, *R;
230 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
231 // This SCEV does not seem to simplify: fail the division here.
232 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
233 return cannotDivide(Numerator);
234 divide(SE, Diff, Denominator, &Q, &R);
235 if (R != Zero)
236 return cannotDivide(Numerator);
237 Quotient = Q;
238}
239
240SCEVDivision::SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
241 const SCEV *Denominator)
242 : SE(S), Denominator(Denominator) {
243 Zero = SE.getZero(Denominator->getType());
244 One = SE.getOne(Denominator->getType());
245
246 // We generally do not know how to divide Expr by Denominator. We initialize
247 // the division to a "cannot divide" state to simplify the rest of the code.
248 cannotDivide(Numerator);
249}
250
251// Convenience function for giving up on the division. We set the quotient to
252// be equal to zero and the remainder to be equal to the numerator.
253void SCEVDivision::cannotDivide(const SCEV *Numerator) {
254 Quotient = Zero;
255 Remainder = Numerator;
256}
257
258void SCEVDivisionPrinterPass::runImpl(Function &F, ScalarEvolution &SE) {
259 OS << "Printing analysis 'Scalar Evolution Division' for function '"
260 << F.getName() << "':\n";
261 for (Instruction &Inst : instructions(F)) {
262 BinaryOperator *Div = dyn_cast<BinaryOperator>(&Inst);
263 if (!Div || Div->getOpcode() != Instruction::SDiv)
264 continue;
265
266 const SCEV *Numerator = SE.getSCEV(Div->getOperand(0));
267 const SCEV *Denominator = SE.getSCEV(Div->getOperand(1));
268 const SCEV *Quotient, *Remainder;
269 SCEVDivision::divide(SE, Numerator, Denominator, &Quotient, &Remainder);
270
271 OS << "Instruction: " << *Div << "\n";
272 OS.indent(2) << "Numerator: " << *Numerator << "\n";
273 OS.indent(2) << "Denominator: " << *Denominator << "\n";
274 OS.indent(2) << "Quotient: " << *Quotient << "\n";
275 OS.indent(2) << "Remainder: " << *Remainder << "\n";
276 }
277}
278
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
Expand Atomic instructions
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
This file defines the DenseMap class.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
static int sizeOfSCEV(const SCEV *S)
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition APInt.h:78
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1926
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
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
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
const APInt & getAPInt() const
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This node represents multiplication of some number of SCEVs.
ArrayRef< SCEVUse > operands() const
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, ValueToSCEVMapTy &Map)
Visit all nodes in the expression tree using worklist traversal.
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Value * getOperand(unsigned i) const
Definition User.h:207
This is an optimization pass for GlobalISel generic memory operations.
DenseMap< const Value *, const SCEV * > ValueToSCEVMapTy
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
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
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static LLVM_ABI void divide(ScalarEvolution &SE, const SCEV *Numerator, const SCEV *Denominator, const SCEV **Quotient, const SCEV **Remainder)
Computes the Quotient and Remainder of the division of Numerator by Denominator.
LLVM_ABI void visitVScale(const SCEVVScale *Numerator)
LLVM_ABI void visitAddRecExpr(const SCEVAddRecExpr *Numerator)
LLVM_ABI void visitConstant(const SCEVConstant *Numerator)
LLVM_ABI void visitAddExpr(const SCEVAddExpr *Numerator)
LLVM_ABI void visitMulExpr(const SCEVMulExpr *Numerator)