diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp --- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp +++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp @@ -360,21 +360,28 @@ } } -// TODO: implement an iterative version -static void topologicalSortImpl(llvm::SetVector &blocks, Block *b) { - blocks.insert(b); - for (Block *bb : b->getSuccessors()) { - if (blocks.count(bb) == 0) - topologicalSortImpl(blocks, bb); +static void topologicalSortImpl(llvm::SetVector &blocks, Block *root) { + llvm::SmallVector stack; + stack.push_back(root); + + while (!stack.empty()) { + Block *b = std::move(stack.back()); + stack.pop_back(); + blocks.insert(b); + + for (Block *succ : b->getSuccessors()) { + if (blocks.count(succ) == 0) + stack.push_back(succ); + } } } /// Sort function blocks topologically. template static llvm::SetVector topologicalSort(T &f) { - // For each blocks that has not been visited yet (i.e. that has no - // predecessors), add it to the list and traverse its successors in DFS - // preorder. + // For each block that has not been visited yet (i.e. that has no + // predecessors), add it to the list and traverse its successors iteratively + // in DFS preorder. llvm::SetVector blocks; for (Block &b : f) { if (blocks.count(&b) == 0)