[CIR] Implement static variable initialization with guarded init #2015
+1,340
−1,067
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Add support for C++ static local variables with non-trivial destructors
and dynamic initialization. This implements the guarded initialization
pattern required by the C++ standard for one-time initialization.
Implementation Details
New CIR Operation: GuardedInitOp
cir.guarded.initinit_regionfor initialization codethread_safe,perform_initCIRGen Changes:
emitCXXGuardedInit()andemitCXXGlobalVarDeclInit()emitGuardedInit()method for ABI abstraction_ZGVZ{function}E{variable}Lowering Implementation:
if (!guard) { init_code; guard = 1; }Verifier:
Design Rationale
Follows ClangIR's deferred lowering principle:
Copies CodeGen structure from:
clang/lib/CodeGen/CGDecl.cpp:353-402(AddInitializerToStaticVarDecl)clang/lib/CodeGen/CGDeclCXX.cpp:176-232(EmitCXXGlobalVarDeclInit)clang/lib/CodeGen/ItaniumCXXABI.cpp:2691-2906(EmitGuardedInit)Testing
New Test:
clang/test/CIR/CodeGen/static-var-init.cppCrash Tests Fixed:
static-var-guarded-init.cpp- Static with non-trivial destructorstatic-var-dyn-cast.cpp- Static with template constructorSupported Cases
✅ Static variables with non-trivial destructors
✅ Static variables with dynamic initialization
✅ Static variables with constant init + non-trivial destructor
✅ Reference static variables
⏳ Thread-safe guards (NYI, marked for future work)
Itanium C++ ABI Compliance
Implements Section 3.3.2 "One-time construction API":
Code Style
All code follows ClangIR standards:
Future Work
Thread-safe guards (Phase 2):
Potential optimizations: