Take advantage of predictable structure of graph to avoid DFS for topo sort

This is a first step toward avoiding having a separate function for topological
sort so we can make it very fast.