Skip to content

Commit 02e1ef5

Browse files
Add SymbolTable::renameToUnique.
1 parent eb68b4f commit 02e1ef5

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

mlir/include/mlir/IR/SymbolTable.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,15 @@ class SymbolTable {
6363
LogicalResult rename(StringAttr from, StringRef to);
6464
LogicalResult rename(Operation *op, StringRef to);
6565

66+
/// Renames the given op or the op refered to by the given name to the a name
67+
/// that is unique within this and the provided other symbol tables and
68+
/// updates the symbol table and all usages of the symbol accordingly. Returns
69+
/// the new name or failure if the renaming fails.
70+
FailureOr<StringAttr> renameToUnique(StringAttr from,
71+
ArrayRef<SymbolTable *> others);
72+
FailureOr<StringAttr> renameToUnique(Operation *op,
73+
ArrayRef<SymbolTable *> others);
74+
6675
/// Return the name of the attribute used for symbol names.
6776
static StringRef getSymbolAttrName() { return "sym_name"; }
6877

mlir/lib/IR/SymbolTable.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,39 @@ LogicalResult SymbolTable::rename(Operation *op, StringRef to) {
258258
return rename(op, toAttr);
259259
}
260260

261+
FailureOr<StringAttr>
262+
SymbolTable::renameToUnique(StringAttr oldName,
263+
ArrayRef<SymbolTable *> others) {
264+
265+
// Determine new name that is unique in all symbol tables.
266+
StringAttr newName;
267+
{
268+
MLIRContext *context = oldName.getContext();
269+
SmallString<64> prefix = oldName.getValue();
270+
int uniqueId = 0;
271+
prefix.push_back('_');
272+
while (true) {
273+
newName = StringAttr::get(context, prefix + Twine(uniqueId++));
274+
auto lookupNewName = [&](SymbolTable *st) { return st->lookup(newName); };
275+
if (!lookupNewName(this) && llvm::none_of(others, lookupNewName)) {
276+
break;
277+
}
278+
}
279+
}
280+
281+
// Apply renaming.
282+
if (failed(rename(oldName, newName)))
283+
return failure();
284+
return newName;
285+
}
286+
287+
FailureOr<StringAttr>
288+
SymbolTable::renameToUnique(Operation *op, ArrayRef<SymbolTable *> others) {
289+
StringAttr from = getNameIfSymbol(op);
290+
assert(from && "expected valid 'name' attribute");
291+
return renameToUnique(from, others);
292+
}
293+
261294
/// Returns the name of the given symbol operation.
262295
StringAttr SymbolTable::getSymbolName(Operation *symbol) {
263296
StringAttr name = getNameIfSymbol(symbol);

0 commit comments

Comments
 (0)