MLIR 24.0.0git
ValueBoundsOpInterface.cpp
Go to the documentation of this file.
1//===- ValueBoundsOpInterface.cpp - Value Bounds -------------------------===//
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
10
12#include "mlir/IR/Matchers.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/SmallVectorExtras.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/DebugLog.h"
19#include "llvm/Support/MathExtras.h"
20
21#include <utility>
22
23#define DEBUG_TYPE "value-bounds-op-interface"
24
25using namespace mlir;
28
29namespace mlir {
30#include "mlir/Interfaces/ValueBoundsOpInterface.cpp.inc"
31} // namespace mlir
32
39
46
53
60
62 if (auto bbArg = dyn_cast<BlockArgument>(value))
63 return bbArg.getOwner()->getParentOp();
64 return value.getDefiningOp();
65}
66
70 : mixedOffsets(offsets), mixedSizes(sizes), mixedStrides(strides) {
71 assert(offsets.size() == sizes.size() &&
72 "expected same number of offsets, sizes, strides");
73 assert(offsets.size() == strides.size() &&
74 "expected same number of offsets, sizes, strides");
75}
76
79 : mixedOffsets(offsets), mixedSizes(sizes) {
80 assert(offsets.size() == sizes.size() &&
81 "expected same number of offsets and sizes");
82 // Assume that all strides are 1.
83 if (offsets.empty())
84 return;
85 MLIRContext *ctx = offsets.front().getContext();
86 mixedStrides.append(offsets.size(), Builder(ctx).getIndexAttr(1));
87}
88
92
93/// If ofr is a constant integer or an IntegerAttr, return the integer.
94static std::optional<int64_t> getConstantIntValue(OpFoldResult ofr) {
95 // Case 1: Check for Constant integer.
96 if (auto val = llvm::dyn_cast_if_present<Value>(ofr)) {
97 APSInt intVal;
98 if (matchPattern(val, m_ConstantInt(&intVal)))
99 return intVal.getSExtValue();
100 return std::nullopt;
101 }
102 // Case 2: Check for IntegerAttr.
103 Attribute attr = llvm::dyn_cast_if_present<Attribute>(ofr);
104 if (auto intAttr = dyn_cast_or_null<IntegerAttr>(attr))
105 return intAttr.getValue().getSExtValue();
106 return std::nullopt;
107}
108
109[[maybe_unused]] static bool isIndexOrIntegerType(Type type) {
110 return type.isIndex() || type.isInteger();
111}
112
113[[maybe_unused]] static bool isIndexLikeType(Type type,
115 return type.isIndex() || (options.allowIntegerType && type.isInteger());
116}
117
120
122 : Variable(static_cast<OpFoldResult>(indexValue)) {}
123
125 : Variable(static_cast<OpFoldResult>(shapedValue), std::optional(dim)) {}
126
128 std::optional<int64_t> dim) {
129 Builder b(ofr.getContext());
130 if (auto constInt = ::getConstantIntValue(ofr)) {
131 assert(!dim && "expected no dim for index/integer-typed values");
132 map = AffineMap::get(/*dimCount=*/0, /*symbolCount=*/0,
133 b.getAffineConstantExpr(*constInt));
134 return;
135 }
136 Value value = cast<Value>(ofr);
137#ifndef NDEBUG
138 if (dim) {
139 assert(isa<ShapedType>(value.getType()) && "expected shaped type");
140 } else {
141 assert(isIndexOrIntegerType(value.getType()) &&
142 "expected index or integer type");
143 }
144#endif // NDEBUG
145 map = AffineMap::get(/*dimCount=*/0, /*symbolCount=*/1,
146 b.getAffineSymbolExpr(0));
147 mapOperands.emplace_back(value, dim);
148}
149
151 ArrayRef<Variable> mapOperands) {
152 assert(map.getNumResults() == 1 && "expected single result");
153
154 // Turn all dims into symbols.
155 Builder b(map.getContext());
156 // Inline size chosen empirically based on compilation profiling.
157 // Profiled: 490K calls, avg=1.5+-0.6. N=4 covers >99% of cases inline.
158 SmallVector<AffineExpr, 4> dimReplacements, symReplacements;
159 for (int64_t i = 0, e = map.getNumDims(); i < e; ++i)
160 dimReplacements.push_back(b.getAffineSymbolExpr(i));
161 for (int64_t i = 0, e = map.getNumSymbols(); i < e; ++i)
162 symReplacements.push_back(b.getAffineSymbolExpr(i + map.getNumDims()));
163 AffineMap tmpMap = map.replaceDimsAndSymbols(
164 dimReplacements, symReplacements, /*numResultDims=*/0,
165 /*numResultSyms=*/map.getNumSymbols() + map.getNumDims());
166
167 // Inline operands.
169 for (auto [index, var] : llvm::enumerate(mapOperands)) {
170 assert(var.map.getNumResults() == 1 && "expected single result");
171 assert(var.map.getNumDims() == 0 && "expected only symbols");
172 SmallVector<AffineExpr> symReplacements;
173 for (auto valueDim : var.mapOperands) {
174 auto *it = llvm::find(this->mapOperands, valueDim);
175 if (it != this->mapOperands.end()) {
176 // There is already a symbol for this operand.
177 symReplacements.push_back(b.getAffineSymbolExpr(
178 std::distance(this->mapOperands.begin(), it)));
179 } else {
180 // This is a new operand: add a new symbol.
181 symReplacements.push_back(
182 b.getAffineSymbolExpr(this->mapOperands.size()));
183 this->mapOperands.push_back(valueDim);
184 }
185 }
186 replacements[b.getAffineSymbolExpr(index)] =
187 var.map.getResult(0).replaceSymbols(symReplacements);
188 }
189 this->map = tmpMap.replace(replacements, /*numResultDims=*/0,
190 /*numResultSyms=*/this->mapOperands.size());
191}
192
194 ValueRange mapOperands)
195 : Variable(map, llvm::map_to_vector(mapOperands,
196 [](Value v) { return Variable(v); })) {}
197
205
207
208#ifndef NDEBUG
209static void assertValidValueDim(Value value, std::optional<int64_t> dim,
211 if (isIndexLikeType(value.getType(), options)) {
212 assert(!dim.has_value() && "invalid dim value");
213 } else if (auto shapedType = dyn_cast<ShapedType>(value.getType())) {
214 assert(*dim >= 0 && "invalid dim value");
215 if (shapedType.hasRank())
216 assert(*dim < shapedType.getRank() && "invalid dim value");
217 } else {
218 llvm_unreachable("unsupported type");
219 }
220}
221#endif // NDEBUG
222
224 AffineExpr expr) {
225 // Note: If `addConservativeSemiAffineBounds` is true then the bound
226 // computation function needs to handle the case that the constraints set
227 // could become empty. This is because the conservative bounds add assumptions
228 // (e.g. for `mod` it assumes `rhs > 0`). If these constraints are later found
229 // not to hold, then the bound is invalid.
230 LogicalResult status = cstr.addBound(
231 type, pos,
232 AffineMap::get(cstr.getNumDimVars(), cstr.getNumSymbolVars(), expr),
236 if (failed(status)) {
237 // Not all semi-affine expressions are not yet supported by
238 // FlatLinearConstraints. However, we can just ignore such failures here.
239 // Even without this bound, there may be enough information in the
240 // constraint system to compute the requested bound. In case this bound is
241 // actually needed, `computeBound` will return `failure`.
242 LDBG() << "Failed to add bound: " << expr << "\n";
243 }
244}
245
247 std::optional<int64_t> dim) {
248#ifndef NDEBUG
249 assertValidValueDim(value, dim, options);
250#endif // NDEBUG
251
252 // Check if the value/dim is statically known. In that case, an affine
253 // constant expression should be returned. This allows us to support
254 // multiplications with constants. (Multiplications of two columns in the
255 // constraint set is not supported.)
256 std::optional<int64_t> constSize = std::nullopt;
257 auto shapedType = dyn_cast<ShapedType>(value.getType());
258 if (shapedType) {
259 if (shapedType.hasRank() && !shapedType.isDynamicDim(*dim))
260 constSize = shapedType.getDimSize(*dim);
261 } else if (auto constInt = ::getConstantIntValue(value)) {
262 constSize = *constInt;
263 }
264
265 // If the value/dim is already mapped, return the corresponding expression
266 // directly.
267 ValueDim valueDim = std::make_pair(value, dim.value_or(kIndexValue));
268 if (valueDimToPosition.contains(valueDim)) {
269 // If it is a constant, return an affine constant expression. Otherwise,
270 // return an affine expression that represents the respective column in the
271 // constraint set.
272 if (constSize)
273 return builder.getAffineConstantExpr(*constSize);
274 return getPosExpr(getPos(value, dim));
275 }
276
277 if (constSize) {
278 // Constant index value/dim: add column to the constraint set, add EQ bound
279 // and return an affine constant expression without pushing the newly added
280 // column to the worklist.
281 (void)insert(value, dim, /*isSymbol=*/true, /*addToWorklist=*/false);
282 if (shapedType)
283 bound(value)[*dim] == *constSize;
284 else
285 bound(value) == *constSize;
286 return builder.getAffineConstantExpr(*constSize);
287 }
288
289 // Dynamic value/dim: insert column to the constraint set and put it on the
290 // worklist. Return an affine expression that represents the newly inserted
291 // column in the constraint set.
292 return getPosExpr(insert(value, dim, /*isSymbol=*/true));
293}
294
296 if (Value value = llvm::dyn_cast_if_present<Value>(ofr))
297 return getExpr(value, /*dim=*/std::nullopt);
298 auto constInt = ::getConstantIntValue(ofr);
299 assert(constInt.has_value() && "expected Integer constant");
300 return builder.getAffineConstantExpr(*constInt);
301}
302
304 return builder.getAffineConstantExpr(constant);
305}
306
308 std::optional<int64_t> dim,
309 bool isSymbol, bool addToWorklist) {
310#ifndef NDEBUG
311 assertValidValueDim(value, dim, options);
312#endif // NDEBUG
313
314 ValueDim valueDim = std::make_pair(value, dim.value_or(kIndexValue));
315 assert(!valueDimToPosition.contains(valueDim) && "already mapped");
316 int64_t pos = isSymbol ? cstr.appendVar(VarKind::Symbol)
317 : cstr.appendVar(VarKind::SetDim);
318 LDBG() << "Inserting constraint set column " << pos << " for: " << value
319 << " (dim: " << dim.value_or(kIndexValue)
320 << ", owner: " << getOwnerOfValue(value)->getName() << ")";
321 positionToValueDim.insert(positionToValueDim.begin() + pos, valueDim);
322 // Update reverse mapping.
323 for (int64_t i = pos, e = positionToValueDim.size(); i < e; ++i)
324 if (positionToValueDim[i].has_value())
326
327 // Do not add block arguments from non-entry blocks to the worklist. The
328 // ValueBoundsOpInterface cannot derive any bounds for such values (they
329 // arise from unstructured control flow), so putting them on the worklist
330 // would be a no-op. More importantly, suppressing the worklist push ensures
331 // that processWorklist never calls getExpr on such a value a second time,
332 // which would otherwise cause the same value to be looked up as already
333 // mapped (triggering an unintended bug path).
334 if (addToWorklist &&
335 (!isa<BlockArgument>(value) ||
336 cast<BlockArgument>(value).getOwner()->isEntryBlock())) {
337 LDBG() << "Push to worklist: " << value
338 << " (dim: " << dim.value_or(kIndexValue) << ")";
339 worklist.push(valueDim);
340 }
341
342 return pos;
343}
344
346 int64_t pos = isSymbol ? cstr.appendVar(VarKind::Symbol)
347 : cstr.appendVar(VarKind::SetDim);
348 LDBG() << "Inserting anonymous constraint set column " << pos;
349 positionToValueDim.insert(positionToValueDim.begin() + pos, std::nullopt);
350 // Update reverse mapping.
351 for (int64_t i = pos, e = positionToValueDim.size(); i < e; ++i)
352 if (positionToValueDim[i].has_value())
354 return pos;
355}
356
358 const ValueDimList &operands,
359 bool isSymbol) {
360 assert(map.getNumResults() == 1 && "expected affine map with one result");
361 int64_t pos = insert(isSymbol);
362
363 // Add map and operands to the constraint set. Dimensions are converted to
364 // symbols. All operands are added to the worklist (unless they were already
365 // processed).
366 auto mapper = [&](std::pair<Value, std::optional<int64_t>> v) {
367 return getExpr(v.first, v.second);
368 };
369 SmallVector<AffineExpr> dimReplacements = llvm::map_to_vector(
370 ArrayRef(operands).take_front(map.getNumDims()), mapper);
371 SmallVector<AffineExpr> symReplacements = llvm::map_to_vector(
372 ArrayRef(operands).drop_front(map.getNumDims()), mapper);
373 addBound(
375 map.getResult(0).replaceDimsAndSymbols(dimReplacements, symReplacements));
376
377 return pos;
378}
379
381 return insert(var.map, var.mapOperands, isSymbol);
382}
383
385 std::optional<int64_t> dim) const {
386#ifndef NDEBUG
387 assertValidValueDim(value, dim, options);
388#endif // NDEBUG
389 LDBG() << "Getting pos for: " << value
390 << " (dim: " << dim.value_or(kIndexValue)
391 << ", owner: " << getOwnerOfValue(value)->getName() << ")";
392 auto it =
393 valueDimToPosition.find(std::make_pair(value, dim.value_or(kIndexValue)));
394 assert(it != valueDimToPosition.end() && "expected mapped entry");
395 return it->second;
396}
397
399 assert(pos >= 0 && pos < cstr.getNumDimAndSymbolVars() && "invalid position");
400 return pos < cstr.getNumDimVars()
401 ? builder.getAffineDimExpr(pos)
402 : builder.getAffineSymbolExpr(pos - cstr.getNumDimVars());
403}
404
406 std::optional<int64_t> dim) const {
407 auto it =
408 valueDimToPosition.find(std::make_pair(value, dim.value_or(kIndexValue)));
409 return it != valueDimToPosition.end();
410}
411
413 LDBG() << "Processing value bounds worklist...";
414 while (!worklist.empty()) {
415 ValueDim valueDim = worklist.front();
416 worklist.pop();
417 assert(valueDimToPosition.contains(valueDim) &&
418 "expected mapped worklist entry");
419 Value value = valueDim.first;
420 int64_t dim = valueDim.second;
421
422 // Check for static dim size.
423 if (dim != kIndexValue) {
424 auto shapedType = cast<ShapedType>(value.getType());
425 if (shapedType.hasRank() && !shapedType.isDynamicDim(dim)) {
426 bound(value)[dim] == getExpr(shapedType.getDimSize(dim));
427 continue;
428 }
429 }
430
431 // Do not process any further if the stop condition is met.
432 auto maybeDim = dim == kIndexValue ? std::nullopt : std::make_optional(dim);
433 if (stopCondition(value, maybeDim, *this)) {
434 LDBG() << "Stop condition met for: " << value << " (dim: " << maybeDim
435 << ")";
436 continue;
437 }
438
439 // Query `ValueBoundsOpInterface` for constraints. New items may be added to
440 // the worklist.
441 auto valueBoundsOp =
442 dyn_cast<ValueBoundsOpInterface>(getOwnerOfValue(value));
443 LDBG() << "Query value bounds for: " << value
444 << " (owner: " << getOwnerOfValue(value)->getName() << ")";
445 if (valueBoundsOp) {
446 if (dim == kIndexValue) {
447 valueBoundsOp.populateBoundsForIndexValue(value, *this);
448 } else {
449 valueBoundsOp.populateBoundsForShapedValueDim(value, dim, *this);
450 }
451 continue;
452 }
453 LDBG() << "--> ValueBoundsOpInterface not implemented";
454
455 // If the op does not implement `ValueBoundsOpInterface`, check if it
456 // implements the `DestinationStyleOpInterface`. OpResults of such ops are
457 // tied to OpOperands. Tied values have the same shape.
458 auto dstOp = value.getDefiningOp<DestinationStyleOpInterface>();
459 if (!dstOp || dim == kIndexValue)
460 continue;
461 Value tiedOperand = dstOp.getTiedOpOperand(cast<OpResult>(value))->get();
462 bound(value)[dim] == getExpr(tiedOperand, dim);
463 }
464}
465
467 assert(pos >= 0 && pos < static_cast<int64_t>(positionToValueDim.size()) &&
468 "invalid position");
469 cstr.projectOut(pos);
470 if (positionToValueDim[pos].has_value()) {
471 bool erased = valueDimToPosition.erase(*positionToValueDim[pos]);
472 (void)erased;
473 assert(erased && "inconsistent reverse mapping");
474 }
475 positionToValueDim.erase(positionToValueDim.begin() + pos);
476 // Update reverse mapping.
477 for (int64_t i = pos, e = positionToValueDim.size(); i < e; ++i)
478 if (positionToValueDim[i].has_value())
480}
481
483 function_ref<bool(ValueDim)> condition) {
484 int64_t nextPos = 0;
485 while (nextPos < static_cast<int64_t>(positionToValueDim.size())) {
486 if (positionToValueDim[nextPos].has_value() &&
487 condition(*positionToValueDim[nextPos])) {
488 projectOut(nextPos);
489 // The column was projected out so another column is now at that position.
490 // Do not increase the counter.
491 } else {
492 ++nextPos;
493 }
494 }
495}
496
498 std::optional<int64_t> except) {
499 int64_t nextPos = 0;
500 while (nextPos < static_cast<int64_t>(positionToValueDim.size())) {
501 if (positionToValueDim[nextPos].has_value() || except == nextPos) {
502 ++nextPos;
503 } else {
504 projectOut(nextPos);
505 // The column was projected out so another column is now at that position.
506 // Do not increase the counter.
507 }
508 }
509}
510
512 AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type,
515 MLIRContext *ctx = var.getContext();
516 int64_t ubAdjustment = options.closedUB ? 0 : 1;
517 Builder b(ctx);
518 mapOperands.clear();
519
520 // Process the backward slice of `value` (i.e., reverse use-def chain) until
521 // `stopCondition` is met.
523 int64_t pos = cstr.insert(var, /*isSymbol=*/false);
524 assert(pos == 0 && "expected first column");
525 cstr.processWorklist();
526
527 // Project out all variables (apart from `valueDim`) that do not match the
528 // stop condition.
529 cstr.projectOut([&](ValueDim p) {
530 auto maybeDim =
531 p.second == kIndexValue ? std::nullopt : std::make_optional(p.second);
532 return !stopCondition(p.first, maybeDim, cstr);
533 });
534 cstr.projectOutAnonymous(/*except=*/pos);
535
536 // Compute lower and upper bounds for `valueDim`.
537 SmallVector<AffineMap> lb(1), ub(1);
538 cstr.cstr.getSliceBounds(pos, 1, ctx, &lb, &ub,
539 /*closedUB=*/true);
540
541 // Note: There are TODOs in the implementation of `getSliceBounds`. In such a
542 // case, no lower/upper bound can be computed at the moment.
543 // EQ, UB bounds: upper bound is needed.
544 if ((type != BoundType::LB) &&
545 (ub.empty() || !ub[0] || ub[0].getNumResults() == 0))
546 return failure();
547 // EQ, LB bounds: lower bound is needed.
548 if ((type != BoundType::UB) &&
549 (lb.empty() || !lb[0] || lb[0].getNumResults() == 0))
550 return failure();
551
552 // TODO: Generate an affine map with multiple results.
553 if (type != BoundType::LB)
554 assert(ub.size() == 1 && ub[0].getNumResults() == 1 &&
555 "multiple bounds not supported");
556 if (type != BoundType::UB)
557 assert(lb.size() == 1 && lb[0].getNumResults() == 1 &&
558 "multiple bounds not supported");
559
560 // EQ bound: lower and upper bound must match.
561 if (type == BoundType::EQ && ub[0] != lb[0])
562 return failure();
563
565 if (type == BoundType::EQ || type == BoundType::LB) {
566 bound = lb[0];
567 } else {
568 // Computed UB is a closed bound.
569 bound = AffineMap::get(ub[0].getNumDims(), ub[0].getNumSymbols(),
570 ub[0].getResult(0) + ubAdjustment);
571 }
572
573 // Gather all SSA values that are used in the computed bound.
574 assert(cstr.cstr.getNumDimAndSymbolVars() == cstr.positionToValueDim.size() &&
575 "inconsistent mapping state");
576 SmallVector<AffineExpr> replacementDims, replacementSymbols;
577 int64_t numDims = 0, numSymbols = 0;
578 for (int64_t i = 0; i < cstr.cstr.getNumDimAndSymbolVars(); ++i) {
579 // Skip `value`.
580 if (i == pos)
581 continue;
582 // Check if the position `i` is used in the generated bound. If so, it must
583 // be included in the generated affine.apply op.
584 bool used = false;
585 bool isDim = i < cstr.cstr.getNumDimVars();
586 if (isDim) {
587 if (bound.isFunctionOfDim(i))
588 used = true;
589 } else {
590 if (bound.isFunctionOfSymbol(i - cstr.cstr.getNumDimVars()))
591 used = true;
592 }
593
594 if (!used) {
595 // Not used: Remove dim/symbol from the result.
596 if (isDim) {
597 replacementDims.push_back(b.getAffineConstantExpr(0));
598 } else {
599 replacementSymbols.push_back(b.getAffineConstantExpr(0));
600 }
601 continue;
602 }
603
604 if (isDim) {
605 replacementDims.push_back(b.getAffineDimExpr(numDims++));
606 } else {
607 replacementSymbols.push_back(b.getAffineSymbolExpr(numSymbols++));
608 }
609
610 assert(cstr.positionToValueDim[i].has_value() &&
611 "cannot build affine map in terms of anonymous column");
612 ValueBoundsConstraintSet::ValueDim valueDim = *cstr.positionToValueDim[i];
613 Value value = valueDim.first;
614 int64_t dim = valueDim.second;
616 // An index-typed/integer-typed value is used: it can be used directly in
617 // the computed bound.
618 assert(isIndexLikeType(value.getType(), options) &&
619 "expected index or integer type");
620 mapOperands.push_back(std::make_pair(value, std::nullopt));
621 continue;
622 }
623
624 assert(cast<ShapedType>(value.getType()).isDynamicDim(dim) &&
625 "expected dynamic dim");
626 mapOperands.push_back(std::make_pair(value, dim));
627 }
628
629 resultMap = bound.replaceDimsAndSymbols(replacementDims, replacementSymbols,
630 numDims, numSymbols);
631 return success();
632}
633
635 AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type,
636 const Variable &var, ValueDimList dependencies,
638 return computeBound(
639 resultMap, mapOperands, type, var,
640 [&](Value v, std::optional<int64_t> d, ValueBoundsConstraintSet &cstr) {
641 return llvm::is_contained(dependencies, std::make_pair(v, d));
642 },
643 options);
644}
645
647 AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type,
648 const Variable &var, ValueRange independencies,
650 // Return "true" if the given value is independent of all values in
651 // `independencies`. I.e., neither the value itself nor any value in the
652 // backward slice (reverse use-def chain) is contained in `independencies`.
653 auto isIndependent = [&](Value v) {
655 DenseSet<Value> visited;
656 worklist.push_back(v);
657 while (!worklist.empty()) {
658 Value next = worklist.pop_back_val();
659 if (!visited.insert(next).second)
660 continue;
661 if (llvm::is_contained(independencies, next))
662 return false;
663 // TODO: DominanceInfo could be used to stop the traversal early.
664 Operation *op = next.getDefiningOp();
665 if (!op)
666 continue;
667 worklist.append(op->getOperands().begin(), op->getOperands().end());
668 }
669 return true;
670 };
671
672 // Reify bounds in terms of any independent values.
673 return computeBound(
674 resultMap, mapOperands, type, var,
675 [&](Value v, std::optional<int64_t> d, ValueBoundsConstraintSet &cstr) {
676 return isIndependent(v);
677 },
678 options);
679}
680
682 presburger::BoundType type, const Variable &var,
684 // Computing a bound projects out the other variables. Check at exponentially
685 // spaced visits to avoid repeating this work for every value in a long slice.
686 int64_t pos = 0;
687 uint64_t numVisited = 0;
688 bool foundBound = false;
689 auto defaultStopCondition = [&](Value, std::optional<int64_t>,
691 if (!foundBound && llvm::isPowerOf2_64(++numVisited))
692 foundBound = cstr.cstr.getConstantBound64(type, pos).has_value();
693 return foundBound;
694 };
695
697 var.getContext(), stopCondition ? stopCondition : defaultStopCondition,
698 options);
699 pos = cstr.populateConstraints(var.map, var.mapOperands);
700 assert(pos == 0 && "expected `map` is the first column");
701
702 // Compute constant bound for `valueDim`.
703 int64_t ubAdjustment = options.closedUB ? 0 : 1;
704 if (auto bound = cstr.cstr.getConstantBound64(type, pos))
705 return type == BoundType::UB ? *bound + ubAdjustment : *bound;
706 return failure();
707}
708
710 std::optional<int64_t> dim) {
711#ifndef NDEBUG
712 assertValidValueDim(value, dim, options);
713#endif // NDEBUG
714
715 // `getExpr` pushes the value/dim onto the worklist (unless it was already
716 // analyzed).
717 (void)getExpr(value, dim);
718 // Process all values/dims on the worklist. This may traverse and analyze
719 // additional IR, depending the current stop function.
721}
722
724 ValueDimList operands) {
725 int64_t pos = insert(map, std::move(operands), /*isSymbol=*/false);
726 // Process the backward slice of `operands` (i.e., reverse use-def chain)
727 // until `stopCondition` is met.
729 return pos;
730}
731
732FailureOr<int64_t>
734 std::optional<int64_t> dim1,
735 std::optional<int64_t> dim2) {
736#ifndef NDEBUG
737 assertValidValueDim(value1, dim1, /*options=*/{});
738 assertValidValueDim(value2, dim2, /*options=*/{});
739#endif // NDEBUG
740
741 Builder b(value1.getContext());
742 AffineMap map = AffineMap::get(/*dimCount=*/2, /*symbolCount=*/0,
743 b.getAffineDimExpr(0) - b.getAffineDimExpr(1));
745 Variable(map, {{value1, dim1}, {value2, dim2}}));
746}
747
750 int64_t rhsPos) {
751 // This function returns "true" if "lhs CMP rhs" is proven to hold.
752 //
753 // Example for ComparisonOperator::LE and index-typed values: We would like to
754 // prove that lhs <= rhs. Proof by contradiction: add the inverse
755 // relation (lhs > rhs) to the constraint set and check if the resulting
756 // constraint set is "empty" (i.e. has no solution). In that case,
757 // lhs > rhs must be incorrect and we can deduce that lhs <= rhs holds.
758
759 // We cannot prove anything if the constraint set is already empty.
760 if (cstr.isEmpty()) {
761 LDBG() << "cannot compare value/dims: constraint system is already empty";
762 return false;
763 }
764
765 // EQ can be expressed as LE and GE.
766 if (cmp == EQ)
767 return comparePos(lhsPos, ComparisonOperator::LE, rhsPos) &&
768 comparePos(lhsPos, ComparisonOperator::GE, rhsPos);
769
770 // Construct inequality.
771 // Inline size chosen empirically based on compilation profiling.
772 // Profiled: 3.2M calls, avg=4.0+-2.3. N=8 covers ~95% of cases inline.
773 SmallVector<int64_t, 8> eq(cstr.getNumCols(), 0);
774 if (cmp == LT || cmp == LE) {
775 ++eq[lhsPos];
776 --eq[rhsPos];
777 } else if (cmp == GT || cmp == GE) {
778 --eq[lhsPos];
779 ++eq[rhsPos];
780 } else {
781 llvm_unreachable("unsupported comparison operator");
782 }
783 if (cmp == LE || cmp == GE)
784 eq[cstr.getNumCols() - 1] -= 1;
785
786 // Add inequality to the constraint set and check if it made the constraint
787 // set empty.
788 int64_t ineqPos = cstr.getNumInequalities();
789 cstr.addInequality(eq);
790 bool isEmpty = cstr.isEmpty();
791 cstr.removeInequality(ineqPos);
792 return isEmpty;
793}
794
796 int64_t lhsPos, ComparisonOperator cmp, int64_t rhsPos) {
797 auto strongCmp = [&](ComparisonOperator cmp,
798 ComparisonOperator negCmp) -> FailureOr<bool> {
799 if (comparePos(lhsPos, cmp, rhsPos))
800 return true;
801 if (comparePos(lhsPos, negCmp, rhsPos))
802 return false;
803 return failure();
804 };
805 switch (cmp) {
815 std::optional<bool> le =
817 if (!le)
818 return failure();
819 if (!*le)
820 return false;
821 std::optional<bool> ge =
823 if (!ge)
824 return failure();
825 if (!*ge)
826 return false;
827 return true;
828 }
829 }
830 llvm_unreachable("invalid comparison operator");
831}
832
835 const Variable &rhs) {
836 int64_t lhsPos = populateConstraints(lhs.map, lhs.mapOperands);
837 int64_t rhsPos = populateConstraints(rhs.map, rhs.mapOperands);
838 return comparePos(lhsPos, cmp, rhsPos);
839}
840
843 const Variable &rhs) {
844 int64_t lhsPos = -1, rhsPos = -1;
845 auto stopCondition = [&](Value v, std::optional<int64_t> dim,
847 // Keep processing as long as lhs/rhs were not processed.
848 if (size_t(lhsPos) >= cstr.positionToValueDim.size() ||
849 size_t(rhsPos) >= cstr.positionToValueDim.size())
850 return false;
851 // Keep processing as long as the relation cannot be proven.
852 return cstr.comparePos(lhsPos, cmp, rhsPos);
853 };
855 return cstr.populateAndCompare(lhs, cmp, rhs);
856}
857
860 const Variable &rhs) {
861 int64_t lhsPos = -1, rhsPos = -1;
862 auto stopCondition = [&](Value v, std::optional<int64_t> dim,
864 // Keep processing as long as lhs/rhs were not processed.
865 if (size_t(lhsPos) >= cstr.positionToValueDim.size() ||
866 size_t(rhsPos) >= cstr.positionToValueDim.size())
867 return false;
868 // Keep processing as long as the strong relation cannot be proven.
869 FailureOr<bool> ordered = cstr.strongComparePos(lhsPos, cmp, rhsPos);
870 return failed(ordered);
871 };
873 lhsPos = cstr.populateConstraints(lhs.map, lhs.mapOperands);
874 rhsPos = cstr.populateConstraints(rhs.map, rhs.mapOperands);
875 return cstr.strongComparePos(lhsPos, cmp, rhsPos);
876}
877
879 const Variable &var2) {
880 // Avoid constructing a constraint set for variables that are already known
881 // to be identical.
882 if (var1.map == var2.map && var1.mapOperands == var2.mapOperands)
883 return true;
884 return strongCompare(var1, ComparisonOperator::EQ, var2);
885}
886
888 MLIRContext *ctx, const HyperrectangularSlice &slice1,
889 const HyperrectangularSlice &slice2) {
890 assert(slice1.getMixedOffsets().size() == slice2.getMixedOffsets().size() &&
891 "expected slices of same rank");
892 assert(slice1.getMixedSizes().size() == slice2.getMixedSizes().size() &&
893 "expected slices of same rank");
894 assert(slice1.getMixedStrides().size() == slice2.getMixedStrides().size() &&
895 "expected slices of same rank");
896
897 Builder b(ctx);
898 bool foundUnknownBound = false;
899 for (int64_t i = 0, e = slice1.getMixedOffsets().size(); i < e; ++i) {
900 AffineMap map =
901 AffineMap::get(/*dimCount=*/0, /*symbolCount=*/4,
902 b.getAffineSymbolExpr(0) +
903 b.getAffineSymbolExpr(1) * b.getAffineSymbolExpr(2) -
904 b.getAffineSymbolExpr(3));
905 {
906 // Case 1: Slices are guaranteed to be non-overlapping if
907 // offset1 + size1 * stride1 <= offset2 (for at least one dimension).
908 SmallVector<OpFoldResult> ofrOperands;
909 ofrOperands.push_back(slice1.getMixedOffsets()[i]);
910 ofrOperands.push_back(slice1.getMixedSizes()[i]);
911 ofrOperands.push_back(slice1.getMixedStrides()[i]);
912 ofrOperands.push_back(slice2.getMixedOffsets()[i]);
913 SmallVector<Value> valueOperands;
914 AffineMap foldedMap =
915 foldAttributesIntoMap(b, map, ofrOperands, valueOperands);
916 FailureOr<int64_t> constBound = computeConstantBound(
917 presburger::BoundType::EQ, Variable(foldedMap, valueOperands));
918 foundUnknownBound |= failed(constBound);
919 if (succeeded(constBound) && *constBound <= 0)
920 return false;
921 }
922 {
923 // Case 2: Slices are guaranteed to be non-overlapping if
924 // offset2 + size2 * stride2 <= offset1 (for at least one dimension).
925 SmallVector<OpFoldResult> ofrOperands;
926 ofrOperands.push_back(slice2.getMixedOffsets()[i]);
927 ofrOperands.push_back(slice2.getMixedSizes()[i]);
928 ofrOperands.push_back(slice2.getMixedStrides()[i]);
929 ofrOperands.push_back(slice1.getMixedOffsets()[i]);
930 SmallVector<Value> valueOperands;
931 AffineMap foldedMap =
932 foldAttributesIntoMap(b, map, ofrOperands, valueOperands);
933 FailureOr<int64_t> constBound = computeConstantBound(
934 presburger::BoundType::EQ, Variable(foldedMap, valueOperands));
935 foundUnknownBound |= failed(constBound);
936 if (succeeded(constBound) && *constBound <= 0)
937 return false;
938 }
939 }
940
941 // If at least one bound could not be computed, we cannot be certain that the
942 // slices are really overlapping.
943 if (foundUnknownBound)
944 return failure();
945
946 // All bounds could be computed and none of the above cases applied.
947 // Therefore, the slices are guaranteed to overlap.
948 return true;
949}
950
952 MLIRContext *ctx, const HyperrectangularSlice &slice1,
953 const HyperrectangularSlice &slice2) {
954 assert(slice1.getMixedOffsets().size() == slice2.getMixedOffsets().size() &&
955 "expected slices of same rank");
956 assert(slice1.getMixedSizes().size() == slice2.getMixedSizes().size() &&
957 "expected slices of same rank");
958 assert(slice1.getMixedStrides().size() == slice2.getMixedStrides().size() &&
959 "expected slices of same rank");
960
961 // The two slices are equivalent if all of their offsets, sizes and strides
962 // are equal. If equality cannot be determined for at least one of those
963 // values, equivalence cannot be determined and this function returns
964 // "failure".
965 for (auto [offset1, offset2] :
966 llvm::zip_equal(slice1.getMixedOffsets(), slice2.getMixedOffsets())) {
967 FailureOr<bool> equal = areEqual(offset1, offset2);
968 if (failed(equal))
969 return failure();
970 if (!equal.value())
971 return false;
972 }
973 for (auto [size1, size2] :
974 llvm::zip_equal(slice1.getMixedSizes(), slice2.getMixedSizes())) {
975 FailureOr<bool> equal = areEqual(size1, size2);
976 if (failed(equal))
977 return failure();
978 if (!equal.value())
979 return false;
980 }
981 for (auto [stride1, stride2] :
982 llvm::zip_equal(slice1.getMixedStrides(), slice2.getMixedStrides())) {
983 FailureOr<bool> equal = areEqual(stride1, stride2);
984 if (failed(equal))
985 return failure();
986 if (!equal.value())
987 return false;
988 }
989 return true;
990}
991
992#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
994 llvm::errs() << "==========\nColumns:\n";
995 llvm::errs() << "(column\tdim\tvalue)\n";
996 for (auto [index, valueDim] : llvm::enumerate(positionToValueDim)) {
997 llvm::errs() << " " << index << "\t";
998 if (valueDim) {
999 if (valueDim->second == kIndexValue) {
1000 llvm::errs() << "n/a\t";
1001 } else {
1002 llvm::errs() << valueDim->second << "\t";
1003 }
1004 llvm::errs() << getOwnerOfValue(valueDim->first)->getName() << " ";
1005 if (OpResult result = dyn_cast<OpResult>(valueDim->first)) {
1006 llvm::errs() << "(result " << result.getResultNumber() << ")";
1007 } else {
1008 llvm::errs() << "(bbarg "
1009 << cast<BlockArgument>(valueDim->first).getArgNumber()
1010 << ")";
1011 }
1012 llvm::errs() << "\n";
1013 } else {
1014 llvm::errs() << "n/a\tn/a\n";
1015 }
1016 }
1017 llvm::errs() << "\nConstraint set:\n";
1018 cstr.dump();
1019 llvm::errs() << "==========\n";
1020}
1021#endif
1022
1025 assert(!this->dim.has_value() && "dim was already set");
1026 this->dim = dim;
1027#ifndef NDEBUG
1028 assertValidValueDim(value, this->dim, cstr.options);
1029#endif // NDEBUG
1030 return *this;
1031}
1032
1034#ifndef NDEBUG
1035 assertValidValueDim(value, this->dim, cstr.options);
1036#endif // NDEBUG
1037 cstr.addBound(BoundType::UB, cstr.getPos(value, this->dim), expr);
1038}
1039
1043
1047
1049#ifndef NDEBUG
1050 assertValidValueDim(value, this->dim, cstr.options);
1051#endif // NDEBUG
1052 cstr.addBound(BoundType::LB, cstr.getPos(value, this->dim), expr);
1053}
1054
1056#ifndef NDEBUG
1057 assertValidValueDim(value, this->dim, cstr.options);
1058#endif // NDEBUG
1059 cstr.addBound(BoundType::EQ, cstr.getPos(value, this->dim), expr);
1060}
1061
1065
1069
1073
1077
1081
1085
1089
1093
1097
return success()
return MutableOperandRange * this
static bool isIndexLikeType(Type type, ValueBoundsOptions options)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static llvm::ManagedStatic< PassManagerOptions > options
static bool isIndexOrIntegerType(Type type)
static Operation * getOwnerOfValue(Value value)
static void assertValidValueDim(Value value, std::optional< int64_t > dim, ValueBoundsOptions options)
Base type for affine expression.
Definition AffineExpr.h:68
AffineExpr replaceDimsAndSymbols(ArrayRef< AffineExpr > dimReplacements, ArrayRef< AffineExpr > symReplacements) const
This method substitutes any uses of dimensions and symbols (e.g.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
unsigned getNumDims() const
unsigned getNumResults() const
AffineMap replaceDimsAndSymbols(ArrayRef< AffineExpr > dimReplacements, ArrayRef< AffineExpr > symReplacements, unsigned numResultDims, unsigned numResultSyms) const
This method substitutes any uses of dimensions and symbols (e.g.
AffineExpr getResult(unsigned idx) const
AffineMap replace(AffineExpr expr, AffineExpr replacement, unsigned numResultDims, unsigned numResultSyms) const
Sparse replace method.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
A hyperrectangular slice, represented as a list of offsets, sizes and strides.
HyperrectangularSlice(ArrayRef< OpFoldResult > offsets, ArrayRef< OpFoldResult > sizes, ArrayRef< OpFoldResult > strides)
ArrayRef< OpFoldResult > getMixedStrides() const
ArrayRef< OpFoldResult > getMixedSizes() const
ArrayRef< OpFoldResult > getMixedOffsets() const
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class represents a single result from folding an operation.
MLIRContext * getContext() const
This is a value defined by a result of an operation.
Definition Value.h:456
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
Helper class that builds a bound for a shaped value dimension or index-typed value.
BoundBuilder & operator[](int64_t dim)
Specify a dimension, assuming that the underlying value is a shaped value.
A variable that can be added to the constraint set as a "column".
Variable(OpFoldResult ofr)
Construct a variable for an index-typed attribute or SSA value.
static bool compare(const Variable &lhs, ComparisonOperator cmp, const Variable &rhs)
Return "true" if "lhs cmp rhs" was proven to hold.
static FailureOr< bool > areEqual(const Variable &var1, const Variable &var2)
Compute whether the given variables are equal.
static LogicalResult computeBound(AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type, const Variable &var, StopConditionFn stopCondition, ValueBoundsOptions options={})
Compute a bound for the given variable.
DenseMap< ValueDim, int64_t > valueDimToPosition
Reverse mapping of values/shape dimensions to columns.
void processWorklist()
Iteratively process all elements on the worklist until an index-typed value or shaped value meets sto...
bool addConservativeSemiAffineBounds
Should conservative bounds be added for semi-affine expressions.
static bool isProvablyNegative(Value value, ValueBoundsConstraintSet &cstr)
Return "true" if the given value is provably negative.
static bool isProvablyPositive(Value value, ValueBoundsConstraintSet &cstr)
Return "true" if the given value is provably positive.
AffineExpr getExpr(Value value, std::optional< int64_t > dim=std::nullopt)
Return an expression that represents the given index-typed value or shaped value dimension.
static FailureOr< bool > areEquivalentSlices(MLIRContext *ctx, const HyperrectangularSlice &slice1, const HyperrectangularSlice &slice2)
Return "true" if the given slices are guaranteed to be equivalent.
ValueBoundsConstraintSet(MLIRContext *ctx, const StopConditionFn &stopCondition, ValueBoundsOptions options={}, bool addConservativeSemiAffineBounds=false)
void projectOut(int64_t pos)
Project out the given column in the constraint set.
std::function< bool( Value, std::optional< int64_t >, ValueBoundsConstraintSet &cstr)> StopConditionFn
The stop condition when traversing the backward slice of a shaped value/ index-type value.
static FailureOr< int64_t > computeConstantDelta(Value value1, Value value2, std::optional< int64_t > dim1=std::nullopt, std::optional< int64_t > dim2=std::nullopt)
Compute a constant delta between the given two values.
static llvm::FailureOr< bool > strongCompare(const Variable &lhs, ComparisonOperator cmp, const Variable &rhs)
This function is similar to ValueBoundsConstraintSet::compare, except that it returns false if !...
static FailureOr< int64_t > computeConstantBound(presburger::BoundType type, const Variable &var, const StopConditionFn &stopCondition=nullptr, ValueBoundsOptions options={})
Compute a constant bound for the given variable.
void addBound(presburger::BoundType type, int64_t pos, AffineExpr expr)
Bound the given column in the underlying constraint set by the given expression.
StopConditionFn stopCondition
The current stop condition function.
ComparisonOperator
Comparison operator for ValueBoundsConstraintSet::compare.
BoundBuilder bound(Value value)
Add a bound for the given index-typed value or shaped value.
static bool isProvablyNonNegative(Value value, ValueBoundsConstraintSet &cstr)
Return "true" if the given value is provably non-negative.
int64_t getPos(Value value, std::optional< int64_t > dim=std::nullopt) const
Return the column position of the given value/dimension.
int64_t insert(Value value, std::optional< int64_t > dim, bool isSymbol=true, bool addToWorklist=true)
Insert a value/dimension into the constraint set.
bool comparePos(int64_t lhsPos, ComparisonOperator cmp, int64_t rhsPos)
Return "true" if, based on the current state of the constraint system, "lhs cmp rhs" was proven to ho...
ValueBoundsOptions options
Options that control value bound computation.
SmallVector< std::optional< ValueDim >, 4 > positionToValueDim
Mapping of columns to values/shape dimensions.
static bool isProvablyNonPositive(Value value, ValueBoundsConstraintSet &cstr)
Return "true" if the given value is provably non-positive.
LLVM_DUMP_METHOD void dump() const
Debugging only: Dump the constraint set and the column-to-value/dim mapping to llvm::errs.
std::queue< ValueDim > worklist
Worklist of values/shape dimensions that have not been processed yet.
FlatLinearConstraints cstr
Constraint system of equalities and inequalities.
static LogicalResult computeIndependentBound(AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type, const Variable &var, ValueRange independencies, ValueBoundsOptions options={})
Compute a bound in that is independent of all values in independencies.
bool isMapped(Value value, std::optional< int64_t > dim=std::nullopt) const
Return "true" if the given value/dim is mapped (i.e., has a corresponding column in the constraint sy...
llvm::FailureOr< bool > strongComparePos(int64_t lhsPos, ComparisonOperator cmp, int64_t rhsPos)
Return "true" if, based on the current state of the constraint system, "lhs cmp rhs" was proven to ho...
AffineExpr getPosExpr(int64_t pos)
Return an affine expression that represents column pos in the constraint set.
void projectOutAnonymous(std::optional< int64_t > except=std::nullopt)
static FailureOr< bool > areOverlappingSlices(MLIRContext *ctx, const HyperrectangularSlice &slice1, const HyperrectangularSlice &slice2)
Return "true" if the given slices are guaranteed to be overlapping.
std::pair< Value, int64_t > ValueDim
An index-typed value or the dimension of a shaped-type value.
void populateConstraints(Value value, std::optional< int64_t > dim)
Traverse the IR starting from the given value/dim and populate constraints as long as the stop condit...
Builder builder
Builder for constructing affine expressions.
bool populateAndCompare(const Variable &lhs, ComparisonOperator cmp, const Variable &rhs)
Populate constraints for lhs/rhs (until the stop condition is met).
static constexpr int64_t kIndexValue
Dimension identifier to indicate a value is index-typed.
static LogicalResult computeDependentBound(AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type, const Variable &var, ValueDimList dependencies, ValueBoundsOptions options={})
Compute a bound in terms of the values/dimensions in dependencies.
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Definition Value.h:108
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
BoundType
The type of bound: equal, lower bound or upper bound.
VarKind
Kind of variable.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
Definition Matchers.h:527
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
bool operator==(StringAttr lhs, std::nullptr_t)
Define comparisons for StringAttr against nullptr and itself to avoid the StringRef overloads from be...
SmallVector< std::pair< Value, std::optional< int64_t > >, 2 > ValueDimList
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
AffineMap foldAttributesIntoMap(Builder &b, AffineMap map, ArrayRef< OpFoldResult > operands, SmallVector< Value > &remainingValues)
Fold all attributes among the given operands into the affine map.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
Options that control value bound computation.