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