1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
|
//===- Var.cpp ------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Var.h"
#include "DimLvlMap.h"
using namespace mlir;
using namespace mlir::sparse_tensor;
using namespace mlir::sparse_tensor::ir_detail;
//===----------------------------------------------------------------------===//
// `Var` implementation.
//===----------------------------------------------------------------------===//
void Var::print(AsmPrinter &printer) const { print(printer.getStream()); }
void Var::print(llvm::raw_ostream &os) const {
os << toChar(getKind()) << getNum();
}
void Var::dump() const {
print(llvm::errs());
llvm::errs() << "\n";
}
//===----------------------------------------------------------------------===//
// `Ranks` implementation.
//===----------------------------------------------------------------------===//
bool Ranks::isValid(DimLvlExpr expr) const {
// FIXME(wrengr): we have cases without affine expr at an early point
if (!expr.getAffineExpr())
return true;
// Each `DimLvlExpr` only allows one kind of non-symbol variable.
int64_t maxSym = -1, maxVar = -1;
// TODO(wrengr): If we run into ASan issues, that may be due to the
// "`{{...}}`" syntax; so we may want to try using local-variables instead.
mlir::getMaxDimAndSymbol<ArrayRef<AffineExpr>>({{expr.getAffineExpr()}},
maxVar, maxSym);
// TODO(wrengr): We may want to add a call to `LLVM_DEBUG` like
// `willBeValidAffineMap` does. And/or should return `InFlightDiagnostic`
// instead of bool.
return maxSym < getSymRank() && maxVar < getRank(expr.getAllowedVarKind());
}
//===----------------------------------------------------------------------===//
// `VarSet` implementation.
//===----------------------------------------------------------------------===//
static constexpr const VarKind everyVarKind[] = {
VarKind::Dimension, VarKind::Symbol, VarKind::Level};
VarSet::VarSet(Ranks const &ranks) {
for (const auto vk : everyVarKind)
impl[vk].reserve(ranks.getRank(vk));
}
bool VarSet::contains(Var var) const {
// NOTE: We make sure to return false on OOB, for consistency with
// the `anyCommon` implementation of `VarSet::occursIn(VarSet)`.
// However beware that, as always with silencing OOB, this can hide
// bugs in client code.
const llvm::SmallBitVector &bits = impl[var.getKind()];
const auto num = var.getNum();
// FIXME(wrengr): If we `assert(num < bits.size())` then
// "roundtrip_encoding.mlir" will fail. So we need to figure out
// where exactly the OOB `var` is coming from, to determine whether
// that's a logic bug or not.
return num < bits.size() && bits[num];
}
bool VarSet::occursIn(VarSet const &other) const {
for (const auto vk : everyVarKind)
if (impl[vk].anyCommon(other.impl[vk]))
return true;
return false;
}
bool VarSet::occursIn(DimLvlExpr expr) const {
if (!expr)
return false;
switch (expr.getAffineKind()) {
case AffineExprKind::Constant:
return false;
case AffineExprKind::SymbolId:
return contains(expr.castSymVar());
case AffineExprKind::DimId:
return contains(expr.castDimLvlVar());
case AffineExprKind::Add:
case AffineExprKind::Mul:
case AffineExprKind::Mod:
case AffineExprKind::FloorDiv:
case AffineExprKind::CeilDiv: {
const auto [lhs, op, rhs] = expr.unpackBinop();
(void)op;
return occursIn(lhs) || occursIn(rhs);
}
}
llvm_unreachable("unknown AffineExprKind");
}
void VarSet::add(Var var) {
// NOTE: `SmallBitVactor::operator[]` will raise assertion errors for OOB.
impl[var.getKind()][var.getNum()] = true;
}
void VarSet::add(VarSet const &other) {
// NOTE: `SmallBitVector::operator&=` will implicitly resize
// the bitvector (unlike `BitVector::operator&=`), so we add an
// assertion against OOB for consistency with the implementation
// of `VarSet::add(Var)`.
for (const auto vk : everyVarKind) {
assert(impl[vk].size() >= other.impl[vk].size());
impl[vk] &= other.impl[vk];
}
}
void VarSet::add(DimLvlExpr expr) {
if (!expr)
return;
switch (expr.getAffineKind()) {
case AffineExprKind::Constant:
return;
case AffineExprKind::SymbolId:
add(expr.castSymVar());
return;
case AffineExprKind::DimId:
add(expr.castDimLvlVar());
return;
case AffineExprKind::Add:
case AffineExprKind::Mul:
case AffineExprKind::Mod:
case AffineExprKind::FloorDiv:
case AffineExprKind::CeilDiv: {
const auto [lhs, op, rhs] = expr.unpackBinop();
(void)op;
add(lhs);
add(rhs);
return;
}
}
llvm_unreachable("unknown AffineExprKind");
}
//===----------------------------------------------------------------------===//
// `VarInfo` implementation.
//===----------------------------------------------------------------------===//
void VarInfo::setNum(Var::Num n) {
assert(!hasNum() && "Var::Num is already set");
assert(Var::isWF_Num(n) && "Var::Num is too large");
num = n;
}
//===----------------------------------------------------------------------===//
// `VarEnv` implementation.
//===----------------------------------------------------------------------===//
/// Helper function for `assertUsageConsistency` to better handle SMLoc
/// mismatches.
// TODO(wrengr): If we switch to the `LocatedVar` design, then there's
// no need for anything like `minSMLoc` since `assertUsageConsistency`
// won't need to do anything about locations.
LLVM_ATTRIBUTE_UNUSED static llvm::SMLoc
minSMLoc(AsmParser &parser, llvm::SMLoc sm1, llvm::SMLoc sm2) {
const auto loc1 = parser.getEncodedSourceLoc(sm1).dyn_cast<FileLineColLoc>();
assert(loc1 && "Could not get `FileLineColLoc` for first `SMLoc`");
const auto loc2 = parser.getEncodedSourceLoc(sm2).dyn_cast<FileLineColLoc>();
assert(loc2 && "Could not get `FileLineColLoc` for second `SMLoc`");
if (loc1.getFilename() != loc2.getFilename())
return SMLoc();
const auto pair1 = std::make_pair(loc1.getLine(), loc1.getColumn());
const auto pair2 = std::make_pair(loc2.getLine(), loc2.getColumn());
return pair1 <= pair2 ? sm1 : sm2;
}
LLVM_ATTRIBUTE_UNUSED static void
assertInternalConsistency(VarEnv const &env, VarInfo::ID id, StringRef name) {
#ifndef NDEBUG
const auto &var = env.access(id);
assert(var.getName() == name && "found inconsistent name");
assert(var.getID() == id && "found inconsistent VarInfo::ID");
#endif // NDEBUG
}
// NOTE(wrengr): if we can actually obtain an `AsmParser` for `minSMLoc`
// (or find some other way to convert SMLoc to FileLineColLoc), then this
// would no longer be `const VarEnv` (and couldn't be a free-function either).
LLVM_ATTRIBUTE_UNUSED static void assertUsageConsistency(VarEnv const &env,
VarInfo::ID id,
llvm::SMLoc loc,
VarKind vk) {
#ifndef NDEBUG
const auto &var = env.access(id);
assert(var.getKind() == vk &&
"a variable of that name already exists with a different VarKind");
// Since the same variable can occur at several locations,
// it would not be appropriate to do `assert(var.getLoc() == loc)`.
/* TODO(wrengr):
const auto minLoc = minSMLoc(_, var.getLoc(), loc);
assert(minLoc && "Location mismatch/incompatibility");
var.loc = minLoc;
// */
#endif // NDEBUG
}
std::optional<VarInfo::ID> VarEnv::lookup(StringRef name) const {
// NOTE: `StringMap::lookup` will return a default-constructed value if
// the key isn't found; which for enums means zero, and therefore makes
// it impossible to distinguish between actual zero-VarInfo::ID vs not-found.
// Whereas `StringMap::at` asserts that the key is found, which we don't
// want either.
const auto iter = ids.find(name);
if (iter == ids.end())
return std::nullopt;
const auto id = iter->second;
#ifndef NDEBUG
assertInternalConsistency(*this, id, name);
#endif // NDEBUG
return id;
}
std::pair<VarInfo::ID, bool> VarEnv::create(StringRef name, llvm::SMLoc loc,
VarKind vk, bool verifyUsage) {
const auto &[iter, didInsert] = ids.try_emplace(name, nextID());
const auto id = iter->second;
if (didInsert) {
vars.emplace_back(id, name, loc, vk);
} else {
#ifndef NDEBUG
assertInternalConsistency(*this, id, name);
if (verifyUsage)
assertUsageConsistency(*this, id, loc, vk);
#endif // NDEBUG
}
return std::make_pair(id, didInsert);
}
std::optional<std::pair<VarInfo::ID, bool>>
VarEnv::lookupOrCreate(Policy creationPolicy, StringRef name, llvm::SMLoc loc,
VarKind vk) {
switch (creationPolicy) {
case Policy::MustNot: {
const auto oid = lookup(name);
if (!oid)
return std::nullopt; // Doesn't exist, but must not create.
#ifndef NDEBUG
assertUsageConsistency(*this, *oid, loc, vk);
#endif // NDEBUG
return std::make_pair(*oid, false);
}
case Policy::May:
return create(name, loc, vk, /*verifyUsage=*/true);
case Policy::Must: {
const auto res = create(name, loc, vk, /*verifyUsage=*/false);
// const auto id = res.first;
const auto didCreate = res.second;
if (!didCreate)
return std::nullopt; // Already exists, but must create.
return res;
}
}
llvm_unreachable("unknown Policy");
}
Var VarEnv::bindUnusedVar(VarKind vk) { return Var(vk, nextNum[vk]++); }
Var VarEnv::bindVar(VarInfo::ID id) {
auto &info = access(id);
const auto var = bindUnusedVar(info.getKind());
// NOTE: `setNum` already checks wellformedness of the `Var::Num`.
info.setNum(var.getNum());
return var;
}
// TODO(wrengr): Alternatively there's `mlir::emitError(Location, Twine const&)`
// which is what `Operation::emitError` uses; though I'm not sure if
// that's appropriate to use here... But if it is, then that means
// we can have `VarInfo` store `Location` rather than `SMLoc`, which
// means we can use `FusedLoc` to handle the combination issue in
// `VarEnv::lookupOrCreate`.
//
// TODO(wrengr): is there any way to combine multiple IFDs, so that
// we can report all unbound variables instead of just the first one
// encountered?
//
InFlightDiagnostic VarEnv::emitErrorIfAnyUnbound(AsmParser &parser) const {
for (const auto &var : vars)
if (!var.hasNum())
return parser.emitError(var.getLoc(),
"Unbound variable: " + var.getName());
return {};
}
//===----------------------------------------------------------------------===//
|