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 /// Replace symbols[0 .. numDims - 1] by symbols[shift .. shift + numDims - 1]. 97 AffineExpr AffineExpr::shiftSymbols(unsigned numSymbols, unsigned shift) const { 98 SmallVector<AffineExpr, 4> symbols; 99 for (unsigned idx = 0; idx < numSymbols; ++idx) 100 symbols.push_back(getAffineSymbolExpr(idx + shift, getContext())); 101 return replaceDimsAndSymbols({}, symbols); 102 } 103 104 /// Sparse replace method. Return the modified expression tree. 105 AffineExpr 106 AffineExpr::replace(const DenseMap<AffineExpr, AffineExpr> &map) const { 107 auto it = map.find(*this); 108 if (it != map.end()) 109 return it->second; 110 switch (getKind()) { 111 default: 112 return *this; 113 case AffineExprKind::Add: 114 case AffineExprKind::Mul: 115 case AffineExprKind::FloorDiv: 116 case AffineExprKind::CeilDiv: 117 case AffineExprKind::Mod: 118 auto binOp = cast<AffineBinaryOpExpr>(); 119 auto lhs = binOp.getLHS(), rhs = binOp.getRHS(); 120 auto newLHS = lhs.replace(map); 121 auto newRHS = rhs.replace(map); 122 if (newLHS == lhs && newRHS == rhs) 123 return *this; 124 return getAffineBinaryOpExpr(getKind(), newLHS, newRHS); 125 } 126 llvm_unreachable("Unknown AffineExpr"); 127 } 128 129 /// Sparse replace method. Return the modified expression tree. 130 AffineExpr AffineExpr::replace(AffineExpr expr, AffineExpr replacement) const { 131 DenseMap<AffineExpr, AffineExpr> map; 132 map.insert(std::make_pair(expr, replacement)); 133 return replace(map); 134 } 135 /// Returns true if this expression is made out of only symbols and 136 /// constants (no dimensional identifiers). 137 bool AffineExpr::isSymbolicOrConstant() const { 138 switch (getKind()) { 139 case AffineExprKind::Constant: 140 return true; 141 case AffineExprKind::DimId: 142 return false; 143 case AffineExprKind::SymbolId: 144 return true; 145 146 case AffineExprKind::Add: 147 case AffineExprKind::Mul: 148 case AffineExprKind::FloorDiv: 149 case AffineExprKind::CeilDiv: 150 case AffineExprKind::Mod: { 151 auto expr = this->cast<AffineBinaryOpExpr>(); 152 return expr.getLHS().isSymbolicOrConstant() && 153 expr.getRHS().isSymbolicOrConstant(); 154 } 155 } 156 llvm_unreachable("Unknown AffineExpr"); 157 } 158 159 /// Returns true if this is a pure affine expression, i.e., multiplication, 160 /// floordiv, ceildiv, and mod is only allowed w.r.t constants. 161 bool AffineExpr::isPureAffine() const { 162 switch (getKind()) { 163 case AffineExprKind::SymbolId: 164 case AffineExprKind::DimId: 165 case AffineExprKind::Constant: 166 return true; 167 case AffineExprKind::Add: { 168 auto op = cast<AffineBinaryOpExpr>(); 169 return op.getLHS().isPureAffine() && op.getRHS().isPureAffine(); 170 } 171 172 case AffineExprKind::Mul: { 173 // TODO: Canonicalize the constants in binary operators to the RHS when 174 // possible, allowing this to merge into the next case. 175 auto op = cast<AffineBinaryOpExpr>(); 176 return op.getLHS().isPureAffine() && op.getRHS().isPureAffine() && 177 (op.getLHS().template isa<AffineConstantExpr>() || 178 op.getRHS().template isa<AffineConstantExpr>()); 179 } 180 case AffineExprKind::FloorDiv: 181 case AffineExprKind::CeilDiv: 182 case AffineExprKind::Mod: { 183 auto op = cast<AffineBinaryOpExpr>(); 184 return op.getLHS().isPureAffine() && 185 op.getRHS().template isa<AffineConstantExpr>(); 186 } 187 } 188 llvm_unreachable("Unknown AffineExpr"); 189 } 190 191 // Returns the greatest known integral divisor of this affine expression. 192 int64_t AffineExpr::getLargestKnownDivisor() const { 193 AffineBinaryOpExpr binExpr(nullptr); 194 switch (getKind()) { 195 case AffineExprKind::SymbolId: 196 LLVM_FALLTHROUGH; 197 case AffineExprKind::DimId: 198 return 1; 199 case AffineExprKind::Constant: 200 return std::abs(this->cast<AffineConstantExpr>().getValue()); 201 case AffineExprKind::Mul: { 202 binExpr = this->cast<AffineBinaryOpExpr>(); 203 return binExpr.getLHS().getLargestKnownDivisor() * 204 binExpr.getRHS().getLargestKnownDivisor(); 205 } 206 case AffineExprKind::Add: 207 LLVM_FALLTHROUGH; 208 case AffineExprKind::FloorDiv: 209 case AffineExprKind::CeilDiv: 210 case AffineExprKind::Mod: { 211 binExpr = cast<AffineBinaryOpExpr>(); 212 return llvm::GreatestCommonDivisor64( 213 binExpr.getLHS().getLargestKnownDivisor(), 214 binExpr.getRHS().getLargestKnownDivisor()); 215 } 216 } 217 llvm_unreachable("Unknown AffineExpr"); 218 } 219 220 bool AffineExpr::isMultipleOf(int64_t factor) const { 221 AffineBinaryOpExpr binExpr(nullptr); 222 uint64_t l, u; 223 switch (getKind()) { 224 case AffineExprKind::SymbolId: 225 LLVM_FALLTHROUGH; 226 case AffineExprKind::DimId: 227 return factor * factor == 1; 228 case AffineExprKind::Constant: 229 return cast<AffineConstantExpr>().getValue() % factor == 0; 230 case AffineExprKind::Mul: { 231 binExpr = cast<AffineBinaryOpExpr>(); 232 // It's probably not worth optimizing this further (to not traverse the 233 // whole sub-tree under - it that would require a version of isMultipleOf 234 // that on a 'false' return also returns the largest known divisor). 235 return (l = binExpr.getLHS().getLargestKnownDivisor()) % factor == 0 || 236 (u = binExpr.getRHS().getLargestKnownDivisor()) % factor == 0 || 237 (l * u) % factor == 0; 238 } 239 case AffineExprKind::Add: 240 case AffineExprKind::FloorDiv: 241 case AffineExprKind::CeilDiv: 242 case AffineExprKind::Mod: { 243 binExpr = cast<AffineBinaryOpExpr>(); 244 return llvm::GreatestCommonDivisor64( 245 binExpr.getLHS().getLargestKnownDivisor(), 246 binExpr.getRHS().getLargestKnownDivisor()) % 247 factor == 248 0; 249 } 250 } 251 llvm_unreachable("Unknown AffineExpr"); 252 } 253 254 bool AffineExpr::isFunctionOfDim(unsigned position) const { 255 if (getKind() == AffineExprKind::DimId) { 256 return *this == mlir::getAffineDimExpr(position, getContext()); 257 } 258 if (auto expr = this->dyn_cast<AffineBinaryOpExpr>()) { 259 return expr.getLHS().isFunctionOfDim(position) || 260 expr.getRHS().isFunctionOfDim(position); 261 } 262 return false; 263 } 264 265 AffineBinaryOpExpr::AffineBinaryOpExpr(AffineExpr::ImplType *ptr) 266 : AffineExpr(ptr) {} 267 AffineExpr AffineBinaryOpExpr::getLHS() const { 268 return static_cast<ImplType *>(expr)->lhs; 269 } 270 AffineExpr AffineBinaryOpExpr::getRHS() const { 271 return static_cast<ImplType *>(expr)->rhs; 272 } 273 274 AffineDimExpr::AffineDimExpr(AffineExpr::ImplType *ptr) : AffineExpr(ptr) {} 275 unsigned AffineDimExpr::getPosition() const { 276 return static_cast<ImplType *>(expr)->position; 277 } 278 279 /// Returns true if the expression is divisible by the given symbol with 280 /// position `symbolPos`. The argument `opKind` specifies here what kind of 281 /// division or mod operation called this division. It helps in implementing the 282 /// commutative property of the floordiv and ceildiv operations. If the argument 283 ///`exprKind` is floordiv and `expr` is also a binary expression of a floordiv 284 /// operation, then the commutative property can be used otherwise, the floordiv 285 /// operation is not divisible. The same argument holds for ceildiv operation. 286 static bool isDivisibleBySymbol(AffineExpr expr, unsigned symbolPos, 287 AffineExprKind opKind) { 288 // The argument `opKind` can either be Modulo, Floordiv or Ceildiv only. 289 assert((opKind == AffineExprKind::Mod || opKind == AffineExprKind::FloorDiv || 290 opKind == AffineExprKind::CeilDiv) && 291 "unexpected opKind"); 292 switch (expr.getKind()) { 293 case AffineExprKind::Constant: 294 if (expr.cast<AffineConstantExpr>().getValue()) 295 return false; 296 return true; 297 case AffineExprKind::DimId: 298 return false; 299 case AffineExprKind::SymbolId: 300 return (expr.cast<AffineSymbolExpr>().getPosition() == symbolPos); 301 // Checks divisibility by the given symbol for both operands. 302 case AffineExprKind::Add: { 303 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 304 return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind) && 305 isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, opKind); 306 } 307 // Checks divisibility by the given symbol for both operands. Consider the 308 // expression `(((s1*s0) floordiv w) mod ((s1 * s2) floordiv p)) floordiv s1`, 309 // this is a division by s1 and both the operands of modulo are divisible by 310 // s1 but it is not divisible by s1 always. The third argument is 311 // `AffineExprKind::Mod` for this reason. 312 case AffineExprKind::Mod: { 313 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 314 return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, 315 AffineExprKind::Mod) && 316 isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, 317 AffineExprKind::Mod); 318 } 319 // Checks if any of the operand divisible by the given symbol. 320 case AffineExprKind::Mul: { 321 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 322 return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind) || 323 isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, opKind); 324 } 325 // Floordiv and ceildiv are divisible by the given symbol when the first 326 // operand is divisible, and the affine expression kind of the argument expr 327 // is same as the argument `opKind`. This can be inferred from commutative 328 // property of floordiv and ceildiv operations and are as follow: 329 // (exp1 floordiv exp2) floordiv exp3 = (exp1 floordiv exp3) floordiv exp2 330 // (exp1 ceildiv exp2) ceildiv exp3 = (exp1 ceildiv exp3) ceildiv expr2 331 // It will fail if operations are not same. For example: 332 // (exps1 ceildiv exp2) floordiv exp3 can not be simplified. 333 case AffineExprKind::FloorDiv: 334 case AffineExprKind::CeilDiv: { 335 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 336 if (opKind != expr.getKind()) 337 return false; 338 return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, expr.getKind()); 339 } 340 } 341 llvm_unreachable("Unknown AffineExpr"); 342 } 343 344 /// Divides the given expression by the given symbol at position `symbolPos`. It 345 /// considers the divisibility condition is checked before calling itself. A 346 /// null expression is returned whenever the divisibility condition fails. 347 static AffineExpr symbolicDivide(AffineExpr expr, unsigned symbolPos, 348 AffineExprKind opKind) { 349 // THe argument `opKind` can either be Modulo, Floordiv or Ceildiv only. 350 assert((opKind == AffineExprKind::Mod || opKind == AffineExprKind::FloorDiv || 351 opKind == AffineExprKind::CeilDiv) && 352 "unexpected opKind"); 353 switch (expr.getKind()) { 354 case AffineExprKind::Constant: 355 if (expr.cast<AffineConstantExpr>().getValue() != 0) 356 return nullptr; 357 return getAffineConstantExpr(0, expr.getContext()); 358 case AffineExprKind::DimId: 359 return nullptr; 360 case AffineExprKind::SymbolId: 361 return getAffineConstantExpr(1, expr.getContext()); 362 // Dividing both operands by the given symbol. 363 case AffineExprKind::Add: { 364 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 365 return getAffineBinaryOpExpr( 366 expr.getKind(), symbolicDivide(binaryExpr.getLHS(), symbolPos, opKind), 367 symbolicDivide(binaryExpr.getRHS(), symbolPos, opKind)); 368 } 369 // Dividing both operands by the given symbol. 370 case AffineExprKind::Mod: { 371 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 372 return getAffineBinaryOpExpr( 373 expr.getKind(), 374 symbolicDivide(binaryExpr.getLHS(), symbolPos, expr.getKind()), 375 symbolicDivide(binaryExpr.getRHS(), symbolPos, expr.getKind())); 376 } 377 // Dividing any of the operand by the given symbol. 378 case AffineExprKind::Mul: { 379 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 380 if (!isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind)) 381 return binaryExpr.getLHS() * 382 symbolicDivide(binaryExpr.getRHS(), symbolPos, opKind); 383 return symbolicDivide(binaryExpr.getLHS(), symbolPos, opKind) * 384 binaryExpr.getRHS(); 385 } 386 // Dividing first operand only by the given symbol. 387 case AffineExprKind::FloorDiv: 388 case AffineExprKind::CeilDiv: { 389 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 390 return getAffineBinaryOpExpr( 391 expr.getKind(), 392 symbolicDivide(binaryExpr.getLHS(), symbolPos, expr.getKind()), 393 binaryExpr.getRHS()); 394 } 395 } 396 llvm_unreachable("Unknown AffineExpr"); 397 } 398 399 /// Simplify a semi-affine expression by handling modulo, floordiv, or ceildiv 400 /// operations when the second operand simplifies to a symbol and the first 401 /// operand is divisible by that symbol. It can be applied to any semi-affine 402 /// expression. Returned expression can either be a semi-affine or pure affine 403 /// expression. 404 static AffineExpr simplifySemiAffine(AffineExpr expr) { 405 switch (expr.getKind()) { 406 case AffineExprKind::Constant: 407 case AffineExprKind::DimId: 408 case AffineExprKind::SymbolId: 409 return expr; 410 case AffineExprKind::Add: 411 case AffineExprKind::Mul: { 412 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 413 return getAffineBinaryOpExpr(expr.getKind(), 414 simplifySemiAffine(binaryExpr.getLHS()), 415 simplifySemiAffine(binaryExpr.getRHS())); 416 } 417 // Check if the simplification of the second operand is a symbol, and the 418 // first operand is divisible by it. If the operation is a modulo, a constant 419 // zero expression is returned. In the case of floordiv and ceildiv, the 420 // symbol from the simplification of the second operand divides the first 421 // operand. Otherwise, simplification is not possible. 422 case AffineExprKind::FloorDiv: 423 case AffineExprKind::CeilDiv: 424 case AffineExprKind::Mod: { 425 AffineBinaryOpExpr binaryExpr = expr.cast<AffineBinaryOpExpr>(); 426 AffineExpr sLHS = simplifySemiAffine(binaryExpr.getLHS()); 427 AffineExpr sRHS = simplifySemiAffine(binaryExpr.getRHS()); 428 AffineSymbolExpr symbolExpr = 429 simplifySemiAffine(binaryExpr.getRHS()).dyn_cast<AffineSymbolExpr>(); 430 if (!symbolExpr) 431 return getAffineBinaryOpExpr(expr.getKind(), sLHS, sRHS); 432 unsigned symbolPos = symbolExpr.getPosition(); 433 if (!isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, expr.getKind())) 434 return getAffineBinaryOpExpr(expr.getKind(), sLHS, sRHS); 435 if (expr.getKind() == AffineExprKind::Mod) 436 return getAffineConstantExpr(0, expr.getContext()); 437 return symbolicDivide(sLHS, symbolPos, expr.getKind()); 438 } 439 } 440 llvm_unreachable("Unknown AffineExpr"); 441 } 442 443 static AffineExpr getAffineDimOrSymbol(AffineExprKind kind, unsigned position, 444 MLIRContext *context) { 445 auto assignCtx = [context](AffineDimExprStorage *storage) { 446 storage->context = context; 447 }; 448 449 StorageUniquer &uniquer = context->getAffineUniquer(); 450 return uniquer.get<AffineDimExprStorage>( 451 assignCtx, static_cast<unsigned>(kind), position); 452 } 453 454 AffineExpr mlir::getAffineDimExpr(unsigned position, MLIRContext *context) { 455 return getAffineDimOrSymbol(AffineExprKind::DimId, position, context); 456 } 457 458 AffineSymbolExpr::AffineSymbolExpr(AffineExpr::ImplType *ptr) 459 : AffineExpr(ptr) {} 460 unsigned AffineSymbolExpr::getPosition() const { 461 return static_cast<ImplType *>(expr)->position; 462 } 463 464 AffineExpr mlir::getAffineSymbolExpr(unsigned position, MLIRContext *context) { 465 return getAffineDimOrSymbol(AffineExprKind::SymbolId, position, context); 466 ; 467 } 468 469 AffineConstantExpr::AffineConstantExpr(AffineExpr::ImplType *ptr) 470 : AffineExpr(ptr) {} 471 int64_t AffineConstantExpr::getValue() const { 472 return static_cast<ImplType *>(expr)->constant; 473 } 474 475 bool AffineExpr::operator==(int64_t v) const { 476 return *this == getAffineConstantExpr(v, getContext()); 477 } 478 479 AffineExpr mlir::getAffineConstantExpr(int64_t constant, MLIRContext *context) { 480 auto assignCtx = [context](AffineConstantExprStorage *storage) { 481 storage->context = context; 482 }; 483 484 StorageUniquer &uniquer = context->getAffineUniquer(); 485 return uniquer.get<AffineConstantExprStorage>( 486 assignCtx, static_cast<unsigned>(AffineExprKind::Constant), constant); 487 } 488 489 /// Simplify add expression. Return nullptr if it can't be simplified. 490 static AffineExpr simplifyAdd(AffineExpr lhs, AffineExpr rhs) { 491 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 492 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 493 // Fold if both LHS, RHS are a constant. 494 if (lhsConst && rhsConst) 495 return getAffineConstantExpr(lhsConst.getValue() + rhsConst.getValue(), 496 lhs.getContext()); 497 498 // Canonicalize so that only the RHS is a constant. (4 + d0 becomes d0 + 4). 499 // If only one of them is a symbolic expressions, make it the RHS. 500 if (lhs.isa<AffineConstantExpr>() || 501 (lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant())) { 502 return rhs + lhs; 503 } 504 505 // At this point, if there was a constant, it would be on the right. 506 507 // Addition with a zero is a noop, return the other input. 508 if (rhsConst) { 509 if (rhsConst.getValue() == 0) 510 return lhs; 511 } 512 // Fold successive additions like (d0 + 2) + 3 into d0 + 5. 513 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 514 if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Add) { 515 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) 516 return lBin.getLHS() + (lrhs.getValue() + rhsConst.getValue()); 517 } 518 519 // Detect "c1 * expr + c_2 * expr" as "(c1 + c2) * expr". 520 // c1 is rRhsConst, c2 is rLhsConst; firstExpr, secondExpr are their 521 // respective multiplicands. 522 Optional<int64_t> rLhsConst, rRhsConst; 523 AffineExpr firstExpr, secondExpr; 524 AffineConstantExpr rLhsConstExpr; 525 auto lBinOpExpr = lhs.dyn_cast<AffineBinaryOpExpr>(); 526 if (lBinOpExpr && lBinOpExpr.getKind() == AffineExprKind::Mul && 527 (rLhsConstExpr = lBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) { 528 rLhsConst = rLhsConstExpr.getValue(); 529 firstExpr = lBinOpExpr.getLHS(); 530 } else { 531 rLhsConst = 1; 532 firstExpr = lhs; 533 } 534 535 auto rBinOpExpr = rhs.dyn_cast<AffineBinaryOpExpr>(); 536 AffineConstantExpr rRhsConstExpr; 537 if (rBinOpExpr && rBinOpExpr.getKind() == AffineExprKind::Mul && 538 (rRhsConstExpr = rBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) { 539 rRhsConst = rRhsConstExpr.getValue(); 540 secondExpr = rBinOpExpr.getLHS(); 541 } else { 542 rRhsConst = 1; 543 secondExpr = rhs; 544 } 545 546 if (rLhsConst && rRhsConst && firstExpr == secondExpr) 547 return getAffineBinaryOpExpr( 548 AffineExprKind::Mul, firstExpr, 549 getAffineConstantExpr(rLhsConst.getValue() + rRhsConst.getValue(), 550 lhs.getContext())); 551 552 // When doing successive additions, bring constant to the right: turn (d0 + 2) 553 // + d1 into (d0 + d1) + 2. 554 if (lBin && lBin.getKind() == AffineExprKind::Add) { 555 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 556 return lBin.getLHS() + rhs + lrhs; 557 } 558 } 559 560 // Detect and transform "expr - c * (expr floordiv c)" to "expr mod c". This 561 // leads to a much more efficient form when 'c' is a power of two, and in 562 // general a more compact and readable form. 563 564 // Process '(expr floordiv c) * (-c)'. 565 if (!rBinOpExpr) 566 return nullptr; 567 568 auto lrhs = rBinOpExpr.getLHS(); 569 auto rrhs = rBinOpExpr.getRHS(); 570 571 // Process lrhs, which is 'expr floordiv c'. 572 AffineBinaryOpExpr lrBinOpExpr = lrhs.dyn_cast<AffineBinaryOpExpr>(); 573 if (!lrBinOpExpr || lrBinOpExpr.getKind() != AffineExprKind::FloorDiv) 574 return nullptr; 575 576 auto llrhs = lrBinOpExpr.getLHS(); 577 auto rlrhs = lrBinOpExpr.getRHS(); 578 579 if (lhs == llrhs && rlrhs == -rrhs) { 580 return lhs % rlrhs; 581 } 582 return nullptr; 583 } 584 585 AffineExpr AffineExpr::operator+(int64_t v) const { 586 return *this + getAffineConstantExpr(v, getContext()); 587 } 588 AffineExpr AffineExpr::operator+(AffineExpr other) const { 589 if (auto simplified = simplifyAdd(*this, other)) 590 return simplified; 591 592 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 593 return uniquer.get<AffineBinaryOpExprStorage>( 594 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Add), *this, other); 595 } 596 597 /// Simplify a multiply expression. Return nullptr if it can't be simplified. 598 static AffineExpr simplifyMul(AffineExpr lhs, AffineExpr rhs) { 599 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 600 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 601 602 if (lhsConst && rhsConst) 603 return getAffineConstantExpr(lhsConst.getValue() * rhsConst.getValue(), 604 lhs.getContext()); 605 606 assert(lhs.isSymbolicOrConstant() || rhs.isSymbolicOrConstant()); 607 608 // Canonicalize the mul expression so that the constant/symbolic term is the 609 // RHS. If both the lhs and rhs are symbolic, swap them if the lhs is a 610 // constant. (Note that a constant is trivially symbolic). 611 if (!rhs.isSymbolicOrConstant() || lhs.isa<AffineConstantExpr>()) { 612 // At least one of them has to be symbolic. 613 return rhs * lhs; 614 } 615 616 // At this point, if there was a constant, it would be on the right. 617 618 // Multiplication with a one is a noop, return the other input. 619 if (rhsConst) { 620 if (rhsConst.getValue() == 1) 621 return lhs; 622 // Multiplication with zero. 623 if (rhsConst.getValue() == 0) 624 return rhsConst; 625 } 626 627 // Fold successive multiplications: eg: (d0 * 2) * 3 into d0 * 6. 628 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 629 if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Mul) { 630 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) 631 return lBin.getLHS() * (lrhs.getValue() * rhsConst.getValue()); 632 } 633 634 // When doing successive multiplication, bring constant to the right: turn (d0 635 // * 2) * d1 into (d0 * d1) * 2. 636 if (lBin && lBin.getKind() == AffineExprKind::Mul) { 637 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 638 return (lBin.getLHS() * rhs) * lrhs; 639 } 640 } 641 642 return nullptr; 643 } 644 645 AffineExpr AffineExpr::operator*(int64_t v) const { 646 return *this * getAffineConstantExpr(v, getContext()); 647 } 648 AffineExpr AffineExpr::operator*(AffineExpr other) const { 649 if (auto simplified = simplifyMul(*this, other)) 650 return simplified; 651 652 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 653 return uniquer.get<AffineBinaryOpExprStorage>( 654 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mul), *this, other); 655 } 656 657 // Unary minus, delegate to operator*. 658 AffineExpr AffineExpr::operator-() const { 659 return *this * getAffineConstantExpr(-1, getContext()); 660 } 661 662 // Delegate to operator+. 663 AffineExpr AffineExpr::operator-(int64_t v) const { return *this + (-v); } 664 AffineExpr AffineExpr::operator-(AffineExpr other) const { 665 return *this + (-other); 666 } 667 668 static AffineExpr simplifyFloorDiv(AffineExpr lhs, AffineExpr rhs) { 669 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 670 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 671 672 // mlir floordiv by zero or negative numbers is undefined and preserved as is. 673 if (!rhsConst || rhsConst.getValue() < 1) 674 return nullptr; 675 676 if (lhsConst) 677 return getAffineConstantExpr( 678 floorDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext()); 679 680 // Fold floordiv of a multiply with a constant that is a multiple of the 681 // divisor. Eg: (i * 128) floordiv 64 = i * 2. 682 if (rhsConst == 1) 683 return lhs; 684 685 // Simplify (expr * const) floordiv divConst when expr is known to be a 686 // multiple of divConst. 687 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 688 if (lBin && lBin.getKind() == AffineExprKind::Mul) { 689 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 690 // rhsConst is known to be a positive constant. 691 if (lrhs.getValue() % rhsConst.getValue() == 0) 692 return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue()); 693 } 694 } 695 696 // Simplify (expr1 + expr2) floordiv divConst when either expr1 or expr2 is 697 // known to be a multiple of divConst. 698 if (lBin && lBin.getKind() == AffineExprKind::Add) { 699 int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor(); 700 int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor(); 701 // rhsConst is known to be a positive constant. 702 if (llhsDiv % rhsConst.getValue() == 0 || 703 lrhsDiv % rhsConst.getValue() == 0) 704 return lBin.getLHS().floorDiv(rhsConst.getValue()) + 705 lBin.getRHS().floorDiv(rhsConst.getValue()); 706 } 707 708 return nullptr; 709 } 710 711 AffineExpr AffineExpr::floorDiv(uint64_t v) const { 712 return floorDiv(getAffineConstantExpr(v, getContext())); 713 } 714 AffineExpr AffineExpr::floorDiv(AffineExpr other) const { 715 if (auto simplified = simplifyFloorDiv(*this, other)) 716 return simplified; 717 718 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 719 return uniquer.get<AffineBinaryOpExprStorage>( 720 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::FloorDiv), *this, 721 other); 722 } 723 724 static AffineExpr simplifyCeilDiv(AffineExpr lhs, AffineExpr rhs) { 725 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 726 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 727 728 if (!rhsConst || rhsConst.getValue() < 1) 729 return nullptr; 730 731 if (lhsConst) 732 return getAffineConstantExpr( 733 ceilDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext()); 734 735 // Fold ceildiv of a multiply with a constant that is a multiple of the 736 // divisor. Eg: (i * 128) ceildiv 64 = i * 2. 737 if (rhsConst.getValue() == 1) 738 return lhs; 739 740 // Simplify (expr * const) ceildiv divConst when const is known to be a 741 // multiple of divConst. 742 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 743 if (lBin && lBin.getKind() == AffineExprKind::Mul) { 744 if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) { 745 // rhsConst is known to be a positive constant. 746 if (lrhs.getValue() % rhsConst.getValue() == 0) 747 return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue()); 748 } 749 } 750 751 return nullptr; 752 } 753 754 AffineExpr AffineExpr::ceilDiv(uint64_t v) const { 755 return ceilDiv(getAffineConstantExpr(v, getContext())); 756 } 757 AffineExpr AffineExpr::ceilDiv(AffineExpr other) const { 758 if (auto simplified = simplifyCeilDiv(*this, other)) 759 return simplified; 760 761 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 762 return uniquer.get<AffineBinaryOpExprStorage>( 763 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::CeilDiv), *this, 764 other); 765 } 766 767 static AffineExpr simplifyMod(AffineExpr lhs, AffineExpr rhs) { 768 auto lhsConst = lhs.dyn_cast<AffineConstantExpr>(); 769 auto rhsConst = rhs.dyn_cast<AffineConstantExpr>(); 770 771 // mod w.r.t zero or negative numbers is undefined and preserved as is. 772 if (!rhsConst || rhsConst.getValue() < 1) 773 return nullptr; 774 775 if (lhsConst) 776 return getAffineConstantExpr(mod(lhsConst.getValue(), rhsConst.getValue()), 777 lhs.getContext()); 778 779 // Fold modulo of an expression that is known to be a multiple of a constant 780 // to zero if that constant is a multiple of the modulo factor. Eg: (i * 128) 781 // mod 64 is folded to 0, and less trivially, (i*(j*4*(k*32))) mod 128 = 0. 782 if (lhs.getLargestKnownDivisor() % rhsConst.getValue() == 0) 783 return getAffineConstantExpr(0, lhs.getContext()); 784 785 // Simplify (expr1 + expr2) mod divConst when either expr1 or expr2 is 786 // known to be a multiple of divConst. 787 auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>(); 788 if (lBin && lBin.getKind() == AffineExprKind::Add) { 789 int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor(); 790 int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor(); 791 // rhsConst is known to be a positive constant. 792 if (llhsDiv % rhsConst.getValue() == 0) 793 return lBin.getRHS() % rhsConst.getValue(); 794 if (lrhsDiv % rhsConst.getValue() == 0) 795 return lBin.getLHS() % rhsConst.getValue(); 796 } 797 798 return nullptr; 799 } 800 801 AffineExpr AffineExpr::operator%(uint64_t v) const { 802 return *this % getAffineConstantExpr(v, getContext()); 803 } 804 AffineExpr AffineExpr::operator%(AffineExpr other) const { 805 if (auto simplified = simplifyMod(*this, other)) 806 return simplified; 807 808 StorageUniquer &uniquer = getContext()->getAffineUniquer(); 809 return uniquer.get<AffineBinaryOpExprStorage>( 810 /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mod), *this, other); 811 } 812 813 AffineExpr AffineExpr::compose(AffineMap map) const { 814 SmallVector<AffineExpr, 8> dimReplacements(map.getResults().begin(), 815 map.getResults().end()); 816 return replaceDimsAndSymbols(dimReplacements, {}); 817 } 818 raw_ostream &mlir::operator<<(raw_ostream &os, AffineExpr expr) { 819 expr.print(os); 820 return os; 821 } 822 823 /// Constructs an affine expression from a flat ArrayRef. If there are local 824 /// identifiers (neither dimensional nor symbolic) that appear in the sum of 825 /// products expression, `localExprs` is expected to have the AffineExpr 826 /// for it, and is substituted into. The ArrayRef `flatExprs` is expected to be 827 /// in the format [dims, symbols, locals, constant term]. 828 AffineExpr mlir::getAffineExprFromFlatForm(ArrayRef<int64_t> flatExprs, 829 unsigned numDims, 830 unsigned numSymbols, 831 ArrayRef<AffineExpr> localExprs, 832 MLIRContext *context) { 833 // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1. 834 assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() && 835 "unexpected number of local expressions"); 836 837 auto expr = getAffineConstantExpr(0, context); 838 // Dimensions and symbols. 839 for (unsigned j = 0; j < numDims + numSymbols; j++) { 840 if (flatExprs[j] == 0) 841 continue; 842 auto id = j < numDims ? getAffineDimExpr(j, context) 843 : getAffineSymbolExpr(j - numDims, context); 844 expr = expr + id * flatExprs[j]; 845 } 846 847 // Local identifiers. 848 for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e; 849 j++) { 850 if (flatExprs[j] == 0) 851 continue; 852 auto term = localExprs[j - numDims - numSymbols] * flatExprs[j]; 853 expr = expr + term; 854 } 855 856 // Constant term. 857 int64_t constTerm = flatExprs[flatExprs.size() - 1]; 858 if (constTerm != 0) 859 expr = expr + constTerm; 860 return expr; 861 } 862 863 SimpleAffineExprFlattener::SimpleAffineExprFlattener(unsigned numDims, 864 unsigned numSymbols) 865 : numDims(numDims), numSymbols(numSymbols), numLocals(0) { 866 operandExprStack.reserve(8); 867 } 868 869 void SimpleAffineExprFlattener::visitMulExpr(AffineBinaryOpExpr expr) { 870 assert(operandExprStack.size() >= 2); 871 // This is a pure affine expr; the RHS will be a constant. 872 assert(expr.getRHS().isa<AffineConstantExpr>()); 873 // Get the RHS constant. 874 auto rhsConst = operandExprStack.back()[getConstantIndex()]; 875 operandExprStack.pop_back(); 876 // Update the LHS in place instead of pop and push. 877 auto &lhs = operandExprStack.back(); 878 for (unsigned i = 0, e = lhs.size(); i < e; i++) { 879 lhs[i] *= rhsConst; 880 } 881 } 882 883 void SimpleAffineExprFlattener::visitAddExpr(AffineBinaryOpExpr expr) { 884 assert(operandExprStack.size() >= 2); 885 const auto &rhs = operandExprStack.back(); 886 auto &lhs = operandExprStack[operandExprStack.size() - 2]; 887 assert(lhs.size() == rhs.size()); 888 // Update the LHS in place. 889 for (unsigned i = 0, e = rhs.size(); i < e; i++) { 890 lhs[i] += rhs[i]; 891 } 892 // Pop off the RHS. 893 operandExprStack.pop_back(); 894 } 895 896 // 897 // t = expr mod c <=> t = expr - c*q and c*q <= expr <= c*q + c - 1 898 // 899 // A mod expression "expr mod c" is thus flattened by introducing a new local 900 // variable q (= expr floordiv c), such that expr mod c is replaced with 901 // 'expr - c * q' and c * q <= expr <= c * q + c - 1 are added to localVarCst. 902 void SimpleAffineExprFlattener::visitModExpr(AffineBinaryOpExpr expr) { 903 assert(operandExprStack.size() >= 2); 904 // This is a pure affine expr; the RHS will be a constant. 905 assert(expr.getRHS().isa<AffineConstantExpr>()); 906 auto rhsConst = operandExprStack.back()[getConstantIndex()]; 907 operandExprStack.pop_back(); 908 auto &lhs = operandExprStack.back(); 909 // TODO: handle modulo by zero case when this issue is fixed 910 // at the other places in the IR. 911 assert(rhsConst > 0 && "RHS constant has to be positive"); 912 913 // Check if the LHS expression is a multiple of modulo factor. 914 unsigned i, e; 915 for (i = 0, e = lhs.size(); i < e; i++) 916 if (lhs[i] % rhsConst != 0) 917 break; 918 // If yes, modulo expression here simplifies to zero. 919 if (i == lhs.size()) { 920 std::fill(lhs.begin(), lhs.end(), 0); 921 return; 922 } 923 924 // Add a local variable for the quotient, i.e., expr % c is replaced by 925 // (expr - q * c) where q = expr floordiv c. Do this while canceling out 926 // the GCD of expr and c. 927 SmallVector<int64_t, 8> floorDividend(lhs); 928 uint64_t gcd = rhsConst; 929 for (unsigned i = 0, e = lhs.size(); i < e; i++) 930 gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i])); 931 // Simplify the numerator and the denominator. 932 if (gcd != 1) { 933 for (unsigned i = 0, e = floorDividend.size(); i < e; i++) 934 floorDividend[i] = floorDividend[i] / static_cast<int64_t>(gcd); 935 } 936 int64_t floorDivisor = rhsConst / static_cast<int64_t>(gcd); 937 938 // Construct the AffineExpr form of the floordiv to store in localExprs. 939 MLIRContext *context = expr.getContext(); 940 auto dividendExpr = getAffineExprFromFlatForm( 941 floorDividend, numDims, numSymbols, localExprs, context); 942 auto divisorExpr = getAffineConstantExpr(floorDivisor, context); 943 auto floorDivExpr = dividendExpr.floorDiv(divisorExpr); 944 int loc; 945 if ((loc = findLocalId(floorDivExpr)) == -1) { 946 addLocalFloorDivId(floorDividend, floorDivisor, floorDivExpr); 947 // Set result at top of stack to "lhs - rhsConst * q". 948 lhs[getLocalVarStartIndex() + numLocals - 1] = -rhsConst; 949 } else { 950 // Reuse the existing local id. 951 lhs[getLocalVarStartIndex() + loc] = -rhsConst; 952 } 953 } 954 955 void SimpleAffineExprFlattener::visitCeilDivExpr(AffineBinaryOpExpr expr) { 956 visitDivExpr(expr, /*isCeil=*/true); 957 } 958 void SimpleAffineExprFlattener::visitFloorDivExpr(AffineBinaryOpExpr expr) { 959 visitDivExpr(expr, /*isCeil=*/false); 960 } 961 962 void SimpleAffineExprFlattener::visitDimExpr(AffineDimExpr expr) { 963 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0)); 964 auto &eq = operandExprStack.back(); 965 assert(expr.getPosition() < numDims && "Inconsistent number of dims"); 966 eq[getDimStartIndex() + expr.getPosition()] = 1; 967 } 968 969 void SimpleAffineExprFlattener::visitSymbolExpr(AffineSymbolExpr expr) { 970 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0)); 971 auto &eq = operandExprStack.back(); 972 assert(expr.getPosition() < numSymbols && "inconsistent number of symbols"); 973 eq[getSymbolStartIndex() + expr.getPosition()] = 1; 974 } 975 976 void SimpleAffineExprFlattener::visitConstantExpr(AffineConstantExpr expr) { 977 operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0)); 978 auto &eq = operandExprStack.back(); 979 eq[getConstantIndex()] = expr.getValue(); 980 } 981 982 // t = expr floordiv c <=> t = q, c * q <= expr <= c * q + c - 1 983 // A floordiv is thus flattened by introducing a new local variable q, and 984 // replacing that expression with 'q' while adding the constraints 985 // c * q <= expr <= c * q + c - 1 to localVarCst (done by 986 // FlatAffineConstraints::addLocalFloorDiv). 987 // 988 // A ceildiv is similarly flattened: 989 // t = expr ceildiv c <=> t = (expr + c - 1) floordiv c 990 void SimpleAffineExprFlattener::visitDivExpr(AffineBinaryOpExpr expr, 991 bool isCeil) { 992 assert(operandExprStack.size() >= 2); 993 assert(expr.getRHS().isa<AffineConstantExpr>()); 994 995 // This is a pure affine expr; the RHS is a positive constant. 996 int64_t rhsConst = operandExprStack.back()[getConstantIndex()]; 997 // TODO: handle division by zero at the same time the issue is 998 // fixed at other places. 999 assert(rhsConst > 0 && "RHS constant has to be positive"); 1000 operandExprStack.pop_back(); 1001 auto &lhs = operandExprStack.back(); 1002 1003 // Simplify the floordiv, ceildiv if possible by canceling out the greatest 1004 // common divisors of the numerator and denominator. 1005 uint64_t gcd = std::abs(rhsConst); 1006 for (unsigned i = 0, e = lhs.size(); i < e; i++) 1007 gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i])); 1008 // Simplify the numerator and the denominator. 1009 if (gcd != 1) { 1010 for (unsigned i = 0, e = lhs.size(); i < e; i++) 1011 lhs[i] = lhs[i] / static_cast<int64_t>(gcd); 1012 } 1013 int64_t divisor = rhsConst / static_cast<int64_t>(gcd); 1014 // If the divisor becomes 1, the updated LHS is the result. (The 1015 // divisor can't be negative since rhsConst is positive). 1016 if (divisor == 1) 1017 return; 1018 1019 // If the divisor cannot be simplified to one, we will have to retain 1020 // the ceil/floor expr (simplified up until here). Add an existential 1021 // quantifier to express its result, i.e., expr1 div expr2 is replaced 1022 // by a new identifier, q. 1023 MLIRContext *context = expr.getContext(); 1024 auto a = 1025 getAffineExprFromFlatForm(lhs, numDims, numSymbols, localExprs, context); 1026 auto b = getAffineConstantExpr(divisor, context); 1027 1028 int loc; 1029 auto divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b); 1030 if ((loc = findLocalId(divExpr)) == -1) { 1031 if (!isCeil) { 1032 SmallVector<int64_t, 8> dividend(lhs); 1033 addLocalFloorDivId(dividend, divisor, divExpr); 1034 } else { 1035 // lhs ceildiv c <=> (lhs + c - 1) floordiv c 1036 SmallVector<int64_t, 8> dividend(lhs); 1037 dividend.back() += divisor - 1; 1038 addLocalFloorDivId(dividend, divisor, divExpr); 1039 } 1040 } 1041 // Set the expression on stack to the local var introduced to capture the 1042 // result of the division (floor or ceil). 1043 std::fill(lhs.begin(), lhs.end(), 0); 1044 if (loc == -1) 1045 lhs[getLocalVarStartIndex() + numLocals - 1] = 1; 1046 else 1047 lhs[getLocalVarStartIndex() + loc] = 1; 1048 } 1049 1050 // Add a local identifier (needed to flatten a mod, floordiv, ceildiv expr). 1051 // The local identifier added is always a floordiv of a pure add/mul affine 1052 // function of other identifiers, coefficients of which are specified in 1053 // dividend and with respect to a positive constant divisor. localExpr is the 1054 // simplified tree expression (AffineExpr) corresponding to the quantifier. 1055 void SimpleAffineExprFlattener::addLocalFloorDivId(ArrayRef<int64_t> dividend, 1056 int64_t divisor, 1057 AffineExpr localExpr) { 1058 assert(divisor > 0 && "positive constant divisor expected"); 1059 for (auto &subExpr : operandExprStack) 1060 subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0); 1061 localExprs.push_back(localExpr); 1062 numLocals++; 1063 // dividend and divisor are not used here; an override of this method uses it. 1064 } 1065 1066 int SimpleAffineExprFlattener::findLocalId(AffineExpr localExpr) { 1067 SmallVectorImpl<AffineExpr>::iterator it; 1068 if ((it = llvm::find(localExprs, localExpr)) == localExprs.end()) 1069 return -1; 1070 return it - localExprs.begin(); 1071 } 1072 1073 /// Simplify the affine expression by flattening it and reconstructing it. 1074 AffineExpr mlir::simplifyAffineExpr(AffineExpr expr, unsigned numDims, 1075 unsigned numSymbols) { 1076 // Simplify semi-affine expressions separately. 1077 if (!expr.isPureAffine()) 1078 expr = simplifySemiAffine(expr); 1079 if (!expr.isPureAffine()) 1080 return expr; 1081 1082 SimpleAffineExprFlattener flattener(numDims, numSymbols); 1083 flattener.walkPostOrder(expr); 1084 ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back(); 1085 auto simplifiedExpr = 1086 getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols, 1087 flattener.localExprs, expr.getContext()); 1088 flattener.operandExprStack.pop_back(); 1089 assert(flattener.operandExprStack.empty()); 1090 1091 return simplifiedExpr; 1092 } 1093