Here comes a stupid question :) If I understand correctly we are adding one more ASTConsumer to the list of Consumers, i.e. we are not replacing the "normal" consumer with the "optimized" consumer. So I fail to understand how adding this new consumer fixes the problems of the other consumer? I'd be happy to read more about the implementation if there are resources you could point me to.
The MultiplexConsumer runs each consumers callbacks in the order they are added. So this consumers HandleTranslationUnit callback will be executed before the FinderASTConsumer runs its HandleTranslationUnit callback(The function that actually does the AST matching. So by modifying the ASTContext traversal scope in this HandleTranslationUnit callback, the results are visible when the Finder comes to do its matching.
Also part of this implementation was taken from clangd which uses a somewhat similar approach to only run tidy checks that originate in the main file https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clangd/ParsedAST.cpp#L73
I love an idea, but i'm afraid that it may impact checks that build some internal database, like misc-confusable-identifiers or misc-unused-using-decls.
Probably some of those checks would need to be rewrite to use some own visitor. And probably we should have access to that Cache (function that check if location should be ignored) from a check code, in such case in some cases it could be used instead of re-inventing a wheal.