# Best algorithm for sequencing reducible control flow graph

I have a reducible control flow graph with only natural loops, produced from a simple DSL. Every node keeps a list of successors and a list of predecessors. I need to make a sequence of nodes out of this CFG with following properties:

1. All predecessors of a block are located before this block, with the exception of backward edges of loops. This implies that all dominators of a block are located before this block.
2. All blocks that are part of the same loop are contiguous, i.e., there is no non-loop block between two loop blocks.

What would be the most efficient algorithm to produce such a sequence?

For illustration consider following CFG (left) with desired output (right). CFG has been produced from a DSL which is roughly equivalent to pseudocode:

    for(; a && b; c++) {
if (d) {
dostuff1();
} else {
dostuff2();
}
dostuff3();
}
dostuff4();


Here is also CFG itself in python:

from collections import defaultdict

class Node:
def __init__(self, id, name):
self.id = id
self.name = name
self.succ = []

class Graph:
def __init__(self):
self.graph = defaultdict(Node)

self.graph[node.id] = node

self.graph[uid].succ.append(self.graph[vid])

g = Graph()