[Pass][Layout] Make algorithm not n^2.

This reduces the time spent in this function while linking ASTMatchersTests
from %43 to %2.4 of total link time.