[clang] [clang] Speed up Decl::getASTContext() (PR #226612)

Nico Weber via cfe-commits cfe-commits at lists.llvm.org
Sun Oct 4 15:49:52 PDT 2026


================
@@ -548,7 +548,15 @@ TranslationUnitDecl *Decl::getTranslationUnitDecl() {
 }
 
 ASTContext &Decl::getASTContext() const {
-  return getTranslationUnitDecl()->getASTContext();
+  if (const auto *TUD = dyn_cast<TranslationUnitDecl>(this))
+    return TUD->getASTContext();
----------------
nico wrote:

Ah, that doesn't build, I need to get a DC from somewhere, and a TranslationUnitDecl has a nullptr DC 😅 I did measure this:

```
ASTContext &Decl::getASTContext() const {
  // This is called a lot, e.g. for every attribute lookup. Only walk up to the
  // TranslationUnitDecl once per DeclContext.
  const DeclContext *DC = getDeclContext();
  if (LLVM_LIKELY(DC && DC->CachedASTContext))
    return *DC->CachedASTContext;

  if (const auto *TUD = dyn_cast<TranslationUnitDecl>(this))
    return TUD->getASTContext();

  DC->CachedASTContext = &getTranslationUnitDecl()->getASTContext();
  return *DC->CachedASTContext;
}
```

It's a line of code more. It's one instruction less at least on aarch64. It does retire 0.3% fewer instructions, but takes a little more wall time (possibly due to the dependent load).

Happy to post disassembly or more detailed numbers, but I think I like the code as-is the most.

https://github.com/llvm/llvm-project/pull/226612


More information about the cfe-commits mailing list