This reverts r214338 (except the test file) and replaces it with a more general algorithm. llvm-svn: 214485