[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.

git-svn-id: https://llvm.org/svn/llvm-project/lld/trunk@176842 91177308-0d34-0410-b5e6-96231b3b80d8