1 //===- AffineExpr.cpp - MLIR Affine Expr Classes --------------------------===// 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 #include "mlir/IR/AffineExpr.h" 10 #include "AffineExprDetail.h" 11 #include "mlir/IR/AffineExprVisitor.h" 12 #include "mlir/IR/AffineMap.h" 13 #include "mlir/IR/IntegerSet.h" 14 #include "mlir/Support/MathExtras.h" 15 #include "llvm/ADT/STLExtras.h" 16 17 using namespace mlir; 18 using namespace mlir::detail; 19 20 MLIRContext *AffineExpr::getContext() const { return expr->context; } 21 22 AffineExprKind AffineExpr::getKind() const { 23 return static_cast<AffineExprKind>(expr->getKind()); 24 } 25 26 /// Walk all of the AffineExprs in this subgraph in postorder. 27 void AffineExpr::walk(std::function<void(AffineExpr)> callback) const { 28 struct AffineExprWalker : public AffineExprVisitor<AffineExprWalker> { 29 std::function<void(AffineExpr)> callback; 30 31 AffineExprWalker(std::function<void(AffineExpr)> callback) 32 : callback(callback) {} 33 34 void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) { callback(expr); } 35 void visitConstantExpr(AffineConstantExpr expr) { callback(expr); } 36 void visitDimExpr(AffineDimExpr expr) { callback(expr); } 37 void visitSymbolExpr(AffineSymbolExpr expr) { callback(expr); } 38 }; 39 40 AffineExprWalker(callback).walkPostOrder(*this); 41 } 42 43 // Dispatch affine expression construction based on kind. 44 AffineExpr mlir::getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs, 45 AffineExpr rhs) { 46 if (kind == AffineExprKind::Add) 47 return lhs + rhs; 48 if (kind == AffineExprKind::Mul) 49 return lhs * rhs; 50 if (kind == AffineExprKind::FloorDiv) 51 return lhs.floorDiv(rhs); 52 if (kind == AffineExprKind::CeilDiv) 53 return lhs.ceilDiv(rhs); 54 if (kind == AffineExprKind::Mod) 55 return lhs % rhs; 56 57 llvm_unreachable("unknown binary operation on affine expressions"); 58 } 59 60 /// This method substitutes any uses of dimensions and symbols (e.g. 61 /// dim#0 with dimReplacements[0]) and returns the modified expression tree. 62 AffineExpr 63 AffineExpr::replaceDimsAndSymbols(ArrayRef<AffineExpr> dimReplacements, 64 ArrayRef<AffineExpr> symReplacements) const { 65 switch (getKind()) { 66 case AffineExprKind::Constant: 67 return *this; 68 case AffineExprKind::DimId: { 69 unsigned dimId = cast<AffineDimExpr>().getPosition(); 70 if (dimId >= dimReplacements.size()) 71 return *this; 72 return dimReplacements[dimId]; 73 } 74 case AffineExprKind::SymbolId: { 75 unsigned symId = cast<AffineSymbolExpr>().getPosition(); 76 if (symId >= symReplacements.size()) 77 return *this; 78 return symReplacements[symId]; 79 } 80 case AffineExprKind::Add: 81 case AffineExprKind::Mul: 82 case AffineExprKind::FloorDiv: 83 case AffineExprKind::CeilDiv: 84 case AffineExprKind::Mod: 85 auto binOp = cast<AffineBinaryOpExpr>(); 86 auto lhs = binOp.getLHS(), rhs = binOp.getRHS(); 87 auto newLHS = lhs.replaceDimsAndSymbols(dimReplacements, symReplacements); 88 auto newRHS = rhs.replaceDimsAndSymbols(dimReplacements, symReplacements); 89 if (newLHS == lhs && newRHS == rhs) 90 return *this; 91 return getAffineBinaryOpExpr(getKind(), newLHS, newRHS); 92 } 93 llvm_unreachable("Unknown AffineExpr"); 94 } 95 96 /// Returns true if this expression is made out of only symbols and 97 /// constants (no dimensional identifiers). 98 bool AffineExpr::isSymbolicOrConstant() const { 99 switch (getKind()) { 100 case AffineExprKind::Constant: 101 return true; 102 case AffineExprKind::DimId: 103 return false; 104 case AffineExprKind::SymbolId: 105 return true; 106 107 case AffineExprKind::Add: 108 case AffineExprKind::Mul: 109 case AffineExprKind::FloorDiv: 110 case AffineExprKind::CeilDiv: 111 case AffineExprKind::Mod: { 112 auto expr = this->cast<AffineBinaryOpExpr>(); 113 return expr.getLHS().isSymbolicOrConstant() && 114 expr.getRHS().isSymbolicOrConstant(); 115 } 116 } 117 llvm_unreachable("Unknown AffineExpr"); 118 } 119 120 /// Returns true if this is a pure affine expression, i.e., multiplication, 121 /// floordiv, ceildiv, and mod is only allowed w.r.t constants. 122 bool AffineExpr::isPureAffine() const { 123 switch (getKind()) { 124 case AffineExprKind::SymbolId: 125 case AffineExprKind::DimId: 126 case AffineExprKind::Constant: 127 return true; 128 case AffineExprKind::Add: { 129 auto op = cast<AffineBinaryOpExpr>(); 130 return op.getLHS().isPureAffine() && op.getRHS().isPureAffine(); 131 } 132 133 case AffineExprKind::Mul: { 134 // TODO: Canonicalize the constants in binary operators to the RHS when 135 // possible, allowing this to merge into the next case. 136 auto op = cast<AffineBinaryOpExpr>(); 137 return op.getLHS().isPureAffine() && op.getRHS().isPureAffine() && 138 (op.getLHS().template isa<AffineConstantExpr>() || 139 op.getRHS().template isa<AffineConstantExpr>()); 140 } 141 case AffineExprKind::FloorDiv: 142 case AffineExprKind::CeilDiv: 143 case AffineExprKind::Mod: { 144 auto op = cast<AffineBinaryOpExpr>(); 145 return op.getLHS().isPureAffine() && 146 op.getRHS().template isa<AffineConstantExpr>(); 147 } 148 } 149 llvm_unreachable("Unknown AffineExpr"); 150 } 151 152 // Returns the greatest known integral divisor of this affine expression. 153 int64_t AffineExpr::getLargestKnownDivisor() const { 154 AffineBinaryOpExpr binExpr(nullptr); 155 switch (getKind()) { 156 case AffineExprKind::SymbolId: 157 LLVM_FALLTHROUGH; 158 case AffineExprKind::DimId: 159 return 1; 160 case AffineExprKind::Constant: 161 return std::abs(this->cast<AffineConstantExpr>().getValue()); 162 case AffineExprKind::Mul: { 163 binExpr = this->cast<AffineBinaryOpExpr>(); 164 return binExpr.getLHS().getLargestKnownDivisor() * 165 binExpr.getRHS().getLargestKnownDivisor(); 166 } 167 case AffineExprKind::Add: 168 LLVM_FALLTHROUGH; 169 case AffineExprKind::FloorDiv: 170 case AffineExprKind::CeilDiv: 171 case AffineExprKind::Mod: { 172 binExpr = cast<AffineBinaryOpExpr>(); 173 return llvm::GreatestCommonDivisor64( 174 binExpr.getLHS().getLargestKnownDivisor(), 175 binExpr.getRHS().getLargestKnownDivisor()); 176 } 177 } 178 llvm_unreachable("Unknown AffineExpr"); 179 } 180 181 bool AffineExpr::isMultipleOf(int64_t factor) const { 182 AffineBinaryOpExpr binExpr(nullptr); 183 uint64_t l, u; 184 switch (getKind()) { 185 case AffineExprKind::SymbolId: 186 LLVM_FALLTHROUGH; 187 case AffineExprKind::DimId: 188 return factor * factor == 1; 189 case AffineExprKind::Constant: 190 return cast<AffineConstantExpr>().getValue() % factor == 0; 191 case AffineExprKind::Mul: { 192 binExpr = cast<AffineBinaryOpExpr>(); 193 // It's probably not worth optimizing this further (to not traverse the 194 // whole sub-tree under - it that would require a version of isMultipleOf 195 // that on a 'false' return also returns the largest known divisor). 196 return (l = binExpr.getLHS().getLargestKnownDivisor()) % factor == 0 || 197 (u = binExpr.getRHS().getLargestKnownDivisor()) % factor == 0 || 198 (l * u) % factor == 0; 199 } 200 case AffineExprKind::Add: 201 case AffineExprKind::FloorDiv: 202 case AffineExprKind::CeilDiv: 203 case AffineExprKind::Mod: { 204 binExpr = cast<AffineBinaryOpExpr>(); 205 return llvm::GreatestCommonDivisor64( 206 binExpr.getLHS().getLargestKnownDivisor(), 207 binExpr.getRHS().getLargestKnownDivisor()) % 208 factor == 209 0; 210 } 211 } 212 llvm_unreachable("Unknown AffineExpr"); 213 } 214 215 bool AffineExpr::isFunctionOfDim(unsigned position) const { 216 if (getKind() == AffineExprKind::DimId) { 217 return *this == mlir::getAffineDimExpr(position, getContext()); 218 } 219 if (auto expr = this->dyn_cast<AffineBinaryOpExpr>()) { 220 return expr.getLHS().isFunctionOfDim(position) || 221 expr.getRHS().isFunctionOfDim(position); 222 } 223 return false; 224 } 225 226 AffineBinaryOpExpr::AffineBinaryOpExpr(AffineExpr::ImplType *ptr) 227 : AffineExpr(ptr) {} 228 AffineExpr AffineBinaryOpExpr::getLHS() const { 229 return static_cast<ImplType *>(expr)->lhs; 230 } 231 AffineExpr AffineBinaryOpExpr::getRHS() const { 232 return static_cast<ImplType *>(expr)->rhs; 233 } 234 235 AffineDimExpr::AffineDimExpr(AffineExpr::ImplType *ptr) : AffineExpr(ptr) {} 236 unsigned AffineDimExpr::getPosition() const { 237 return static_cast<ImplType *>(expr)->position; 238 } 239 240 static AffineExpr getAffineDimOrSymbol(AffineExprKind kind, unsigned position, 241 MLIRContext *context) { 242 auto assignCtx = [context](AffineDimExprStorage *storage) { 243 storage->context = context; 244 }; 245 246 StorageUniquer &uniquer = context->getAffineUniquer(); 247 return uniquer.get<AffineDimExprStorage>( 248 assignCtx, static_cast<unsigned>(kind), position); 249 } 250 251 AffineExpr mlir::getAffineDimExpr(unsigned position, MLIRContext *context) { 252 return getAffineDimOrSymbol(AffineExprKind::DimId, position, context); 253 } 254 255 AffineSymbolExpr::AffineSymbolExpr(AffineExpr::ImplType *ptr) 256 : AffineExpr(ptr) {} 257 unsigned AffineSymbolExpr::getPosition() const { 258 return static_cast<ImplType *>(expr)->position; 259 } 260 261 AffineExpr mlir::getAffineSymbolExpr(unsigned position, MLIRContext *context) { 262 return getAffineDimOrSymbol(AffineExprKind::SymbolId, position, context); 263 ; 264 } 265 266 AffineConstantExpr::AffineConstantExpr(AffineExpr::ImplType *ptr) 267 : AffineExpr(ptr) {} 268 int64_t AffineConstantExpr::getValue() const { 269 return static_cast<ImplType *>(expr)->constant; 270 } 271 272 bool AffineExpr::operator==(int64_t v) const { 273 return *this == getAffineConstantExpr(v, getContext()); 274 } 275 276 AffineExpr mlir::getAffineConstantExpr(int64_t constant, MLIRContext *context) { 277 auto assignCtx = [context](AffineConstantExprStorage *storage) { 278 storage->context = context; 279 }; 280 281 StorageUniquer &uniquer = context->getAffineUniquer(); 282 return uniquer.get<AffineConstantExprStorage>( 283 assignCtx, static_cast<unsigned>(AffineExprKind::Constant), constant); 284 } 285 286 /// Simplify add expression. Return nullptr if it can't be simplified. 287 static AffineExpr simplifyAdd(AffineExpr lhs, AffineExpr rhs) { 288 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 289 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 290 // Fold if both LHS, RHS are a constant. 291 if (lhsConst && rhsConst) 292 return getAffineConstantExpr(lhsConst.getValue() + rhsConst.getValue(), 293 lhs.getContext()); 294 295 // Canonicalize so that only the RHS is a constant. (4 + d0 becomes d0 + 4). 296 // If only one of them is a symbolic expressions, make it the RHS. 297 if (lhs.isa<AffineConstantExpr>() || 298 (lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant())) { 299 return rhs + lhs; 300 } 301 302 // At this point, if there was a constant, it would be on the right. 303 304 // Addition with a zero is a noop, return the other input. 305 if (rhsConst) { 306 if (rhsConst.getValue() == 0) 307 return lhs; 308 } 309 // Fold successive additions like (d0 + 2) + 3 into d0 + 5. 310 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 311 if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Add) { 312 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) 313 return lBin.getLHS() + (lrhs.getValue() + rhsConst.getValue()); 314 } 315 316 // Detect "c1 * expr + c_2 * expr" as "(c1 + c2) * expr". 317 // c1 is rRhsConst, c2 is rLhsConst; firstExpr, secondExpr are their 318 // respective multiplicands. 319 Optional<int64_t> rLhsConst, rRhsConst; 320 AffineExpr firstExpr, secondExpr; 321 AffineConstantExpr rLhsConstExpr; 322 auto lBinOpExpr = lhs.dyn_cast<AffineBinaryOpExpr>(); 323 if (lBinOpExpr && lBinOpExpr.getKind() == AffineExprKind::Mul && 324 (rLhsConstExpr = lBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) { 325 rLhsConst = rLhsConstExpr.getValue(); 326 firstExpr = lBinOpExpr.getLHS(); 327 } else { 328 rLhsConst = 1; 329 firstExpr = lhs; 330 } 331 332 auto rBinOpExpr = rhs.dyn_cast<AffineBinaryOpExpr>(); 333 AffineConstantExpr rRhsConstExpr; 334 if (rBinOpExpr && rBinOpExpr.getKind() == AffineExprKind::Mul && 335 (rRhsConstExpr = rBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) { 336 rRhsConst = rRhsConstExpr.getValue(); 337 secondExpr = rBinOpExpr.getLHS(); 338 } else { 339 rRhsConst = 1; 340 secondExpr = rhs; 341 } 342 343 if (rLhsConst && rRhsConst && firstExpr == secondExpr) 344 return getAffineBinaryOpExpr( 345 AffineExprKind::Mul, firstExpr, 346 getAffineConstantExpr(rLhsConst.getValue() + rRhsConst.getValue(), 347 lhs.getContext())); 348 349 // When doing successive additions, bring constant to the right: turn (d0 + 2) 350 // + d1 into (d0 + d1) + 2. 351 if (lBin && lBin.getKind() == AffineExprKind::Add) { 352 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 353 return lBin.getLHS() + rhs + lrhs; 354 } 355 } 356 357 // Detect and transform "expr - c * (expr floordiv c)" to "expr mod c". This 358 // leads to a much more efficient form when 'c' is a power of two, and in 359 // general a more compact and readable form. 360 361 // Process '(expr floordiv c) * (-c)'. 362 if (!rBinOpExpr) 363 return nullptr; 364 365 auto lrhs = rBinOpExpr.getLHS(); 366 auto rrhs = rBinOpExpr.getRHS(); 367 368 // Process lrhs, which is 'expr floordiv c'. 369 AffineBinaryOpExpr lrBinOpExpr = lrhs.dyn_cast<AffineBinaryOpExpr>(); 370 if (!lrBinOpExpr || lrBinOpExpr.getKind() != AffineExprKind::FloorDiv) 371 return nullptr; 372 373 auto llrhs = lrBinOpExpr.getLHS(); 374 auto rlrhs = lrBinOpExpr.getRHS(); 375 376 if (lhs == llrhs && rlrhs == -rrhs) { 377 return lhs % rlrhs; 378 } 379 return nullptr; 380 } 381 382 AffineExpr AffineExpr::operator+(int64_t v) const { 383 return *this + getAffineConstantExpr(v, getContext()); 384 } 385 AffineExpr AffineExpr::operator+(AffineExpr other) const { 386 if (auto simplified = simplifyAdd(*this, other)) 387 return simplified; 388 389 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 390 return uniquer.get<AffineBinaryOpExprStorage>( 391 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Add), *this, other); 392 } 393 394 /// Simplify a multiply expression. Return nullptr if it can't be simplified. 395 static AffineExpr simplifyMul(AffineExpr lhs, AffineExpr rhs) { 396 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 397 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 398 399 if (lhsConst && rhsConst) 400 return getAffineConstantExpr(lhsConst.getValue() * rhsConst.getValue(), 401 lhs.getContext()); 402 403 assert(lhs.isSymbolicOrConstant() || rhs.isSymbolicOrConstant()); 404 405 // Canonicalize the mul expression so that the constant/symbolic term is the 406 // RHS. If both the lhs and rhs are symbolic, swap them if the lhs is a 407 // constant. (Note that a constant is trivially symbolic). 408 if (!rhs.isSymbolicOrConstant() || lhs.isa<AffineConstantExpr>()) { 409 // At least one of them has to be symbolic. 410 return rhs * lhs; 411 } 412 413 // At this point, if there was a constant, it would be on the right. 414 415 // Multiplication with a one is a noop, return the other input. 416 if (rhsConst) { 417 if (rhsConst.getValue() == 1) 418 return lhs; 419 // Multiplication with zero. 420 if (rhsConst.getValue() == 0) 421 return rhsConst; 422 } 423 424 // Fold successive multiplications: eg: (d0 * 2) * 3 into d0 * 6. 425 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 426 if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Mul) { 427 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) 428 return lBin.getLHS() * (lrhs.getValue() * rhsConst.getValue()); 429 } 430 431 // When doing successive multiplication, bring constant to the right: turn (d0 432 // * 2) * d1 into (d0 * d1) * 2. 433 if (lBin && lBin.getKind() == AffineExprKind::Mul) { 434 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 435 return (lBin.getLHS() * rhs) * lrhs; 436 } 437 } 438 439 return nullptr; 440 } 441 442 AffineExpr AffineExpr::operator*(int64_t v) const { 443 return *this * getAffineConstantExpr(v, getContext()); 444 } 445 AffineExpr AffineExpr::operator*(AffineExpr other) const { 446 if (auto simplified = simplifyMul(*this, other)) 447 return simplified; 448 449 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 450 return uniquer.get<AffineBinaryOpExprStorage>( 451 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mul), *this, other); 452 } 453 454 // Unary minus, delegate to operator*. 455 AffineExpr AffineExpr::operator-() const { 456 return *this * getAffineConstantExpr(-1, getContext()); 457 } 458 459 // Delegate to operator+. 460 AffineExpr AffineExpr::operator-(int64_t v) const { return *this + (-v); } 461 AffineExpr AffineExpr::operator-(AffineExpr other) const { 462 return *this + (-other); 463 } 464 465 static AffineExpr simplifyFloorDiv(AffineExpr lhs, AffineExpr rhs) { 466 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 467 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 468 469 // mlir floordiv by zero or negative numbers is undefined and preserved as is. 470 if (!rhsConst || rhsConst.getValue() < 1) 471 return nullptr; 472 473 if (lhsConst) 474 return getAffineConstantExpr( 475 floorDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext()); 476 477 // Fold floordiv of a multiply with a constant that is a multiple of the 478 // divisor. Eg: (i * 128) floordiv 64 = i * 2. 479 if (rhsConst == 1) 480 return lhs; 481 482 // Simplify (expr * const) floordiv divConst when expr is known to be a 483 // multiple of divConst. 484 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 485 if (lBin && lBin.getKind() == AffineExprKind::Mul) { 486 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 487 // rhsConst is known to be a positive constant. 488 if (lrhs.getValue() % rhsConst.getValue() == 0) 489 return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue()); 490 } 491 } 492 493 // Simplify (expr1 + expr2) floordiv divConst when either expr1 or expr2 is 494 // known to be a multiple of divConst. 495 if (lBin && lBin.getKind() == AffineExprKind::Add) { 496 int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor(); 497 int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor(); 498 // rhsConst is known to be a positive constant. 499 if (llhsDiv % rhsConst.getValue() == 0 || 500 lrhsDiv % rhsConst.getValue() == 0) 501 return lBin.getLHS().floorDiv(rhsConst.getValue()) + 502 lBin.getRHS().floorDiv(rhsConst.getValue()); 503 } 504 505 return nullptr; 506 } 507 508 AffineExpr AffineExpr::floorDiv(uint64_t v) const { 509 return floorDiv(getAffineConstantExpr(v, getContext())); 510 } 511 AffineExpr AffineExpr::floorDiv(AffineExpr other) const { 512 if (auto simplified = simplifyFloorDiv(*this, other)) 513 return simplified; 514 515 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 516 return uniquer.get<AffineBinaryOpExprStorage>( 517 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::FloorDiv), *this, 518 other); 519 } 520 521 static AffineExpr simplifyCeilDiv(AffineExpr lhs, AffineExpr rhs) { 522 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 523 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 524 525 if (!rhsConst || rhsConst.getValue() < 1) 526 return nullptr; 527 528 if (lhsConst) 529 return getAffineConstantExpr( 530 ceilDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext()); 531 532 // Fold ceildiv of a multiply with a constant that is a multiple of the 533 // divisor. Eg: (i * 128) ceildiv 64 = i * 2. 534 if (rhsConst.getValue() == 1) 535 return lhs; 536 537 // Simplify (expr * const) ceildiv divConst when const is known to be a 538 // multiple of divConst. 539 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 540 if (lBin && lBin.getKind() == AffineExprKind::Mul) { 541 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 542 // rhsConst is known to be a positive constant. 543 if (lrhs.getValue() % rhsConst.getValue() == 0) 544 return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue()); 545 } 546 } 547 548 return nullptr; 549 } 550 551 AffineExpr AffineExpr::ceilDiv(uint64_t v) const { 552 return ceilDiv(getAffineConstantExpr(v, getContext())); 553 } 554 AffineExpr AffineExpr::ceilDiv(AffineExpr other) const { 555 if (auto simplified = simplifyCeilDiv(*this, other)) 556 return simplified; 557 558 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 559 return uniquer.get<AffineBinaryOpExprStorage>( 560 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::CeilDiv), *this, 561 other); 562 } 563 564 static AffineExpr simplifyMod(AffineExpr lhs, AffineExpr rhs) { 565 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 566 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 567 568 // mod w.r.t zero or negative numbers is undefined and preserved as is. 569 if (!rhsConst || rhsConst.getValue() < 1) 570 return nullptr; 571 572 if (lhsConst) 573 return getAffineConstantExpr(mod(lhsConst.getValue(), rhsConst.getValue()), 574 lhs.getContext()); 575 576 // Fold modulo of an expression that is known to be a multiple of a constant 577 // to zero if that constant is a multiple of the modulo factor. Eg: (i * 128) 578 // mod 64 is folded to 0, and less trivially, (i*(j*4*(k*32))) mod 128 = 0. 579 if (lhs.getLargestKnownDivisor() % rhsConst.getValue() == 0) 580 return getAffineConstantExpr(0, lhs.getContext()); 581 582 // Simplify (expr1 + expr2) mod divConst when either expr1 or expr2 is 583 // known to be a multiple of divConst. 584 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 585 if (lBin && lBin.getKind() == AffineExprKind::Add) { 586 int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor(); 587 int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor(); 588 // rhsConst is known to be a positive constant. 589 if (llhsDiv % rhsConst.getValue() == 0) 590 return lBin.getRHS() % rhsConst.getValue(); 591 if (lrhsDiv % rhsConst.getValue() == 0) 592 return lBin.getLHS() % rhsConst.getValue(); 593 } 594 595 return nullptr; 596 } 597 598 AffineExpr AffineExpr::operator%(uint64_t v) const { 599 return *this % getAffineConstantExpr(v, getContext()); 600 } 601 AffineExpr AffineExpr::operator%(AffineExpr other) const { 602 if (auto simplified = simplifyMod(*this, other)) 603 return simplified; 604 605 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 606 return uniquer.get<AffineBinaryOpExprStorage>( 607 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mod), *this, other); 608 } 609 610 AffineExpr AffineExpr::compose(AffineMap map) const { 611 SmallVector<AffineExpr, 8> dimReplacements(map.getResults().begin(), 612 map.getResults().end()); 613 return replaceDimsAndSymbols(dimReplacements, {}); 614 } 615 raw_ostream &mlir::operator<<(raw_ostream &os, AffineExpr expr) { 616 expr.print(os); 617 return os; 618 } 619 620 /// Constructs an affine expression from a flat ArrayRef. If there are local 621 /// identifiers (neither dimensional nor symbolic) that appear in the sum of 622 /// products expression, `localExprs` is expected to have the AffineExpr 623 /// for it, and is substituted into. The ArrayRef `flatExprs` is expected to be 624 /// in the format [dims, symbols, locals, constant term]. 625 AffineExpr mlir::getAffineExprFromFlatForm(ArrayRef<int64_t> flatExprs, 626 unsigned numDims, 627 unsigned numSymbols, 628 ArrayRef<AffineExpr> localExprs, 629 MLIRContext *context) { 630 // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1. 631 assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() && 632 "unexpected number of local expressions"); 633 634 auto expr = getAffineConstantExpr(0, context); 635 // Dimensions and symbols. 636 for (unsigned j = 0; j < numDims + numSymbols; j++) { 637 if (flatExprs[j] == 0) 638 continue; 639 auto id = j < numDims ? getAffineDimExpr(j, context) 640 : getAffineSymbolExpr(j - numDims, context); 641 expr = expr + id * flatExprs[j]; 642 } 643 644 // Local identifiers. 645 for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e; 646 j++) { 647 if (flatExprs[j] == 0) 648 continue; 649 auto term = localExprs[j - numDims - numSymbols] * flatExprs[j]; 650 expr = expr + term; 651 } 652 653 // Constant term. 654 int64_t constTerm = flatExprs[flatExprs.size() - 1]; 655 if (constTerm != 0) 656 expr = expr + constTerm; 657 return expr; 658 } 659 660 SimpleAffineExprFlattener::SimpleAffineExprFlattener(unsigned numDims, 661 unsigned numSymbols) 662 : numDims(numDims), numSymbols(numSymbols), numLocals(0) { 663 operandExprStack.reserve(8); 664 } 665 666 void SimpleAffineExprFlattener::visitMulExpr(AffineBinaryOpExpr expr) { 667 assert(operandExprStack.size() >= 2); 668 // This is a pure affine expr; the RHS will be a constant. 669 assert(expr.getRHS().isa<AffineConstantExpr>()); 670 // Get the RHS constant. 671 auto rhsConst = operandExprStack.back()[getConstantIndex()]; 672 operandExprStack.pop_back(); 673 // Update the LHS in place instead of pop and push. 674 auto &lhs = operandExprStack.back(); 675 for (unsigned i = 0, e = lhs.size(); i < e; i++) { 676 lhs[i] *= rhsConst; 677 } 678 } 679 680 void SimpleAffineExprFlattener::visitAddExpr(AffineBinaryOpExpr expr) { 681 assert(operandExprStack.size() >= 2); 682 const auto &rhs = operandExprStack.back(); 683 auto &lhs = operandExprStack[operandExprStack.size() - 2]; 684 assert(lhs.size() == rhs.size()); 685 // Update the LHS in place. 686 for (unsigned i = 0, e = rhs.size(); i < e; i++) { 687 lhs[i] += rhs[i]; 688 } 689 // Pop off the RHS. 690 operandExprStack.pop_back(); 691 } 692 693 // 694 // t = expr mod c <=> t = expr - c*q and c*q <= expr <= c*q + c - 1 695 // 696 // A mod expression "expr mod c" is thus flattened by introducing a new local 697 // variable q (= expr floordiv c), such that expr mod c is replaced with 698 // 'expr - c * q' and c * q <= expr <= c * q + c - 1 are added to localVarCst. 699 void SimpleAffineExprFlattener::visitModExpr(AffineBinaryOpExpr expr) { 700 assert(operandExprStack.size() >= 2); 701 // This is a pure affine expr; the RHS will be a constant. 702 assert(expr.getRHS().isa<AffineConstantExpr>()); 703 auto rhsConst = operandExprStack.back()[getConstantIndex()]; 704 operandExprStack.pop_back(); 705 auto &lhs = operandExprStack.back(); 706 // TODO(bondhugula): handle modulo by zero case when this issue is fixed 707 // at the other places in the IR. 708 assert(rhsConst > 0 && "RHS constant has to be positive"); 709 710 // Check if the LHS expression is a multiple of modulo factor. 711 unsigned i, e; 712 for (i = 0, e = lhs.size(); i < e; i++) 713 if (lhs[i] % rhsConst != 0) 714 break; 715 // If yes, modulo expression here simplifies to zero. 716 if (i == lhs.size()) { 717 std::fill(lhs.begin(), lhs.end(), 0); 718 return; 719 } 720 721 // Add a local variable for the quotient, i.e., expr % c is replaced by 722 // (expr - q * c) where q = expr floordiv c. Do this while canceling out 723 // the GCD of expr and c. 724 SmallVector<int64_t, 8> floorDividend(lhs); 725 uint64_t gcd = rhsConst; 726 for (unsigned i = 0, e = lhs.size(); i < e; i++) 727 gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i])); 728 // Simplify the numerator and the denominator. 729 if (gcd != 1) { 730 for (unsigned i = 0, e = floorDividend.size(); i < e; i++) 731 floorDividend[i] = floorDividend[i] / static_cast<int64_t>(gcd); 732 } 733 int64_t floorDivisor = rhsConst / static_cast<int64_t>(gcd); 734 735 // Construct the AffineExpr form of the floordiv to store in localExprs. 736 MLIRContext *context = expr.getContext(); 737 auto dividendExpr = getAffineExprFromFlatForm( 738 floorDividend, numDims, numSymbols, localExprs, context); 739 auto divisorExpr = getAffineConstantExpr(floorDivisor, context); 740 auto floorDivExpr = dividendExpr.floorDiv(divisorExpr); 741 int loc; 742 if ((loc = findLocalId(floorDivExpr)) == -1) { 743 addLocalFloorDivId(floorDividend, floorDivisor, floorDivExpr); 744 // Set result at top of stack to "lhs - rhsConst * q". 745 lhs[getLocalVarStartIndex() + numLocals - 1] = -rhsConst; 746 } else { 747 // Reuse the existing local id. 748 lhs[getLocalVarStartIndex() + loc] = -rhsConst; 749 } 750 } 751 752 void SimpleAffineExprFlattener::visitCeilDivExpr(AffineBinaryOpExpr expr) { 753 visitDivExpr(expr, /*isCeil=*/true); 754 } 755 void SimpleAffineExprFlattener::visitFloorDivExpr(AffineBinaryOpExpr expr) { 756 visitDivExpr(expr, /*isCeil=*/false); 757 } 758 759 void SimpleAffineExprFlattener::visitDimExpr(AffineDimExpr expr) { 760 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0)); 761 auto &eq = operandExprStack.back(); 762 assert(expr.getPosition() < numDims && "Inconsistent number of dims"); 763 eq[getDimStartIndex() + expr.getPosition()] = 1; 764 } 765 766 void SimpleAffineExprFlattener::visitSymbolExpr(AffineSymbolExpr expr) { 767 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0)); 768 auto &eq = operandExprStack.back(); 769 assert(expr.getPosition() < numSymbols && "inconsistent number of symbols"); 770 eq[getSymbolStartIndex() + expr.getPosition()] = 1; 771 } 772 773 void SimpleAffineExprFlattener::visitConstantExpr(AffineConstantExpr expr) { 774 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0)); 775 auto &eq = operandExprStack.back(); 776 eq[getConstantIndex()] = expr.getValue(); 777 } 778 779 // t = expr floordiv c <=> t = q, c * q <= expr <= c * q + c - 1 780 // A floordiv is thus flattened by introducing a new local variable q, and 781 // replacing that expression with 'q' while adding the constraints 782 // c * q <= expr <= c * q + c - 1 to localVarCst (done by 783 // FlatAffineConstraints::addLocalFloorDiv). 784 // 785 // A ceildiv is similarly flattened: 786 // t = expr ceildiv c <=> t = (expr + c - 1) floordiv c 787 void SimpleAffineExprFlattener::visitDivExpr(AffineBinaryOpExpr expr, 788 bool isCeil) { 789 assert(operandExprStack.size() >= 2); 790 assert(expr.getRHS().isa<AffineConstantExpr>()); 791 792 // This is a pure affine expr; the RHS is a positive constant. 793 int64_t rhsConst = operandExprStack.back()[getConstantIndex()]; 794 // TODO(bondhugula): handle division by zero at the same time the issue is 795 // fixed at other places. 796 assert(rhsConst > 0 && "RHS constant has to be positive"); 797 operandExprStack.pop_back(); 798 auto &lhs = operandExprStack.back(); 799 800 // Simplify the floordiv, ceildiv if possible by canceling out the greatest 801 // common divisors of the numerator and denominator. 802 uint64_t gcd = std::abs(rhsConst); 803 for (unsigned i = 0, e = lhs.size(); i < e; i++) 804 gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i])); 805 // Simplify the numerator and the denominator. 806 if (gcd != 1) { 807 for (unsigned i = 0, e = lhs.size(); i < e; i++) 808 lhs[i] = lhs[i] / static_cast<int64_t>(gcd); 809 } 810 int64_t divisor = rhsConst / static_cast<int64_t>(gcd); 811 // If the divisor becomes 1, the updated LHS is the result. (The 812 // divisor can't be negative since rhsConst is positive). 813 if (divisor == 1) 814 return; 815 816 // If the divisor cannot be simplified to one, we will have to retain 817 // the ceil/floor expr (simplified up until here). Add an existential 818 // quantifier to express its result, i.e., expr1 div expr2 is replaced 819 // by a new identifier, q. 820 MLIRContext *context = expr.getContext(); 821 auto a = 822 getAffineExprFromFlatForm(lhs, numDims, numSymbols, localExprs, context); 823 auto b = getAffineConstantExpr(divisor, context); 824 825 int loc; 826 auto divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b); 827 if ((loc = findLocalId(divExpr)) == -1) { 828 if (!isCeil) { 829 SmallVector<int64_t, 8> dividend(lhs); 830 addLocalFloorDivId(dividend, divisor, divExpr); 831 } else { 832 // lhs ceildiv c <=> (lhs + c - 1) floordiv c 833 SmallVector<int64_t, 8> dividend(lhs); 834 dividend.back() += divisor - 1; 835 addLocalFloorDivId(dividend, divisor, divExpr); 836 } 837 } 838 // Set the expression on stack to the local var introduced to capture the 839 // result of the division (floor or ceil). 840 std::fill(lhs.begin(), lhs.end(), 0); 841 if (loc == -1) 842 lhs[getLocalVarStartIndex() + numLocals - 1] = 1; 843 else 844 lhs[getLocalVarStartIndex() + loc] = 1; 845 } 846 847 // Add a local identifier (needed to flatten a mod, floordiv, ceildiv expr). 848 // The local identifier added is always a floordiv of a pure add/mul affine 849 // function of other identifiers, coefficients of which are specified in 850 // dividend and with respect to a positive constant divisor. localExpr is the 851 // simplified tree expression (AffineExpr) corresponding to the quantifier. 852 void SimpleAffineExprFlattener::addLocalFloorDivId(ArrayRef<int64_t> dividend, 853 int64_t divisor, 854 AffineExpr localExpr) { 855 assert(divisor > 0 && "positive constant divisor expected"); 856 for (auto &subExpr : operandExprStack) 857 subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0); 858 localExprs.push_back(localExpr); 859 numLocals++; 860 // dividend and divisor are not used here; an override of this method uses it. 861 } 862 863 int SimpleAffineExprFlattener::findLocalId(AffineExpr localExpr) { 864 SmallVectorImpl<AffineExpr>::iterator it; 865 if ((it = llvm::find(localExprs, localExpr)) == localExprs.end()) 866 return -1; 867 return it - localExprs.begin(); 868 } 869 870 /// Simplify the affine expression by flattening it and reconstructing it. 871 AffineExpr mlir::simplifyAffineExpr(AffineExpr expr, unsigned numDims, 872 unsigned numSymbols) { 873 // TODO(bondhugula): only pure affine for now. The simplification here can 874 // be extended to semi-affine maps in the future. 875 if (!expr.isPureAffine()) 876 return expr; 877 878 SimpleAffineExprFlattener flattener(numDims, numSymbols); 879 flattener.walkPostOrder(expr); 880 ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back(); 881 auto simplifiedExpr = 882 getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols, 883 flattener.localExprs, expr.getContext()); 884 flattener.operandExprStack.pop_back(); 885 assert(flattener.operandExprStack.empty()); 886 887 return simplifiedExpr; 888 } 889