1 //===- SymbolTable.cpp - MLIR Symbol Table Class --------------------------===// 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/SymbolTable.h" 10 #include "llvm/ADT/SetVector.h" 11 #include "llvm/ADT/SmallPtrSet.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/StringSwitch.h" 14 15 using namespace mlir; 16 17 /// Return true if the given operation is unknown and may potentially define a 18 /// symbol table. 19 static bool isPotentiallyUnknownSymbolTable(Operation *op) { 20 return !op->getDialect() && op->getNumRegions() == 1; 21 } 22 23 /// Returns the string name of the given symbol, or None if this is not a 24 /// symbol. 25 static Optional<StringRef> getNameIfSymbol(Operation *symbol) { 26 auto nameAttr = 27 symbol->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()); 28 return nameAttr ? nameAttr.getValue() : Optional<StringRef>(); 29 } 30 31 /// Computes the nested symbol reference attribute for the symbol 'symbolName' 32 /// that are usable within the symbol table operations from 'symbol' as far up 33 /// to the given operation 'within', where 'within' is an ancestor of 'symbol'. 34 /// Returns success if all references up to 'within' could be computed. 35 static LogicalResult 36 collectValidReferencesFor(Operation *symbol, StringRef symbolName, 37 Operation *within, 38 SmallVectorImpl<SymbolRefAttr> &results) { 39 assert(within->isAncestor(symbol) && "expected 'within' to be an ancestor"); 40 MLIRContext *ctx = symbol->getContext(); 41 42 auto leafRef = FlatSymbolRefAttr::get(symbolName, ctx); 43 results.push_back(leafRef); 44 45 // Early exit for when 'within' is the parent of 'symbol'. 46 Operation *symbolTableOp = symbol->getParentOp(); 47 if (within == symbolTableOp) 48 return success(); 49 50 // Collect references until 'symbolTableOp' reaches 'within'. 51 SmallVector<FlatSymbolRefAttr, 1> nestedRefs(1, leafRef); 52 do { 53 // Each parent of 'symbol' should define a symbol table. 54 if (!symbolTableOp->hasTrait<OpTrait::SymbolTable>()) 55 return failure(); 56 // Each parent of 'symbol' should also be a symbol. 57 Optional<StringRef> symbolTableName = getNameIfSymbol(symbolTableOp); 58 if (!symbolTableName) 59 return failure(); 60 results.push_back(SymbolRefAttr::get(*symbolTableName, nestedRefs, ctx)); 61 62 symbolTableOp = symbolTableOp->getParentOp(); 63 if (symbolTableOp == within) 64 break; 65 nestedRefs.insert(nestedRefs.begin(), 66 FlatSymbolRefAttr::get(*symbolTableName, ctx)); 67 } while (true); 68 return success(); 69 } 70 71 //===----------------------------------------------------------------------===// 72 // SymbolTable 73 //===----------------------------------------------------------------------===// 74 75 /// Build a symbol table with the symbols within the given operation. 76 SymbolTable::SymbolTable(Operation *symbolTableOp) 77 : symbolTableOp(symbolTableOp) { 78 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>() && 79 "expected operation to have SymbolTable trait"); 80 assert(symbolTableOp->getNumRegions() == 1 && 81 "expected operation to have a single region"); 82 assert(llvm::hasSingleElement(symbolTableOp->getRegion(0)) && 83 "expected operation to have a single block"); 84 85 for (auto &op : symbolTableOp->getRegion(0).front()) { 86 Optional<StringRef> name = getNameIfSymbol(&op); 87 if (!name) 88 continue; 89 90 auto inserted = symbolTable.insert({*name, &op}); 91 (void)inserted; 92 assert(inserted.second && 93 "expected region to contain uniquely named symbol operations"); 94 } 95 } 96 97 /// Look up a symbol with the specified name, returning null if no such name 98 /// exists. Names never include the @ on them. 99 Operation *SymbolTable::lookup(StringRef name) const { 100 return symbolTable.lookup(name); 101 } 102 103 /// Erase the given symbol from the table. 104 void SymbolTable::erase(Operation *symbol) { 105 Optional<StringRef> name = getNameIfSymbol(symbol); 106 assert(name && "expected valid 'name' attribute"); 107 assert(symbol->getParentOp() == symbolTableOp && 108 "expected this operation to be inside of the operation with this " 109 "SymbolTable"); 110 111 auto it = symbolTable.find(*name); 112 if (it != symbolTable.end() && it->second == symbol) { 113 symbolTable.erase(it); 114 symbol->erase(); 115 } 116 } 117 118 /// Insert a new symbol into the table and associated operation, and rename it 119 /// as necessary to avoid collisions. 120 void SymbolTable::insert(Operation *symbol, Block::iterator insertPt) { 121 auto &body = symbolTableOp->getRegion(0).front(); 122 if (insertPt == Block::iterator() || insertPt == body.end()) 123 insertPt = Block::iterator(body.getTerminator()); 124 125 assert(insertPt->getParentOp() == symbolTableOp && 126 "expected insertPt to be in the associated module operation"); 127 128 body.getOperations().insert(insertPt, symbol); 129 130 // Add this symbol to the symbol table, uniquing the name if a conflict is 131 // detected. 132 StringRef name = getSymbolName(symbol); 133 if (symbolTable.insert({name, symbol}).second) 134 return; 135 // If a conflict was detected, then the symbol will not have been added to 136 // the symbol table. Try suffixes until we get to a unique name that works. 137 SmallString<128> nameBuffer(name); 138 unsigned originalLength = nameBuffer.size(); 139 140 // Iteratively try suffixes until we find one that isn't used. 141 do { 142 nameBuffer.resize(originalLength); 143 nameBuffer += '_'; 144 nameBuffer += std::to_string(uniquingCounter++); 145 } while (!symbolTable.insert({nameBuffer, symbol}).second); 146 setSymbolName(symbol, nameBuffer); 147 } 148 149 /// Returns the name of the given symbol operation. 150 StringRef SymbolTable::getSymbolName(Operation *symbol) { 151 Optional<StringRef> name = getNameIfSymbol(symbol); 152 assert(name && "expected valid symbol name"); 153 return *name; 154 } 155 /// Sets the name of the given symbol operation. 156 void SymbolTable::setSymbolName(Operation *symbol, StringRef name) { 157 symbol->setAttr(getSymbolAttrName(), 158 StringAttr::get(name, symbol->getContext())); 159 } 160 161 /// Returns the visibility of the given symbol operation. 162 SymbolTable::Visibility SymbolTable::getSymbolVisibility(Operation *symbol) { 163 // If the attribute doesn't exist, assume public. 164 StringAttr vis = symbol->getAttrOfType<StringAttr>(getVisibilityAttrName()); 165 if (!vis) 166 return Visibility::Public; 167 168 // Otherwise, switch on the string value. 169 return llvm::StringSwitch<Visibility>(vis.getValue()) 170 .Case("private", Visibility::Private) 171 .Case("nested", Visibility::Nested) 172 .Case("public", Visibility::Public); 173 } 174 /// Sets the visibility of the given symbol operation. 175 void SymbolTable::setSymbolVisibility(Operation *symbol, Visibility vis) { 176 MLIRContext *ctx = symbol->getContext(); 177 178 // If the visibility is public, just drop the attribute as this is the 179 // default. 180 if (vis == Visibility::Public) { 181 symbol->removeAttr(Identifier::get(getVisibilityAttrName(), ctx)); 182 return; 183 } 184 185 // Otherwise, update the attribute. 186 assert((vis == Visibility::Private || vis == Visibility::Nested) && 187 "unknown symbol visibility kind"); 188 189 StringRef visName = vis == Visibility::Private ? "private" : "nested"; 190 symbol->setAttr(getVisibilityAttrName(), StringAttr::get(visName, ctx)); 191 } 192 193 /// Returns the nearest symbol table from a given operation `from`. Returns 194 /// nullptr if no valid parent symbol table could be found. 195 Operation *SymbolTable::getNearestSymbolTable(Operation *from) { 196 assert(from && "expected valid operation"); 197 if (isPotentiallyUnknownSymbolTable(from)) 198 return nullptr; 199 200 while (!from->hasTrait<OpTrait::SymbolTable>()) { 201 from = from->getParentOp(); 202 203 // Check that this is a valid op and isn't an unknown symbol table. 204 if (!from || isPotentiallyUnknownSymbolTable(from)) 205 return nullptr; 206 } 207 return from; 208 } 209 210 /// Walks all symbol table operations nested within, and including, `op`. For 211 /// each symbol table operation, the provided callback is invoked with the op 212 /// and a boolean signifying if the symbols within that symbol table can be 213 /// treated as if all uses are visible. `allSymUsesVisible` identifies whether 214 /// all of the symbol uses of symbols within `op` are visible. 215 void SymbolTable::walkSymbolTables( 216 Operation *op, bool allSymUsesVisible, 217 function_ref<void(Operation *, bool)> callback) { 218 bool isSymbolTable = op->hasTrait<OpTrait::SymbolTable>(); 219 if (isSymbolTable) { 220 SymbolOpInterface symbol = dyn_cast<SymbolOpInterface>(op); 221 allSymUsesVisible |= !symbol || symbol.isPrivate(); 222 } else { 223 // Otherwise if 'op' is not a symbol table, any nested symbols are 224 // guaranteed to be hidden. 225 allSymUsesVisible = true; 226 } 227 228 for (Region ®ion : op->getRegions()) 229 for (Block &block : region) 230 for (Operation &nestedOp : block) 231 walkSymbolTables(&nestedOp, allSymUsesVisible, callback); 232 233 // If 'op' had the symbol table trait, visit it after any nested symbol 234 // tables. 235 if (isSymbolTable) 236 callback(op, allSymUsesVisible); 237 } 238 239 /// Returns the operation registered with the given symbol name with the 240 /// regions of 'symbolTableOp'. 'symbolTableOp' is required to be an operation 241 /// with the 'OpTrait::SymbolTable' trait. Returns nullptr if no valid symbol 242 /// was found. 243 Operation *SymbolTable::lookupSymbolIn(Operation *symbolTableOp, 244 StringRef symbol) { 245 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>()); 246 247 // Look for a symbol with the given name. 248 for (auto &op : symbolTableOp->getRegion(0).front().without_terminator()) 249 if (getNameIfSymbol(&op) == symbol) 250 return &op; 251 return nullptr; 252 } 253 Operation *SymbolTable::lookupSymbolIn(Operation *symbolTableOp, 254 SymbolRefAttr symbol) { 255 SmallVector<Operation *, 4> resolvedSymbols; 256 if (failed(lookupSymbolIn(symbolTableOp, symbol, resolvedSymbols))) 257 return nullptr; 258 return resolvedSymbols.back(); 259 } 260 261 LogicalResult 262 SymbolTable::lookupSymbolIn(Operation *symbolTableOp, SymbolRefAttr symbol, 263 SmallVectorImpl<Operation *> &symbols) { 264 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>()); 265 266 // Lookup the root reference for this symbol. 267 symbolTableOp = lookupSymbolIn(symbolTableOp, symbol.getRootReference()); 268 if (!symbolTableOp) 269 return failure(); 270 symbols.push_back(symbolTableOp); 271 272 // If there are no nested references, just return the root symbol directly. 273 ArrayRef<FlatSymbolRefAttr> nestedRefs = symbol.getNestedReferences(); 274 if (nestedRefs.empty()) 275 return success(); 276 277 // Verify that the root is also a symbol table. 278 if (!symbolTableOp->hasTrait<OpTrait::SymbolTable>()) 279 return failure(); 280 281 // Otherwise, lookup each of the nested non-leaf references and ensure that 282 // each corresponds to a valid symbol table. 283 for (FlatSymbolRefAttr ref : nestedRefs.drop_back()) { 284 symbolTableOp = lookupSymbolIn(symbolTableOp, ref.getValue()); 285 if (!symbolTableOp || !symbolTableOp->hasTrait<OpTrait::SymbolTable>()) 286 return failure(); 287 symbols.push_back(symbolTableOp); 288 } 289 symbols.push_back(lookupSymbolIn(symbolTableOp, symbol.getLeafReference())); 290 return success(symbols.back()); 291 } 292 293 /// Returns the operation registered with the given symbol name within the 294 /// closes parent operation with the 'OpTrait::SymbolTable' trait. Returns 295 /// nullptr if no valid symbol was found. 296 Operation *SymbolTable::lookupNearestSymbolFrom(Operation *from, 297 StringRef symbol) { 298 Operation *symbolTableOp = getNearestSymbolTable(from); 299 return symbolTableOp ? lookupSymbolIn(symbolTableOp, symbol) : nullptr; 300 } 301 Operation *SymbolTable::lookupNearestSymbolFrom(Operation *from, 302 SymbolRefAttr symbol) { 303 Operation *symbolTableOp = getNearestSymbolTable(from); 304 return symbolTableOp ? lookupSymbolIn(symbolTableOp, symbol) : nullptr; 305 } 306 307 //===----------------------------------------------------------------------===// 308 // SymbolTable Trait Types 309 //===----------------------------------------------------------------------===// 310 311 LogicalResult detail::verifySymbolTable(Operation *op) { 312 if (op->getNumRegions() != 1) 313 return op->emitOpError() 314 << "Operations with a 'SymbolTable' must have exactly one region"; 315 if (!llvm::hasSingleElement(op->getRegion(0))) 316 return op->emitOpError() 317 << "Operations with a 'SymbolTable' must have exactly one block"; 318 319 // Check that all symbols are uniquely named within child regions. 320 DenseMap<Attribute, Location> nameToOrigLoc; 321 for (auto &block : op->getRegion(0)) { 322 for (auto &op : block) { 323 // Check for a symbol name attribute. 324 auto nameAttr = 325 op.getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()); 326 if (!nameAttr) 327 continue; 328 329 // Try to insert this symbol into the table. 330 auto it = nameToOrigLoc.try_emplace(nameAttr, op.getLoc()); 331 if (!it.second) 332 return op.emitError() 333 .append("redefinition of symbol named '", nameAttr.getValue(), "'") 334 .attachNote(it.first->second) 335 .append("see existing symbol definition here"); 336 } 337 } 338 return success(); 339 } 340 341 LogicalResult detail::verifySymbol(Operation *op) { 342 // Verify the name attribute. 343 if (!op->getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName())) 344 return op->emitOpError() << "requires string attribute '" 345 << mlir::SymbolTable::getSymbolAttrName() << "'"; 346 347 // Verify the visibility attribute. 348 if (Attribute vis = op->getAttr(mlir::SymbolTable::getVisibilityAttrName())) { 349 StringAttr visStrAttr = vis.dyn_cast<StringAttr>(); 350 if (!visStrAttr) 351 return op->emitOpError() << "requires visibility attribute '" 352 << mlir::SymbolTable::getVisibilityAttrName() 353 << "' to be a string attribute, but got " << vis; 354 355 if (!llvm::is_contained(ArrayRef<StringRef>{"public", "private", "nested"}, 356 visStrAttr.getValue())) 357 return op->emitOpError() 358 << "visibility expected to be one of [\"public\", \"private\", " 359 "\"nested\"], but got " 360 << visStrAttr; 361 } 362 return success(); 363 } 364 365 //===----------------------------------------------------------------------===// 366 // Symbol Use Lists 367 //===----------------------------------------------------------------------===// 368 369 /// Walk all of the symbol references within the given operation, invoking the 370 /// provided callback for each found use. The callbacks takes as arguments: the 371 /// use of the symbol, and the nested access chain to the attribute within the 372 /// operation dictionary. An access chain is a set of indices into nested 373 /// container attributes. For example, a symbol use in an attribute dictionary 374 /// that looks like the following: 375 /// 376 /// {use = [{other_attr, @symbol}]} 377 /// 378 /// May have the following access chain: 379 /// 380 /// [0, 0, 1] 381 /// 382 static WalkResult walkSymbolRefs( 383 Operation *op, 384 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 385 // Check to see if the operation has any attributes. 386 if (op->getMutableAttrDict().empty()) 387 return WalkResult::advance(); 388 DictionaryAttr attrDict = op->getAttrDictionary(); 389 390 // A worklist of a container attribute and the current index into the held 391 // attribute list. 392 SmallVector<Attribute, 1> attrWorklist(1, attrDict); 393 SmallVector<int, 1> curAccessChain(1, /*Value=*/-1); 394 395 // Process the symbol references within the given nested attribute range. 396 auto processAttrs = [&](int &index, auto attrRange) -> WalkResult { 397 for (Attribute attr : llvm::drop_begin(attrRange, index)) { 398 /// Check for a nested container attribute, these will also need to be 399 /// walked. 400 if (attr.isa<ArrayAttr>() || attr.isa<DictionaryAttr>()) { 401 attrWorklist.push_back(attr); 402 curAccessChain.push_back(-1); 403 return WalkResult::advance(); 404 } 405 406 // Invoke the provided callback if we find a symbol use and check for a 407 // requested interrupt. 408 if (auto symbolRef = attr.dyn_cast<SymbolRefAttr>()) 409 if (callback({op, symbolRef}, curAccessChain).wasInterrupted()) 410 return WalkResult::interrupt(); 411 412 // Make sure to keep the index counter in sync. 413 ++index; 414 } 415 416 // Pop this container attribute from the worklist. 417 attrWorklist.pop_back(); 418 curAccessChain.pop_back(); 419 return WalkResult::advance(); 420 }; 421 422 WalkResult result = WalkResult::advance(); 423 do { 424 Attribute attr = attrWorklist.back(); 425 int &index = curAccessChain.back(); 426 ++index; 427 428 // Process the given attribute, which is guaranteed to be a container. 429 if (auto dict = attr.dyn_cast<DictionaryAttr>()) 430 result = processAttrs(index, make_second_range(dict.getValue())); 431 else 432 result = processAttrs(index, attr.cast<ArrayAttr>().getValue()); 433 } while (!attrWorklist.empty() && !result.wasInterrupted()); 434 return result; 435 } 436 437 /// Walk all of the uses, for any symbol, that are nested within the given 438 /// regions, invoking the provided callback for each. This does not traverse 439 /// into any nested symbol tables. 440 static Optional<WalkResult> walkSymbolUses( 441 MutableArrayRef<Region> regions, 442 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 443 SmallVector<Region *, 1> worklist(llvm::make_pointer_range(regions)); 444 while (!worklist.empty()) { 445 for (Operation &op : worklist.pop_back_val()->getOps()) { 446 if (walkSymbolRefs(&op, callback).wasInterrupted()) 447 return WalkResult::interrupt(); 448 449 // Check that this isn't a potentially unknown symbol table. 450 if (isPotentiallyUnknownSymbolTable(&op)) 451 return llvm::None; 452 453 // If this op defines a new symbol table scope, we can't traverse. Any 454 // symbol references nested within 'op' are different semantically. 455 if (!op.hasTrait<OpTrait::SymbolTable>()) { 456 for (Region ®ion : op.getRegions()) 457 worklist.push_back(®ion); 458 } 459 } 460 } 461 return WalkResult::advance(); 462 } 463 /// Walk all of the uses, for any symbol, that are nested within the given 464 /// operation 'from', invoking the provided callback for each. This does not 465 /// traverse into any nested symbol tables. 466 static Optional<WalkResult> walkSymbolUses( 467 Operation *from, 468 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 469 // If this operation has regions, and it, as well as its dialect, isn't 470 // registered then conservatively fail. The operation may define a 471 // symbol table, so we can't opaquely know if we should traverse to find 472 // nested uses. 473 if (isPotentiallyUnknownSymbolTable(from)) 474 return llvm::None; 475 476 // Walk the uses on this operation. 477 if (walkSymbolRefs(from, callback).wasInterrupted()) 478 return WalkResult::interrupt(); 479 480 // Only recurse if this operation is not a symbol table. A symbol table 481 // defines a new scope, so we can't walk the attributes from within the symbol 482 // table op. 483 if (!from->hasTrait<OpTrait::SymbolTable>()) 484 return walkSymbolUses(from->getRegions(), callback); 485 return WalkResult::advance(); 486 } 487 488 namespace { 489 /// This class represents a single symbol scope. A symbol scope represents the 490 /// set of operations nested within a symbol table that may reference symbols 491 /// within that table. A symbol scope does not contain the symbol table 492 /// operation itself, just its contained operations. A scope ends at leaf 493 /// operations or another symbol table operation. 494 struct SymbolScope { 495 /// Walk the symbol uses within this scope, invoking the given callback. 496 /// This variant is used when the callback type matches that expected by 497 /// 'walkSymbolUses'. 498 template <typename CallbackT, 499 typename std::enable_if_t<!std::is_same< 500 typename llvm::function_traits<CallbackT>::result_t, 501 void>::value> * = nullptr> 502 Optional<WalkResult> walk(CallbackT cback) { 503 if (Region *region = limit.dyn_cast<Region *>()) 504 return walkSymbolUses(*region, cback); 505 return walkSymbolUses(limit.get<Operation *>(), cback); 506 } 507 /// This variant is used when the callback type matches a stripped down type: 508 /// void(SymbolTable::SymbolUse use) 509 template <typename CallbackT, 510 typename std::enable_if_t<std::is_same< 511 typename llvm::function_traits<CallbackT>::result_t, 512 void>::value> * = nullptr> 513 Optional<WalkResult> walk(CallbackT cback) { 514 return walk([=](SymbolTable::SymbolUse use, ArrayRef<int>) { 515 return cback(use), WalkResult::advance(); 516 }); 517 } 518 519 /// The representation of the symbol within this scope. 520 SymbolRefAttr symbol; 521 522 /// The IR unit representing this scope. 523 llvm::PointerUnion<Operation *, Region *> limit; 524 }; 525 } // end anonymous namespace 526 527 /// Collect all of the symbol scopes from 'symbol' to (inclusive) 'limit'. 528 static SmallVector<SymbolScope, 2> collectSymbolScopes(Operation *symbol, 529 Operation *limit) { 530 StringRef symName = SymbolTable::getSymbolName(symbol); 531 assert(!symbol->hasTrait<OpTrait::SymbolTable>() || symbol != limit); 532 533 // Compute the ancestors of 'limit'. 534 llvm::SetVector<Operation *, SmallVector<Operation *, 4>, 535 SmallPtrSet<Operation *, 4>> 536 limitAncestors; 537 Operation *limitAncestor = limit; 538 do { 539 // Check to see if 'symbol' is an ancestor of 'limit'. 540 if (limitAncestor == symbol) { 541 // Check that the nearest symbol table is 'symbol's parent. SymbolRefAttr 542 // doesn't support parent references. 543 if (SymbolTable::getNearestSymbolTable(limit->getParentOp()) == 544 symbol->getParentOp()) 545 return {{SymbolRefAttr::get(symName, symbol->getContext()), limit}}; 546 return {}; 547 } 548 549 limitAncestors.insert(limitAncestor); 550 } while ((limitAncestor = limitAncestor->getParentOp())); 551 552 // Try to find the first ancestor of 'symbol' that is an ancestor of 'limit'. 553 Operation *commonAncestor = symbol->getParentOp(); 554 do { 555 if (limitAncestors.count(commonAncestor)) 556 break; 557 } while ((commonAncestor = commonAncestor->getParentOp())); 558 assert(commonAncestor && "'limit' and 'symbol' have no common ancestor"); 559 560 // Compute the set of valid nested references for 'symbol' as far up to the 561 // common ancestor as possible. 562 SmallVector<SymbolRefAttr, 2> references; 563 bool collectedAllReferences = succeeded( 564 collectValidReferencesFor(symbol, symName, commonAncestor, references)); 565 566 // Handle the case where the common ancestor is 'limit'. 567 if (commonAncestor == limit) { 568 SmallVector<SymbolScope, 2> scopes; 569 570 // Walk each of the ancestors of 'symbol', calling the compute function for 571 // each one. 572 Operation *limitIt = symbol->getParentOp(); 573 for (size_t i = 0, e = references.size(); i != e; 574 ++i, limitIt = limitIt->getParentOp()) { 575 assert(limitIt->hasTrait<OpTrait::SymbolTable>()); 576 scopes.push_back({references[i], &limitIt->getRegion(0)}); 577 } 578 return scopes; 579 } 580 581 // Otherwise, we just need the symbol reference for 'symbol' that will be 582 // used within 'limit'. This is the last reference in the list we computed 583 // above if we were able to collect all references. 584 if (!collectedAllReferences) 585 return {}; 586 return {{references.back(), limit}}; 587 } 588 static SmallVector<SymbolScope, 2> collectSymbolScopes(Operation *symbol, 589 Region *limit) { 590 auto scopes = collectSymbolScopes(symbol, limit->getParentOp()); 591 592 // If we collected some scopes to walk, make sure to constrain the one for 593 // limit to the specific region requested. 594 if (!scopes.empty()) 595 scopes.back().limit = limit; 596 return scopes; 597 } 598 template <typename IRUnit> 599 static SmallVector<SymbolScope, 1> collectSymbolScopes(StringRef symbol, 600 IRUnit *limit) { 601 return {{SymbolRefAttr::get(symbol, limit->getContext()), limit}}; 602 } 603 604 /// Returns true if the given reference 'SubRef' is a sub reference of the 605 /// reference 'ref', i.e. 'ref' is a further qualified reference. 606 static bool isReferencePrefixOf(SymbolRefAttr subRef, SymbolRefAttr ref) { 607 if (ref == subRef) 608 return true; 609 610 // If the references are not pointer equal, check to see if `subRef` is a 611 // prefix of `ref`. 612 if (ref.isa<FlatSymbolRefAttr>() || 613 ref.getRootReference() != subRef.getRootReference()) 614 return false; 615 616 auto refLeafs = ref.getNestedReferences(); 617 auto subRefLeafs = subRef.getNestedReferences(); 618 return subRefLeafs.size() < refLeafs.size() && 619 subRefLeafs == refLeafs.take_front(subRefLeafs.size()); 620 } 621 622 //===----------------------------------------------------------------------===// 623 // SymbolTable::getSymbolUses 624 625 /// The implementation of SymbolTable::getSymbolUses below. 626 template <typename FromT> 627 static Optional<SymbolTable::UseRange> getSymbolUsesImpl(FromT from) { 628 std::vector<SymbolTable::SymbolUse> uses; 629 auto walkFn = [&](SymbolTable::SymbolUse symbolUse, ArrayRef<int>) { 630 uses.push_back(symbolUse); 631 return WalkResult::advance(); 632 }; 633 auto result = walkSymbolUses(from, walkFn); 634 return result ? Optional<SymbolTable::UseRange>(std::move(uses)) : llvm::None; 635 } 636 637 /// Get an iterator range for all of the uses, for any symbol, that are nested 638 /// within the given operation 'from'. This does not traverse into any nested 639 /// symbol tables, and will also only return uses on 'from' if it does not 640 /// also define a symbol table. This is because we treat the region as the 641 /// boundary of the symbol table, and not the op itself. This function returns 642 /// None if there are any unknown operations that may potentially be symbol 643 /// tables. 644 auto SymbolTable::getSymbolUses(Operation *from) -> Optional<UseRange> { 645 return getSymbolUsesImpl(from); 646 } 647 auto SymbolTable::getSymbolUses(Region *from) -> Optional<UseRange> { 648 return getSymbolUsesImpl(MutableArrayRef<Region>(*from)); 649 } 650 651 //===----------------------------------------------------------------------===// 652 // SymbolTable::getSymbolUses 653 654 /// The implementation of SymbolTable::getSymbolUses below. 655 template <typename SymbolT, typename IRUnitT> 656 static Optional<SymbolTable::UseRange> getSymbolUsesImpl(SymbolT symbol, 657 IRUnitT *limit) { 658 std::vector<SymbolTable::SymbolUse> uses; 659 for (SymbolScope &scope : collectSymbolScopes(symbol, limit)) { 660 if (!scope.walk([&](SymbolTable::SymbolUse symbolUse) { 661 if (isReferencePrefixOf(scope.symbol, symbolUse.getSymbolRef())) 662 uses.push_back(symbolUse); 663 })) 664 return llvm::None; 665 } 666 return SymbolTable::UseRange(std::move(uses)); 667 } 668 669 /// Get all of the uses of the given symbol that are nested within the given 670 /// operation 'from', invoking the provided callback for each. This does not 671 /// traverse into any nested symbol tables. This function returns None if there 672 /// are any unknown operations that may potentially be symbol tables. 673 auto SymbolTable::getSymbolUses(StringRef symbol, Operation *from) 674 -> Optional<UseRange> { 675 return getSymbolUsesImpl(symbol, from); 676 } 677 auto SymbolTable::getSymbolUses(Operation *symbol, Operation *from) 678 -> Optional<UseRange> { 679 return getSymbolUsesImpl(symbol, from); 680 } 681 auto SymbolTable::getSymbolUses(StringRef symbol, Region *from) 682 -> Optional<UseRange> { 683 return getSymbolUsesImpl(symbol, from); 684 } 685 auto SymbolTable::getSymbolUses(Operation *symbol, Region *from) 686 -> Optional<UseRange> { 687 return getSymbolUsesImpl(symbol, from); 688 } 689 690 //===----------------------------------------------------------------------===// 691 // SymbolTable::symbolKnownUseEmpty 692 693 /// The implementation of SymbolTable::symbolKnownUseEmpty below. 694 template <typename SymbolT, typename IRUnitT> 695 static bool symbolKnownUseEmptyImpl(SymbolT symbol, IRUnitT *limit) { 696 for (SymbolScope &scope : collectSymbolScopes(symbol, limit)) { 697 // Walk all of the symbol uses looking for a reference to 'symbol'. 698 if (scope.walk([&](SymbolTable::SymbolUse symbolUse, ArrayRef<int>) { 699 return isReferencePrefixOf(scope.symbol, symbolUse.getSymbolRef()) 700 ? WalkResult::interrupt() 701 : WalkResult::advance(); 702 }) != WalkResult::advance()) 703 return false; 704 } 705 return true; 706 } 707 708 /// Return if the given symbol is known to have no uses that are nested within 709 /// the given operation 'from'. This does not traverse into any nested symbol 710 /// tables. This function will also return false if there are any unknown 711 /// operations that may potentially be symbol tables. 712 bool SymbolTable::symbolKnownUseEmpty(StringRef symbol, Operation *from) { 713 return symbolKnownUseEmptyImpl(symbol, from); 714 } 715 bool SymbolTable::symbolKnownUseEmpty(Operation *symbol, Operation *from) { 716 return symbolKnownUseEmptyImpl(symbol, from); 717 } 718 bool SymbolTable::symbolKnownUseEmpty(StringRef symbol, Region *from) { 719 return symbolKnownUseEmptyImpl(symbol, from); 720 } 721 bool SymbolTable::symbolKnownUseEmpty(Operation *symbol, Region *from) { 722 return symbolKnownUseEmptyImpl(symbol, from); 723 } 724 725 //===----------------------------------------------------------------------===// 726 // SymbolTable::replaceAllSymbolUses 727 728 /// Rebuild the given attribute container after replacing all references to a 729 /// symbol with the updated attribute in 'accesses'. 730 static Attribute rebuildAttrAfterRAUW( 731 Attribute container, 732 ArrayRef<std::pair<SmallVector<int, 1>, SymbolRefAttr>> accesses, 733 unsigned depth) { 734 // Given a range of Attributes, update the ones referred to by the given 735 // access chains to point to the new symbol attribute. 736 auto updateAttrs = [&](auto &&attrRange) { 737 auto attrBegin = std::begin(attrRange); 738 for (unsigned i = 0, e = accesses.size(); i != e;) { 739 ArrayRef<int> access = accesses[i].first; 740 Attribute &attr = *std::next(attrBegin, access[depth]); 741 742 // Check to see if this is a leaf access, i.e. a SymbolRef. 743 if (access.size() == depth + 1) { 744 attr = accesses[i].second; 745 ++i; 746 continue; 747 } 748 749 // Otherwise, this is a container. Collect all of the accesses for this 750 // index and recurse. The recursion here is bounded by the size of the 751 // largest access array. 752 auto nestedAccesses = accesses.drop_front(i).take_while([&](auto &it) { 753 ArrayRef<int> nextAccess = it.first; 754 return nextAccess.size() > depth + 1 && 755 nextAccess[depth] == access[depth]; 756 }); 757 attr = rebuildAttrAfterRAUW(attr, nestedAccesses, depth + 1); 758 759 // Skip over all of the accesses that refer to the nested container. 760 i += nestedAccesses.size(); 761 } 762 }; 763 764 if (auto dictAttr = container.dyn_cast<DictionaryAttr>()) { 765 auto newAttrs = llvm::to_vector<4>(dictAttr.getValue()); 766 updateAttrs(make_second_range(newAttrs)); 767 return DictionaryAttr::get(newAttrs, dictAttr.getContext()); 768 } 769 auto newAttrs = llvm::to_vector<4>(container.cast<ArrayAttr>().getValue()); 770 updateAttrs(newAttrs); 771 return ArrayAttr::get(newAttrs, container.getContext()); 772 } 773 774 /// Generates a new symbol reference attribute with a new leaf reference. 775 static SymbolRefAttr generateNewRefAttr(SymbolRefAttr oldAttr, 776 FlatSymbolRefAttr newLeafAttr) { 777 if (oldAttr.isa<FlatSymbolRefAttr>()) 778 return newLeafAttr; 779 auto nestedRefs = llvm::to_vector<2>(oldAttr.getNestedReferences()); 780 nestedRefs.back() = newLeafAttr; 781 return SymbolRefAttr::get(oldAttr.getRootReference(), nestedRefs, 782 oldAttr.getContext()); 783 } 784 785 /// The implementation of SymbolTable::replaceAllSymbolUses below. 786 template <typename SymbolT, typename IRUnitT> 787 static LogicalResult 788 replaceAllSymbolUsesImpl(SymbolT symbol, StringRef newSymbol, IRUnitT *limit) { 789 // A collection of operations along with their new attribute dictionary. 790 std::vector<std::pair<Operation *, DictionaryAttr>> updatedAttrDicts; 791 792 // The current operation being processed. 793 Operation *curOp = nullptr; 794 795 // The set of access chains into the attribute dictionary of the current 796 // operation, as well as the replacement attribute to use. 797 SmallVector<std::pair<SmallVector<int, 1>, SymbolRefAttr>, 1> accessChains; 798 799 // Generate a new attribute dictionary for the current operation by replacing 800 // references to the old symbol. 801 auto generateNewAttrDict = [&] { 802 auto oldDict = curOp->getAttrDictionary(); 803 auto newDict = rebuildAttrAfterRAUW(oldDict, accessChains, /*depth=*/0); 804 return newDict.cast<DictionaryAttr>(); 805 }; 806 807 // Generate a new attribute to replace the given attribute. 808 MLIRContext *ctx = limit->getContext(); 809 FlatSymbolRefAttr newLeafAttr = FlatSymbolRefAttr::get(newSymbol, ctx); 810 for (SymbolScope &scope : collectSymbolScopes(symbol, limit)) { 811 SymbolRefAttr newAttr = generateNewRefAttr(scope.symbol, newLeafAttr); 812 auto walkFn = [&](SymbolTable::SymbolUse symbolUse, 813 ArrayRef<int> accessChain) { 814 SymbolRefAttr useRef = symbolUse.getSymbolRef(); 815 if (!isReferencePrefixOf(scope.symbol, useRef)) 816 return WalkResult::advance(); 817 818 // If we have a valid match, check to see if this is a proper 819 // subreference. If it is, then we will need to generate a different new 820 // attribute specifically for this use. 821 SymbolRefAttr replacementRef = newAttr; 822 if (useRef != scope.symbol) { 823 if (scope.symbol.isa<FlatSymbolRefAttr>()) { 824 replacementRef = 825 SymbolRefAttr::get(newSymbol, useRef.getNestedReferences(), ctx); 826 } else { 827 auto nestedRefs = llvm::to_vector<4>(useRef.getNestedReferences()); 828 nestedRefs[scope.symbol.getNestedReferences().size() - 1] = 829 newLeafAttr; 830 replacementRef = 831 SymbolRefAttr::get(useRef.getRootReference(), nestedRefs, ctx); 832 } 833 } 834 835 // If there was a previous operation, generate a new attribute dict 836 // for it. This means that we've finished processing the current 837 // operation, so generate a new dictionary for it. 838 if (curOp && symbolUse.getUser() != curOp) { 839 updatedAttrDicts.push_back({curOp, generateNewAttrDict()}); 840 accessChains.clear(); 841 } 842 843 // Record this access. 844 curOp = symbolUse.getUser(); 845 accessChains.push_back({llvm::to_vector<1>(accessChain), replacementRef}); 846 return WalkResult::advance(); 847 }; 848 if (!scope.walk(walkFn)) 849 return failure(); 850 851 // Check to see if we have a dangling op that needs to be processed. 852 if (curOp) { 853 updatedAttrDicts.push_back({curOp, generateNewAttrDict()}); 854 curOp = nullptr; 855 } 856 } 857 858 // Update the attribute dictionaries as necessary. 859 for (auto &it : updatedAttrDicts) 860 it.first->setAttrs(it.second); 861 return success(); 862 } 863 864 /// Attempt to replace all uses of the given symbol 'oldSymbol' with the 865 /// provided symbol 'newSymbol' that are nested within the given operation 866 /// 'from'. This does not traverse into any nested symbol tables. If there are 867 /// any unknown operations that may potentially be symbol tables, no uses are 868 /// replaced and failure is returned. 869 LogicalResult SymbolTable::replaceAllSymbolUses(StringRef oldSymbol, 870 StringRef newSymbol, 871 Operation *from) { 872 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 873 } 874 LogicalResult SymbolTable::replaceAllSymbolUses(Operation *oldSymbol, 875 StringRef newSymbol, 876 Operation *from) { 877 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 878 } 879 LogicalResult SymbolTable::replaceAllSymbolUses(StringRef oldSymbol, 880 StringRef newSymbol, 881 Region *from) { 882 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 883 } 884 LogicalResult SymbolTable::replaceAllSymbolUses(Operation *oldSymbol, 885 StringRef newSymbol, 886 Region *from) { 887 return replaceAllSymbolUsesImpl(oldSymbol, newSymbol, from); 888 } 889 890 //===----------------------------------------------------------------------===// 891 // Symbol Interfaces 892 //===----------------------------------------------------------------------===// 893 894 /// Include the generated symbol interfaces. 895 #include "mlir/IR/SymbolInterfaces.cpp.inc" 896