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