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