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