1 //===- SymbolTable.cpp - MLIR Symbol Table Class --------------------------===// 2 // 3 // Copyright 2019 The MLIR Authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // ============================================================================= 17 18 #include "mlir/IR/SymbolTable.h" 19 #include "llvm/ADT/SmallString.h" 20 21 using namespace mlir; 22 23 /// Return true if the given operation is unknown and may potentially define a 24 /// symbol table. 25 static bool isPotentiallyUnknownSymbolTable(Operation *op) { 26 return !op->getDialect() && op->getNumRegions() == 1; 27 } 28 29 //===----------------------------------------------------------------------===// 30 // SymbolTable 31 //===----------------------------------------------------------------------===// 32 33 /// Build a symbol table with the symbols within the given operation. 34 SymbolTable::SymbolTable(Operation *op) : context(op->getContext()) { 35 assert(op->hasTrait<OpTrait::SymbolTable>() && 36 "expected operation to have SymbolTable trait"); 37 assert(op->getNumRegions() == 1 && 38 "expected operation to have a single region"); 39 40 for (auto &block : op->getRegion(0)) { 41 for (auto &op : block) { 42 auto nameAttr = op.getAttrOfType<StringAttr>(getSymbolAttrName()); 43 if (!nameAttr) 44 continue; 45 46 auto inserted = symbolTable.insert({nameAttr.getValue(), &op}); 47 (void)inserted; 48 assert(inserted.second && 49 "expected region to contain uniquely named symbol operations"); 50 } 51 } 52 } 53 54 /// Look up a symbol with the specified name, returning null if no such name 55 /// exists. Names never include the @ on them. 56 Operation *SymbolTable::lookup(StringRef name) const { 57 return symbolTable.lookup(name); 58 } 59 60 /// Erase the given symbol from the table. 61 void SymbolTable::erase(Operation *symbol) { 62 auto nameAttr = symbol->getAttrOfType<StringAttr>(getSymbolAttrName()); 63 assert(nameAttr && "expected valid 'name' attribute"); 64 65 auto it = symbolTable.find(nameAttr.getValue()); 66 if (it != symbolTable.end() && it->second == symbol) 67 symbolTable.erase(it); 68 } 69 70 /// Insert a new symbol into the table, and rename it as necessary to avoid 71 /// collisions. 72 void SymbolTable::insert(Operation *symbol) { 73 auto nameAttr = symbol->getAttrOfType<StringAttr>(getSymbolAttrName()); 74 assert(nameAttr && "expected valid 'name' attribute"); 75 76 // Add this symbol to the symbol table, uniquing the name if a conflict is 77 // detected. 78 if (symbolTable.insert({nameAttr.getValue(), symbol}).second) 79 return; 80 81 // If a conflict was detected, then the symbol will not have been added to 82 // the symbol table. Try suffixes until we get to a unique name that works. 83 SmallString<128> nameBuffer(nameAttr.getValue()); 84 unsigned originalLength = nameBuffer.size(); 85 86 // Iteratively try suffixes until we find one that isn't used. 87 do { 88 nameBuffer.resize(originalLength); 89 nameBuffer += '_'; 90 nameBuffer += std::to_string(uniquingCounter++); 91 } while (!symbolTable.insert({nameBuffer, symbol}).second); 92 symbol->setAttr(getSymbolAttrName(), StringAttr::get(nameBuffer, context)); 93 } 94 95 /// Returns the operation registered with the given symbol name with the 96 /// regions of 'symbolTableOp'. 'symbolTableOp' is required to be an operation 97 /// with the 'OpTrait::SymbolTable' trait. Returns nullptr if no valid symbol 98 /// was found. 99 Operation *SymbolTable::lookupSymbolIn(Operation *symbolTableOp, 100 StringRef symbol) { 101 assert(symbolTableOp->hasTrait<OpTrait::SymbolTable>()); 102 103 // Look for a symbol with the given name. 104 for (auto &block : symbolTableOp->getRegion(0)) { 105 for (auto &op : block) { 106 auto nameAttr = op.template getAttrOfType<StringAttr>( 107 mlir::SymbolTable::getSymbolAttrName()); 108 if (nameAttr && nameAttr.getValue() == symbol) 109 return &op; 110 } 111 } 112 return nullptr; 113 } 114 115 /// Returns the operation registered with the given symbol name within the 116 /// closes parent operation with the 'OpTrait::SymbolTable' trait. Returns 117 /// nullptr if no valid symbol was found. 118 Operation *SymbolTable::lookupNearestSymbolFrom(Operation *from, 119 StringRef symbol) { 120 assert(from && "expected valid operation"); 121 while (!from->hasTrait<OpTrait::SymbolTable>()) { 122 from = from->getParentOp(); 123 124 // Check that this is a valid op and isn't an unknown symbol table. 125 if (!from || isPotentiallyUnknownSymbolTable(from)) 126 return nullptr; 127 } 128 return lookupSymbolIn(from, symbol); 129 } 130 131 //===----------------------------------------------------------------------===// 132 // SymbolTable Trait Types 133 //===----------------------------------------------------------------------===// 134 135 LogicalResult OpTrait::impl::verifySymbolTable(Operation *op) { 136 if (op->getNumRegions() != 1) 137 return op->emitOpError() 138 << "Operations with a 'SymbolTable' must have exactly one region"; 139 140 // Check that all symbols are uniquely named within child regions. 141 llvm::StringMap<Location> nameToOrigLoc; 142 for (auto &block : op->getRegion(0)) { 143 for (auto &op : block) { 144 // Check for a symbol name attribute. 145 auto nameAttr = 146 op.getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()); 147 if (!nameAttr) 148 continue; 149 150 // Try to insert this symbol into the table. 151 auto it = nameToOrigLoc.try_emplace(nameAttr.getValue(), op.getLoc()); 152 if (!it.second) 153 return op.emitError() 154 .append("redefinition of symbol named '", nameAttr.getValue(), "'") 155 .attachNote(it.first->second) 156 .append("see existing symbol definition here"); 157 } 158 } 159 return success(); 160 } 161 162 LogicalResult OpTrait::impl::verifySymbol(Operation *op) { 163 if (!op->getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName())) 164 return op->emitOpError() << "requires string attribute '" 165 << mlir::SymbolTable::getSymbolAttrName() << "'"; 166 return success(); 167 } 168 169 //===----------------------------------------------------------------------===// 170 // Symbol Use Lists 171 //===----------------------------------------------------------------------===// 172 173 /// Walk all of the symbol references within the given operation, invoking the 174 /// provided callback for each found use. The callbacks takes as arguments: the 175 /// use of the symbol, and the nested access chain to the attribute within the 176 /// operation dictionary. An access chain is a set of indices into nested 177 /// container attributes. For example, a symbol use in an attribute dictionary 178 /// that looks like the following: 179 /// 180 /// {use = [{other_attr, @symbol}]} 181 /// 182 /// May have the following access chain: 183 /// 184 /// [0, 0, 1] 185 /// 186 static WalkResult walkSymbolRefs( 187 Operation *op, 188 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 189 // Check to see if the operation has any attributes. 190 DictionaryAttr attrDict = op->getAttrList().getDictionary(); 191 if (!attrDict) 192 return WalkResult::advance(); 193 194 // A worklist of a container attribute and the current index into the held 195 // attribute list. 196 SmallVector<Attribute, 1> attrWorklist(1, attrDict); 197 SmallVector<int, 1> curAccessChain(1, /*Value=*/-1); 198 199 // Process the symbol references within the given nested attribute range. 200 auto processAttrs = [&](int &index, auto attrRange) -> WalkResult { 201 for (Attribute attr : llvm::drop_begin(attrRange, index)) { 202 /// Check for a nested container attribute, these will also need to be 203 /// walked. 204 if (attr.isa<ArrayAttr>() || attr.isa<DictionaryAttr>()) { 205 attrWorklist.push_back(attr); 206 curAccessChain.push_back(-1); 207 return WalkResult::advance(); 208 } 209 210 // Invoke the provided callback if we find a symbol use and check for a 211 // requested interrupt. 212 if (auto symbolRef = attr.dyn_cast<SymbolRefAttr>()) 213 if (callback({op, symbolRef}, curAccessChain).wasInterrupted()) 214 return WalkResult::interrupt(); 215 216 // Make sure to keep the index counter in sync. 217 ++index; 218 } 219 220 // Pop this container attribute from the worklist. 221 attrWorklist.pop_back(); 222 curAccessChain.pop_back(); 223 return WalkResult::advance(); 224 }; 225 226 WalkResult result = WalkResult::advance(); 227 do { 228 Attribute attr = attrWorklist.back(); 229 int &index = curAccessChain.back(); 230 ++index; 231 232 // Process the given attribute, which is guaranteed to be a container. 233 if (auto dict = attr.dyn_cast<DictionaryAttr>()) 234 result = processAttrs(index, make_second_range(dict.getValue())); 235 else 236 result = processAttrs(index, attr.cast<ArrayAttr>().getValue()); 237 } while (!attrWorklist.empty() && !result.wasInterrupted()); 238 return result; 239 } 240 241 /// Walk all of the uses, for any symbol, that are nested within the given 242 /// operation 'from', invoking the provided callback for each. This does not 243 /// traverse into any nested symbol tables, and will also only return uses on 244 /// 'from' if it does not also define a symbol table. 245 static Optional<WalkResult> walkSymbolUses( 246 Operation *from, 247 function_ref<WalkResult(SymbolTable::SymbolUse, ArrayRef<int>)> callback) { 248 // If from is not a symbol table, check for uses. A symbol table defines a new 249 // scope, so we can't walk the attributes from the symbol table op. 250 if (!from->hasTrait<OpTrait::SymbolTable>()) { 251 if (walkSymbolRefs(from, callback).wasInterrupted()) 252 return WalkResult::interrupt(); 253 } 254 255 SmallVector<Region *, 1> worklist; 256 worklist.reserve(from->getNumRegions()); 257 for (Region ®ion : from->getRegions()) 258 worklist.push_back(®ion); 259 260 while (!worklist.empty()) { 261 Region *region = worklist.pop_back_val(); 262 for (Block &block : *region) { 263 for (Operation &op : block) { 264 if (walkSymbolRefs(&op, callback).wasInterrupted()) 265 return WalkResult::interrupt(); 266 267 // If this operation has regions, and it as well as its dialect arent't 268 // registered then conservatively fail. The operation may define a 269 // symbol table, so we can't opaquely know if we should traverse to find 270 // nested uses. 271 if (isPotentiallyUnknownSymbolTable(&op)) 272 return llvm::None; 273 274 // If this op defines a new symbol table scope, we can't traverse. Any 275 // symbol references nested within 'op' are different semantically. 276 if (!op.hasTrait<OpTrait::SymbolTable>()) { 277 for (Region ®ion : op.getRegions()) 278 worklist.push_back(®ion); 279 } 280 } 281 } 282 } 283 return WalkResult::advance(); 284 } 285 286 /// Get an iterator range for all of the uses, for any symbol, that are nested 287 /// within the given operation 'from'. This does not traverse into any nested 288 /// symbol tables, and will also only return uses on 'from' if it does not 289 /// also define a symbol table. This is because we treat the region as the 290 /// boundary of the symbol table, and not the op itself. This function returns 291 /// None if there are any unknown operations that may potentially be symbol 292 /// tables. 293 auto SymbolTable::getSymbolUses(Operation *from) -> Optional<UseRange> { 294 std::vector<SymbolUse> uses; 295 Optional<WalkResult> result = 296 walkSymbolUses(from, [&](SymbolUse symbolUse, ArrayRef<int>) { 297 uses.push_back(symbolUse); 298 return WalkResult::advance(); 299 }); 300 return result ? Optional<UseRange>(std::move(uses)) : Optional<UseRange>(); 301 } 302 303 /// Get all of the uses of the given symbol that are nested within the given 304 /// operation 'from', invoking the provided callback for each. This does not 305 /// traverse into any nested symbol tables, and will also only return uses on 306 /// 'from' if it does not also define a symbol table. This is because we treat 307 /// the region as the boundary of the symbol table, and not the op itself. This 308 /// function returns None if there are any unknown operations that may 309 /// potentially be symbol tables. 310 auto SymbolTable::getSymbolUses(StringRef symbol, Operation *from) 311 -> Optional<UseRange> { 312 SymbolRefAttr symbolRefAttr = SymbolRefAttr::get(symbol, from->getContext()); 313 314 std::vector<SymbolUse> uses; 315 Optional<WalkResult> result = 316 walkSymbolUses(from, [&](SymbolUse symbolUse, ArrayRef<int>) { 317 if (symbolRefAttr == symbolUse.getSymbolRef()) 318 uses.push_back(symbolUse); 319 return WalkResult::advance(); 320 }); 321 return result ? Optional<UseRange>(std::move(uses)) : Optional<UseRange>(); 322 } 323 324 /// Return if the given symbol is known to have no uses that are nested within 325 /// the given operation 'from'. This does not traverse into any nested symbol 326 /// tables, and will also only count uses on 'from' if it does not also define 327 /// a symbol table. This is because we treat the region as the boundary of the 328 /// symbol table, and not the op itself. This function will also return false if 329 /// there are any unknown operations that may potentially be symbol tables. 330 bool SymbolTable::symbolKnownUseEmpty(StringRef symbol, Operation *from) { 331 SymbolRefAttr symbolRefAttr = SymbolRefAttr::get(symbol, from->getContext()); 332 333 // Walk all of the symbol uses looking for a reference to 'symbol'. 334 Optional<WalkResult> walkResult = 335 walkSymbolUses(from, [&](SymbolUse symbolUse, ArrayRef<int>) { 336 return symbolUse.getSymbolRef() == symbolRefAttr 337 ? WalkResult::interrupt() 338 : WalkResult::advance(); 339 }); 340 return walkResult && !walkResult->wasInterrupted(); 341 } 342 343 /// Rebuild the given attribute container after replacing all references to a 344 /// symbol with `newSymAttr`. 345 static Attribute rebuildAttrAfterRAUW(Attribute container, 346 ArrayRef<SmallVector<int, 1>> accesses, 347 SymbolRefAttr newSymAttr, 348 unsigned depth) { 349 // Given a range of Attributes, update the ones referred to by the given 350 // access chains to point to the new symbol attribute. 351 auto updateAttrs = [&](auto &&attrRange) { 352 auto attrBegin = std::begin(attrRange); 353 for (unsigned i = 0, e = accesses.size(); i != e;) { 354 ArrayRef<int> access = accesses[i]; 355 Attribute &attr = *std::next(attrBegin, access[depth]); 356 357 // Check to see if this is a leaf access, i.e. a SymbolRef. 358 if (access.size() == depth + 1) { 359 attr = newSymAttr; 360 ++i; 361 continue; 362 } 363 364 // Otherwise, this is a container. Collect all of the accesses for this 365 // index and recurse. The recursion here is bounded by the size of the 366 // largest access array. 367 auto nestedAccesses = 368 accesses.drop_front(i).take_while([&](ArrayRef<int> nextAccess) { 369 return nextAccess.size() > depth + 1 && 370 nextAccess[depth] == access[depth]; 371 }); 372 attr = rebuildAttrAfterRAUW(attr, nestedAccesses, newSymAttr, depth + 1); 373 374 // Skip over all of the accesses that refer to the nested container. 375 i += nestedAccesses.size(); 376 } 377 }; 378 379 if (auto dictAttr = container.dyn_cast<DictionaryAttr>()) { 380 auto newAttrs = llvm::to_vector<4>(dictAttr.getValue()); 381 updateAttrs(make_second_range(newAttrs)); 382 return DictionaryAttr::get(newAttrs, dictAttr.getContext()); 383 } 384 auto newAttrs = llvm::to_vector<4>(container.cast<ArrayAttr>().getValue()); 385 updateAttrs(newAttrs); 386 return ArrayAttr::get(newAttrs, container.getContext()); 387 } 388 389 /// Attempt to replace all uses of the given symbol 'oldSymbol' with the 390 /// provided symbol 'newSymbol' that are nested within the given operation 391 /// 'from'. This does not traverse into any nested symbol tables, and will 392 /// also only replace uses on 'from' if it does not also define a symbol 393 /// table. This is because we treat the region as the boundary of the symbol 394 /// table, and not the op itself. If there are any unknown operations that may 395 /// potentially be symbol tables, no uses are replaced and failure is returned. 396 LogicalResult SymbolTable::replaceAllSymbolUses(StringRef oldSymbol, 397 StringRef newSymbol, 398 Operation *from) { 399 SymbolRefAttr oldAttr = SymbolRefAttr::get(oldSymbol, from->getContext()); 400 SymbolRefAttr newSymAttr = SymbolRefAttr::get(newSymbol, from->getContext()); 401 402 // A collection of operations along with their new attribute dictionary. 403 std::vector<std::pair<Operation *, DictionaryAttr>> updatedAttrDicts; 404 405 // The current operation, and its old symbol access chains, being processed. 406 Operation *curOp = nullptr; 407 SmallVector<SmallVector<int, 1>, 1> accessChains; 408 409 // Generate a new attribute dictionary for the current operation by replacing 410 // references to the old symbol. 411 auto generateNewAttrDict = [&] { 412 auto newAttrDict = 413 rebuildAttrAfterRAUW(curOp->getAttrList().getDictionary(), accessChains, 414 newSymAttr, /*depth=*/0); 415 return newAttrDict.cast<DictionaryAttr>(); 416 }; 417 418 // Walk the symbol uses collecting uses of the old symbol. 419 auto walkFn = [&](SymbolTable::SymbolUse symbolUse, 420 ArrayRef<int> accessChain) { 421 if (symbolUse.getSymbolRef() != oldAttr) 422 return WalkResult::advance(); 423 424 // If there was a previous operation, generate a new attribute dict for it. 425 // This means that we've finished processing the current operation, so 426 // generate a new dictionary for it. 427 if (curOp && symbolUse.getUser() != curOp) { 428 updatedAttrDicts.push_back({curOp, generateNewAttrDict()}); 429 accessChains.clear(); 430 } 431 432 // Record this access. 433 curOp = symbolUse.getUser(); 434 accessChains.push_back(llvm::to_vector<1>(accessChain)); 435 return WalkResult::advance(); 436 }; 437 if (!walkSymbolUses(from, walkFn)) 438 return failure(); 439 440 // Update the attribute dictionaries as necessary. 441 for (auto &it : updatedAttrDicts) 442 it.first->setAttrs(it.second); 443 444 // Check to see if we have a dangling op that needs to be processed. 445 if (curOp) 446 curOp->setAttrs(generateNewAttrDict()); 447 448 return success(); 449 } 450