Repository navigation
LLVM IR backend (initial pass) - #221
Open
SamuelMarks wants to merge 9 commits into
Open
SamuelMarks wants to merge 9 commits into
SamuelMarks wants to merge 9 commits into
Conversation
… C++ tests Comprehensive implementation across all planned backend phases: - Test suite: Replaced Python test runners with C++ test executables (build config, driver flag, fuzz). - Architecture & Scoping: Implemented scoped local symbol table for alloca tracking, LValue/RValue semantics with implicit loads, and dynamic TargetTriple/DataLayout construction from EDG target macros. - Type System & Layout: Lowered primitives (bool, complex, float variants), empty struct padding, union lowering with bitcast access, bitfield packing/masking, and arrays/VLAs/pointer-to-member types. - Global State & Linkage: Added linkage mappings (weak, linkonce, comdat, TLS), recursive constant evaluation for static initializers, and dynamic initializers registered in llvm.global_ctors/dtors. - Control Flow & Statements: Implemented loops (while, do, for), switches, case/default handling, and jumps (break, continue, goto). - Expressions & Operations: Implemented GEP memory references (arrays, struct fields), function calls (direct, indirect, vararg, sret), full arithmetic/logic/comparisons, casts, ternary operators, and restrict/noalias qualification. - ABI & Attributes: Applied function and parameter attributes (NoReturn, inline hints, ByVal, SExt/ZExt), vtable/RTTI support.
…ted gotos, and test suite Add support for exception handling, GNU inline assembly, computed gotos, and extended constants in the LLVM IR generator, alongside automated tests and CI coverage: - Exception Handling: Added Itanium ABI personality routine setup (__gxx_personality_v0), landing pads, throw/rethrow runtime calls (__cxa_allocate_exception, __cxa_throw, __cxa_rethrow), catch blocks (__cxa_begin_catch, __cxa_end_catch), and invoke instructions for calls. - Inline Assembly: Implemented stmk_asm lowering to llvm::InlineAsm with operand constraint string translation, register clobber handling, and argument forwarding. - Computed Gotos: Implemented stmk_assigned_goto using llvm::IndirectBrInst dispatching to address-taken labels, with BlockAddress evaluation. - Constants: Added fp_to_hex_constant_string evaluation for float/double/long double (including inf/nan), UTF-16/UTF-32 string constant arrays, and label address constants. - Testing & CI: Added CTest configurations for EH, inline assembly, constants, and computed gotos, test coverage script, and GitHub Actions workflow.
… support, and verification Enhance LLVM backend code generation and validation with typeinfo integration, extended inline assembly handling, opaque pointer modernization, and verification: - Target Triple & Lifecycles: Configured target triple derivation across macOS, Windows, and Linux targets; ensured thorough state cleanup in llvm_gen_be_terminate. - Verifier Integration: Added function verification pass via llvm::verifyFunction with source position mapping on diagnostic failure. - Exception Handling & RTTI: Lowered typeinfo references using EDG mangled names (__cxa_throw typeinfo/dtor args) and added catch clause dispatch matching via llvm.eh.typeid.for. - Inline Assembly: Supported multiple outputs via struct returns, indirect memory operand constraints (*), and value extraction to lvalue destinations. - Type System & Opaque Pointers: Streamlined GEP and pointer bitcasts for opaque pointer support; added explicit float/complex kind mappings (bfloat16, fp16, fp80, fp128, etc.). - Testing & Coverage: Added multi-output inline asm test, lit test cases for for-loops and opaque pointers, orchestrator/verifier test targets, and coverage validation scripts.
…t layouts, and refine codegen Decouple LLVM backend configuration from C-generator assumptions, adopt runtime target configuration parameters, and resolve memory paging and terminator handling in the LLVM IR generator: - Target Configuration & Environment: Replaced static compile-time TARG_* macros with dynamic targ_* variables in DataLayout and type generation; decoupled BACK_END_IS_LLVM_GEN_BE from C-backend IL lowering and layout macros in front-end headers and lowering routines (host_envir.h, target.h, il_alloc.c, lower_c99.c, etc.). - Back-end Isolation: Guarded back_end() definition in c_gen_be.c and cp_gen_be.c when BACK_END_IS_LLVM_GEN_BE is active; upgraded C++ standard to C++17 in build configs. - Scope & Memory Management: Added get_scope_for_routine_definition with IL memory region paging (read_memory_region) to ensure routine definitions are available during code generation. - Control Flow & Terminators: Ensured conditional branch conditions are typed as i1; added terminator fallbacks to unreachable/ret void to guarantee block termination prior to module and function verification. - Inline Assembly & Expressions: Refactored assembly constraint string parsing, memory operand indirection, and register clobber lookups; corrected AST expression operator kinds and exception throw dynamic init handling. - Test Suite: Extended assembly, constant, and exception handling tests covering primitive and pointer catches, mixed asm outputs, float variants, and complex types.
Collaborator
|
Thanks, I've opened #245 for a central discussion of the topic of some kind of "native IR" back end for the EDG compiler project. |
…on, and pass pipeline Implement target calling convention ABIs (AAPCS64, SysV x86-64, Win64), DWARF debug metadata emission, machine code/assembly generation, optimization pipelines, and centralized error handling with test coverage: - Target Calling Conventions: Implemented ABI argument and return value classification for SysV x86-64, AAPCS64, and Win64 calling conventions, supporting direct, indirect, sret, coercion, and register attributes. - DWARF Debug Information: Added DIBuilder lifecycle management, compile unit setup, subprogram declarations, lexical block scopes, debug locations on instructions, and type metadata for primitives, pointers, and variables. - Code Generation & Emission: Integrated LLVM TargetMachine code generation to emit object files (.o) and assembly (.s); hooked into cpfe CLI flags (--gen_llvm_file_name, --llvm_opt_level, etc.). - Optimization Pipeline: Integrated LLVM new PassManager supporting optimization levels O0 through O3, Os, Oz, along with loop and SLP vectorization passes. - Error Handling & Modularization: Added centralized error subsystem with structured error contexts (llvm_gen_be_error_t); decoupled internal declarations into dedicated headers (llvm_gen_be_type.h, llvm_gen_be_expr.h, llvm_gen_be_const.h). - Test Infrastructure: Added unit tests for ABIs, DWARF metadata, pass pipelines, fault injection, and codegen, along with lit tests, GCC torture runner, and STL header compilation validation.
…ARF scopes, and update test suite Enforce uniform error propagation via [[nodiscard]] llvm_gen_be_error_t, annotate backend routines with noexcept, wire DWARF debug scopes and variable declarations into function lowering, and update backend tests: - Error Propagation & noexcept: Decorated llvm_gen_be_error_t with [[nodiscard]] at the type definition, eliminating redundant per-function attributes while guaranteeing mandatory error checking; annotated backend APIs with noexcept and migrated routines (get_llvm_type, build_data_layout, get_typeinfo_global, llvm_gen_be, back_end) to return status codes via out-parameters. - Diagnostic Context: Threaded persistent error context via be_state->err_context in code generation and target machine emission instead of localized stack buffers. - DWARF Debug Information: Integrated DI subprograms and lexical block scopes into routine lowering; added llvm.dbg.declare emission for routine parameters and non-static local variables with source position mapping. - Frontend Integration: Guarded back_end() in c_gen_be.h and cp_gen_be.h when BACK_END_IS_LLVM_GEN_BE is active, and hooked llvm_gen_be_cleanup into fe_wrapup.c. - Test Suite & Targets: Added C++17 and LLVM link dependencies to orchestrator and verifier test targets in CMake; updated fault injection and type unit tests to reflect out-parameter signatures; aligned lit test bitfield and datalayout expectations.
SamuelMarks
marked this pull request as ready for review
October 9, 2026 14:50
…ics, and revamp test suite
Modularize the C++ object model (vtables/RTTI), exception handling, inline
assembly, coroutines, and target ABI subsystems, implement atomic operations
and doc-coverage verification, and replace legacy test scripts with an exhaustive
C++ test suite:
- C++ Object Model & RTTI: Factored vtable emission and virtual method dispatch
into dedicated modules (llvm_gen_be_vtable.{h,cpp}) and RTTI descriptor generation
into llvm_gen_be_rtti.{h,cpp}, supporting Itanium and MSVC layouts with thunk generation.
- Exception Handling: Separated landing pads, cleanup unwinding, and personality
routines into llvm_gen_be_eh.{h,cpp} with full Itanium and MSVC funclet support.
- Target ABIs & Assembly: Added RISC-V 64-bit ABI classification (llvm_gen_be_abi_riscv64.{h,cpp}),
refined Win64 parameter passing, and modularized GNU inline assembly handling
into llvm_gen_be_asm.{h,cpp} with constraint parsing and asm-goto support.
- Modern C++ Features & Atomics: Implemented C++20 coroutine intrinsics and pass
lowering (llvm_gen_be_coro.{h,cpp}) and lowered C11/C++20 atomic builtins
(__atomic_thread_fence, __atomic_fetch_*, __atomic_compare_exchange).
- Code Quality & Documentation: Added check_doc_coverage.py and CMake target to
enforce 100% Doxygen coverage on backend types, fields, and functions; instrumented
coverage flags via EDG_LLVM_BE_COVERAGE.
- Test Infrastructure Revamp: Consolidated and replaced fragmented shell and unit tests
under tests/llvm_ir_backend_tests/ with dedicated, self-contained C++ unit test
executables (test_llvm_*) covering types, expressions, control flow, ABIs, EH,
inline asm, atomics, debug info, optimization pipelines, and differential fuzzing.
…MP, PGO/LTO pipelines, and expanded test coverage
Implement multi-target calling convention ABIs across eight additional architectures,
member pointer representation for Itanium and MSVC models, OpenMP lowering, PGO/LTO
compilation pipelines, and extensive test suites:
- Multi-Target Calling Conventions: Added complete ABI lowering implementations for
ARM32, LoongArch64, MIPS, PPC64, SystemZ (s390x), SPARC, WebAssembly, and x86-32
alongside classification improvements for AAPCS64, RISC-V 64, SysV x86-64, and Win64.
- Member Pointers: Implemented lowering for pointers to member functions and data
(llvm_gen_be_ptrmem.{h,cpp}) supporting Itanium dual-field representations and MSVC
single, multiple, and virtual inheritance layouts.
- OpenMP Runtime Lowering: Added OpenMP 5.x construct emission (llvm_gen_be_omp.{h,cpp})
interfacing with libomp/kmpc runtime primitives for parallel regions, worksharing loops,
critical sections, and atomic constructs.
- Driver, PGO, and LTO Pipelines: Modularized backend driver orchestration
(llvm_gen_be_driver.{h,cpp}) with CLI integration for Profile-Guided Optimization
(PGO generation/use), ThinLTO/LTO bitcode emission, and sanitizer instrumentation.
- Expression, Statement, & Model Lowering: Substantially expanded expression evaluation,
statement lowerings (switch jump tables, indirect branches, cleanup blocks), TLS
and static initializers, complex vtable/thunk layouts, and MSVC RTTI structures.
- Test Suite Expansion: Added unit tests for declarations, error handling, LTO,
modules, MSVC inline assembly, OpenMP, and PGO, accompanied by comprehensive lit
integration test suites and documentation coverage verification.
* Implement ABI, builtins, RTTI, EH, and dtor subsystems in GCC backend
Expand the native libgccjit backend (gcc_gen_be) with comprehensive language
feature lowering, runtime support, lexical scoping, and subsystem test coverage:
- ABI, Calling Conventions, and Attributes (src/gcc_gen_be_abi.[ch]):
- Implement gcc_gen_be_apply_function_attributes, gcc_gen_be_apply_struct_attributes,
and gcc_gen_be_apply_variable_attributes for packing, alignment, TLS, and linkage.
- Builtins and Intrinsics (src/gcc_gen_be_builtin.[ch]):
- Add gcc_gen_be_lower_builtin_call using libgccjit builtin function lookup.
- RTTI, VTables, and Thunks (src/gcc_gen_be_rtti.[ch]):
- Add vtable and VTT emission (gcc_gen_be_emit_vtable, gcc_gen_be_emit_vtt).
- Generate virtual method dispatch thunks (gcc_gen_be_emit_thunk).
- Implement dynamic_cast and typeid lowering with type_info descriptor emission.
- Exception Handling and RAII Destructors (src/gcc_gen_be_eh.[ch], src/gcc_gen_be_dtor.[ch]):
- Declare standard EH symbols (__cxa_throw, etc.) and lower throw expressions.
- Implement __cxa_atexit and __cxa_thread_atexit registration for global and TLS destructors.
- Lexical Scopes and Control Flow (src/gcc_gen_be_context.[ch], src/gcc_gen_be_stmt.[ch], src/gcc_gen_be_cache.[ch]):
- Introduce lexical scope push/pop stacks to support variable shadowing.
- Add stack save/restore helpers for VLA allocation.
- Expand cache types for local static guard variables and string constants.
- Dynamic Symbol Loader (src/gcc_gen_be_lib_loader.[ch]):
- Dynamically load modern libgccjit symbols for union constructors, bitcasts,
vector rvalues, builtin retrieval, and link sections.
- CLI and Driver Integration (src/cmd_line.[ch], src/gcc_gen_be_main.c):
- Register --gcc_gen_be and -c command-line options.
- Lower function scopes with lexical scope tracking and default terminator emission.
- Subsystem Unit Tests and Coverage (tests/gcc_be/, dev_tools/):
- Add subsystem test suites for ABI, builtins, debug, dtor, main, RTTI, and statements.
- Update CMake targets and end-to-end backend test fixtures.
- Add scripts for verifying backend test and documentation coverage.
- Remove deprecated dev-init.py.
* Implement subsystem unit tests, dynamic caching, and context stacks in GCC backend
Expand the native libgccjit backend (gcc_gen_be) with dynamic memory management,
subsystem diagnostics, modern libgccjit symbol loading, and a modular unit test suite:
- Context and Control-Flow Stacks (gcc_gen_be_context.[ch]):
- Replace static stack arrays with dynamically resizing stacks for break, continue,
switch exit, nested blocks, and RAII cleanup handlers.
- Introduce gcc_gen_be_push_block() / gcc_gen_be_pop_block() for nested scope tracking.
- Add thread-ownership verification via gcc_gen_be_check_thread_safety().
- Cache Resizing and Metrics (gcc_gen_be_cache.[ch]):
- Convert fixed-size hash buckets in be_cache_map to dynamically resizing tables.
- Track cache lookup metrics (hits, misses) retrievable via cache_get_metrics().
- Add GCC_GEN_BE_CACHE_SWITCH_CASE for jump target deduplication.
- Diagnostic Integration and Extended Errors (gcc_gen_be_error.[ch]):
- Introduce gcc_gen_be_report_diagnostic() bridging backend errors with EDG's
diagnostic counters and f_error.
- Add detailed error codes for EH, unresolved symbols, vtables, RTTI, asm constraints,
and DWARF emissions.
- Declarations and Expressions (gcc_gen_be_decl.[ch], gcc_gen_be_expr.[ch]):
- Separate global vs local variable lowering (gcc_gen_be_lower_global_variable_decl
and gcc_gen_be_lower_local_variable_decl).
- Add gcc_gen_be_lower_constant_rvalue() with aggregate initializer lowering.
- Dynamic Symbol Loader (gcc_gen_be_lib_loader.[ch]):
- Dynamically load optional modern libgccjit symbols (TLS models, vector types,
extended asm goto, function/variable attributes, struct/array constructors).
- Namespaces and Header Structuring:
- Standardize C++ namespaces (BEGIN_EDG_NAMESPACE / END_EDG_NAMESPACE) across
backend headers.
- Modular Unit Test Suite (tests/gcc_be/):
- Add standalone unit test suites for all backend subsystems: test_gcc_be_cache,
test_gcc_be_context, test_gcc_be_decl, test_gcc_be_errors, test_gcc_be_expr,
test_gcc_be_lib_loader, test_gcc_be_stmt, and test_gcc_be_type.
- Update tests/gcc_be/CMakeLists.txt to build and register subsystem tests.
- Tracking and Documentation:
- Add TODO_PLAN.md documenting architecture, test coverage mandates, and roadmap.
* Enforce universal error codes, percolation, and noexcept across GCC backend
Enforce strict error handling invariants, non-discardable return codes,
and noexcept specification across all GCC backend (gcc_gen_be) subsystems:
- Error infrastructure (gcc_gen_be_error.[ch]):
- Attach GCC_GEN_BE_NODISCARD directly to typedef enum gcc_gen_be_error_t
to ensure compiler-enforced return value checks across all backend APIs.
- Introduce GCC_GEN_BE_NOEXCEPT macro and add GCC_GEN_BE_ERROR_COMPILATION_FAILED.
- Refactor gcc_gen_be_error_string() to take an out-parameter and return
gcc_gen_be_error_t.
- Universal error code returns and pointer out-parameters:
- Update context getters/setters (gcc_gen_be_get_state, gcc_gen_be_get_context,
gcc_gen_be_set_context, gcc_gen_be_get_current_block, gcc_gen_be_set_current_block).
- Update helper constructors such as gcc_gen_be_get_global_ctor_block().
- Convert driver entry points gcc_gen_be() and back_end() to return
gcc_gen_be_error_t.
- Strict error propagation:
- Percolate all internal fallible operations (cache lookups/inserts/clears,
type and expression lowering, location queries, memory allocations) via
GCC_GEN_BE_CHECK().
- Eliminate ignored return values, unhandled fallback paths, and silent errors.
- Universal noexcept annotation:
- Decorate all backend function declarations and definitions across
gcc_gen_be_cache, gcc_gen_be_context, gcc_gen_be_decl, gcc_gen_be_error,
gcc_gen_be_expr, gcc_gen_be_lib_loader, gcc_gen_be_location,
gcc_gen_be_main, gcc_gen_be_stmt, and gcc_gen_be_type with GCC_GEN_BE_NOEXCEPT.
* Modularize GCC backend into dedicated subsystems and expand CLI options
Decompose monolithic gcc_gen_be.c and gcc_gen_be.h into modular,
decoupled backend subsystems to improve maintainability, testability,
and separation of concerns:
- gcc_gen_be_cache: hash map memoization for types, variables, functions,
and fields.
- gcc_gen_be_context: context lifecycle, option configuration, and active
basic block tracking.
- gcc_gen_be_decl: declaration lowering for globals, local variables, and
parameters.
- gcc_gen_be_error: centralized backend error handling and diagnostics.
- gcc_gen_be_expr: expression lowering for operators, calls, and accessors.
- gcc_gen_be_lib_loader: cross-platform dynamic loader for libgccjit.
- gcc_gen_be_location: mapping frontend source locations to JIT locations.
- gcc_gen_be_main: driver entry points and compilation invocation.
- gcc_gen_be_stmt: statement and CFG control-flow lowering.
- gcc_gen_be_type: type system lowering across scalar, aggregate, pointer,
and function types.
Additionally:
- Support GCC backend CLI optimization and debug flags in cmd_line.[ch]
(-O0..-O3, -Os, -Ofast, -g, -fPIC, -fPIE, dump flags).
- Update src/CMakeLists.txt for the new modular sources and coverage flags.
- Expand tests/gcc_be/ suite and modernize coverage verification script
to inspect all gcc_gen_be_*.c compilation units.
* GCC [libgccjit] backend (initial pass)
* Update LICENSE.txt for clarity []
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
PR: Native LLVM IR Generation Backend, Target ABIs, DWARF Debug Info, Optimization Pipeline & Verification Suite
Metadata
llvm_backendmain(e3e8268d32dc63147ca431f28f2f3cdf1789909c)c3770edf17..7fa91abfbf)feat), Architecture & Refactoring (refactor), Infrastructure & CI (ci), Tests (test), Documentation (docs)Table of Contents
[[nodiscard]]Error Enumerationnoexcept& Strict-fno-exceptionstests/llvm_ir_backend_tests/)tests/lit/llvm/)tests/test_llvm_*.sh)1. Executive Summary
This pull request implements a native LLVM Intermediate Representation (IR) generation backend (
llvm_gen_be) for the EDG C/C++ Front End (cpfe).Prior to this pull request, the EDG compiler in this repository lowered its internal Intermediate Language (IL) primarily through C source code generation (
c_gen_be) or C++ source code generation (cp_gen_be), relying on downstream compilers to emit machine code. This pull request introduces direct, high-fidelity lowering from EDG IL directly into LLVM IR, enablingcpfeto interface natively with the LLVM ecosystem without the intermediate textual C emission step.Key Capabilities Introduced
.ll), binary bitcode (.bc), native target assembly (.s), and relocatable object files (.o/.obj) directly via LLVM'sTargetMachineand MC layers.__gxx_personality_v0), landing pads, exception allocation/throw (__cxa_allocate_exception,__cxa_throw), rethrow, typeid matching (llvm.eh.typeid.for), and RTTI dispatch.INTEGER,SSE,SSEUP,X87,X87UP,COMPLEX_X87, andMEMORY, struct splitting, andsret).sret).sret).DIBuilderto emit DWARF metadata (DICompileUnit,DISubprogram,DILexicalBlock,DILocation, primitive/compositeDITypedescriptors, and@llvm.dbg.declare/@llvm.dbg.valuefor variables).PassBuilder) with full support for optimization levelsO0,O1,O2,O3,Os, andOz, function inlining, and SLP/Loop vectorization.stmk_asm) intollvm::InlineAsm, supporting operand constraint strings, memory operands (*), register clobber lists, and multi-output struct extractions viaextractvalue.-fno-exceptions.noexceptdecoration across 100% of backend functions.[[nodiscard]] llvm_gen_be_error_terror enumeration with mandatory bubbling (0 ignored error returns).new (std::nothrow)andout_of_memoryerror handling.Doxyfile.llvm_be)..github/workflows/llvm_be_coverage.yml).2. Background & Motivation
The EDG front end parses C and C++ source code into a detailed, type-annotated abstract Intermediate Language (IL). Historically, EDG deployments frequently translated this IL back into high-level C code, which was subsequently compiled with a host C compiler (such as GCC, Clang, or MSVC). While portable, this model introduces several drawbacks:
noalias/restrict), and exact calling conventions.By implementing a direct LLVM IR generator inside EDG:
cpfe, turning EDG into a fully self-contained, end-to-end compiler.3. Architectural Overview & Subsystem Deep Dive
The backend architecture is located under
src/llvm_gen_be*and organized into dedicated, modular subsystems:3.1 Backend Driver & Lifecycle Management
llvm_gen_be(): Main entry point called bycfe.cduring frontend execution.back_end(): Standard EDG backend hook, guarded inc_gen_be.h/cp_gen_be.hand routed tollvm_gen_be().llvm_gen_be_cleanup(): Clean teardown called fromfe_wrapup.c, releasing AST maps, symbol tables, and LLVM context structures.LLVMBackendState):Encapsulates the
llvm::LLVMContext,llvm::Module,llvm::IRBuilder<>,llvm_gen_be_debug_state_t, symbol lookup tables, type cache, VLA stack markers, and landing pad stacks.Constructs target-accurate
DataLayoutstrings at runtime using EDG target configuration parameters (targ_char_bit,targ_sizeof_pointer,targ_sizeof_int,targ_sizeof_double, etc.), avoiding hardcoded host assumptions.Automatically executes
llvm::verifyModule()andllvm::verifyFunction(), mapping verification diagnostics to EDG internal diagnostics.3.2 Robust Error Subsystem & Non-Throwing Invariants
enum class [[nodiscard]] llvm_gen_be_error_t : intdefines:ok: Success.invalid_argument: Null pointer or invalid parameter passed.out_of_memory: Allocation failed.unsupported_type,unsupported_expr,unsupported_stmt: Unimplemented or unexpected IL node.abi_classification_failed: Calling convention mismatch.di_metadata_failure: Debug metadata generation error.pass_pipeline_failure: Optimization pass manager error.code_gen_failure: Machine code emission failure.verification_failure: LLVM IR verifier rejected module/function.io_error: Output stream failure.llvm_gen_be_error_context_t):Threaded directly through
be_state->err_context, storing the filename, line, column, and a 512-byte formatted diagnostic message.Functions return status codes and pass results via out-pointers (e.g.,
llvm_gen_be_error_t get_llvm_type(a_type_ptr edg_type, llvm::Type** out_type) noexcept), ensuring that every return code is checked at the call site.3.3 Type System Lowering & Memory Layout
i1(bool),i8,i16,i32,i64, andi128.half/fp16(fk_fp16,fk_float16),bfloat16(fk_std_bfloat16),float,double,x86_fp80, andfp128._Complex: Aggregate struct{ elem_ty, elem_ty }.Fully modernized for LLVM 15+ opaque pointer architecture using
llvm::PointerType::getUnqual(*be_state->context).[N x i8]) matching EDG field offsets (field->offset).llvm::StructType::create()).{ ptrdiff_t, ptrdiff_t }.ptrdiff_t.3.4 Constant Evaluation & Static Initializers
llvm::ConstantIntfor arbitrary bit-widths.fp_to_hex_constant_string(), correctly handling positive/negative zero, subnormals, infinities, and NaNs.ConstantDataArrayfor 8-bit strings, UTF-16 strings (uint16_t[]), and UTF-32 strings (uint32_t[]), placed in private global string constants (.str).llvm::BlockAddress::get(func, label_bb).llvm::ConstantStructandllvm::ConstantArrayinstances.3.5 Declaration & Global State Lowering
ExternalLinkage,InternalLinkage(static),LinkOnceODRLinkage(inline/templates),WeakAnyLinkage.GeneralDynamicTLSModel).__attribute__((section("...")))and visibility flags (Hidden,Protected,Default).NoReturn,AlwaysInline,NoInline,NoAlias(forrestrictpointers).get_scope_for_routine_definition()usingread_memory_region()to guarantee routine IL is paged into memory during backend generation.Registers initialization functions into
@llvm.global_ctorsand@llvm.global_dtorswith specified priority keys.3.6 Statement Lowering & Control Flow
stmk_expr), return statements (stmk_returnwith value or void), blocks (stmk_block) with scoped alloca allocations.be_state->break_blocksandbe_state->continue_blocks.llvm::SwitchInst, handling both individual case expressions and GNU case ranges (case low ... high:).llvm::IndirectBrInsttargeting address-taken label blocks.@llvm.stacksaveand@llvm.stackrestoreintrinsics at scope entry and exit.3.7 Expression Lowering & Operations
CreateLoademitted when evaluating an LValue in an RValue context; preservesvolatilequalifiers.icmp,fcmp).&&) and OR (||) lower to short-circuit conditional branches with resultllvm::PHINodes.?:): Lowered via conditional branches and PHI merging.eok_assign) by emitting@llvm.memcpycalls.lshr/ashr) byfield->bit_offsetand masks (and) with(1 << bit_size) - 1.3.8 Target Calling Convention ABIs
Implemented in dedicated modules for target-specific parameter passing and return rules:
src/llvm_gen_be_abi_sysv_x86_64.*):INTEGER,SSE,SSEUP,X87,X87UP,COMPLEX_X87, andMEMORY.i64ordouble).byval).sret) for types exceeding 16 bytes or classified asMEMORY.va_start,va_arg,va_copy,va_end).src/llvm_gen_be_abi_aapcs64.*):src/llvm_gen_be_abi_win64.*):va_startlowering.3.9 DWARF Debug Information Subsystem
llvm_gen_be_debug_state_tusingllvm::DIBuilder.DICompileUnitwith compile flags, host compiler version, and source filename.DISubprogramfor each function definition and maintains a scope stack (push_lexical_block,pop_lexical_block) emitting nestedDILexicalBlocks.DILocationmetadata to instructions matching EDGa_source_position.DIBasicType,DIDerivedType(pointers/const),DICompositeType(arrays, structs), and attaches@llvm.dbg.declarewithDILocalVariabledescriptors to stack allocas.3.10 Optimization Pipeline (LLVM New PassManager)
PassBuilderwithModulePassManager,FunctionPassManager, and analysis managers (LoopAnalysisManager,FunctionAnalysisManager,CGSCCAnalysisManager,ModuleAnalysisManager).llvm_opt_options_tsupporting levelsO0,O1,O2,O3,Os, andOz.3.11 Target Machine Code Generation & Multi-Format Emission
initialize_llvm_targets).emit_machine_code_to_file():.ll(viaraw_fd_ostream).bc(viaWriteBitcodeToFile).s(viaTargetMachine::addPassesToEmitFilewithCodeGenFileType::AssemblyFile).o/.obj(viaTargetMachine::addPassesToEmitFilewithCodeGenFileType::ObjectFile)3.12 C++ Exception Handling & RTTI Dispatch
__gxx_personality_v0).invokeinstructions for function calls inside active try-blocks, targeting exception landing pads.landingpadinstructions with typeinfo clauses and cleanup flags.llvm.eh.typeid.forand typeinfo comparisons.__cxa_allocate_exception,__cxa_throw,__cxa_rethrow,__cxa_begin_catch, and__cxa_end_catch.catch (...)(catch-all) andresumeinstructions for unhandled exceptions.3.13 GNU Inline Assembly Support
stmk_asmstatements tollvm::InlineAsm.*), and clobber lists (named_register_names).callinstructions to inline assembly objects withhasSideEffects = true.extractvalueinstructions.4. Front-End & Build System Integration
4.1 Command-Line Options & Driver Integration
Registered new CLI flags in
src/cmd_line.handsrc/cmd_line.c:--gen_llvm_file_name <file>: Emits textual LLVM IR (.ll).--gen_llvm_bc_file_name <file>: Emits LLVM binary bitcode (.bc).--gen_obj_file_name <file>: Emits native machine object file (.o/.obj).--gen_asm_file_name <file>: Emits native assembly file (.s).Hooked backend execution in
src/cfe.c:Hooked memory cleanup in
src/fe_wrapup.c:4.2 Decoupling Static C-Backend Macros & Dynamic Target Layouts
src/defines.handsrc/host_envir.hto defineBACK_END_IS_LLVM_GEN_BEand decouple backend configurations fromBACK_END_IS_C_GEN_BEassumptions.back_end()insrc/c_gen_be.c,src/c_gen_be.h,src/cp_gen_be.c, andsrc/cp_gen_be.hwhenBACK_END_IS_LLVM_GEN_BEis active, allowing clean linking without symbol collisions.src/targ_def.handsrc/lower_il.c.4.3 CMake Build Configuration & LLVM Discovery
set(CMAKE_CXX_STANDARD 17)) acrosssrc/CMakeLists.txtanddev_tools/CMakeLists.txt.ENABLE_LLVM_BACKENDcache option (set(ENABLE_LLVM_BACKEND FALSE CACHE BOOL ...)).src/cmake/cpfe/CMakeLists.txtandsrc/cmake/cpfe-cp/CMakeLists.txt.tests/CMakeLists.txtwith LLVM components:Core,Support,Target,BitWriter,Analysis,Passes,MC,MCParser,TargetParser,AsmPrinter,AsmParser.5. Quality, Standards & Architectural Conformance
This pull request strictly satisfies all project-wide quality standards and mandates:
5.1 Centralized
[[nodiscard]]Error Enumerationtypedef enum class [[nodiscard]] llvm_gen_be_error_t : intinsrc/llvm_gen_be_error.h.(void)casts on error functions.5.2 Pervasive
noexcept& Strict-fno-exceptionssrc/llvm_gen_be*.handsrc/llvm_gen_be*.cppare decorated withnoexcept.throw,catch,try).-fno-exceptionsmode.5.3 Non-Throwing Heap Allocations
new (std::nothrow).llvm_gen_be_error_t::out_of_memory.5.4 100% Documentation Coverage (Doxygen)
Doxyfile.llvm_be:@fileand@brief/@detailsfor every source and header file.@struct/@enum/@classblock for every data structure.@brief,@details, explicit@param[in]/@param[out], and@returndocumentingllvm_gen_be_error_t::okand failure modes.5.5 100% Test & Branch Coverage Gate
.github/workflows/llvm_be_coverage.ymlanddev_tools/bin/run_coverage.sh).6. Comprehensive Testing & Verification Framework
The pull request adds an extensive, multi-tiered test infrastructure:
6.1 Unit Test Suite (
tests/llvm_ir_backend_tests/)18 dedicated C++ unit test executables verifying each subsystem in isolation:
error_test.cpp: Tests allllvm_gen_be_error_tenum values, string formatting, context recording, and reset behavior.fault_injection_test.cpp: Injects null pointers, invalid type kinds, unsupported expressions/statements, and bad file paths across all public APIs to verify proper error propagation.type_test.cpp: Tests all scalar integer types, floating-point types (bfloat16,fp16,fp80,fp128), complex numbers, arrays, VLAs, packed structs, and unions.const_test.cpp: Tests integer constants, float hexadecimal conversions, string literals (8-bit, UTF-16, UTF-32), block addresses, and nested constant aggregates.codegen_test.cpp: Tests target registry initialization, TargetMachine creation for multiple target triples, and emission of.ll,.bc,.s, and.ofiles.opt_pipeline_test.cpp: Tests parsing optimization level strings and executing PassManager pipelines across O0 through O3, Os, and Oz.abi_sysv_test.cpp&abi_sysv_integration_test.cpp: Tests System V AMD64 eightbyte argument classification, struct splitting, memory pass, andsret.abi_aapcs64_test.cpp: Tests ARM64 argument classification, HFA/HVA aggregate detection, and reference passing.abi_win64_test.cpp: Tests Microsoft Windows x64 calling convention, power-of-two composite rules, and indirect argument passing.debug_init_test.cpp: Tests DWARF debug state initialization, DIBuilder setup, and cleanup.debug_scope_test.cpp: Tests subprogram creation, lexical block scope stack push/pop, and location mapping.debug_types_test.cpp: Tests DWARF type descriptor generation for primitives, pointers, arrays, composites, and@llvm.dbg.declareemission.eh_test.cpp: Tests landing pad construction, personality routine attachment, and catch clause typeid matching.asm_test.cpp: Tests inline assembly constraint parsing, register clobbers, and multiple output values.goto_test.cpp: Tests labeled statements, forward/backward jumps, and computed indirect gotos.test_llvm_build_config.cpp: Validates backend build configurations and feature flags.test_llvm_driver_flag.cpp: Validates command-line driver flags for LLVM output files.test_llvm_verifier.cpp&test_llvm_orchestrator.cpp: Orchestrates end-to-end backend lowering and verifies module consistency.6.2 Lit Test Suite (
tests/lit/llvm/)LLVM lit tests verifying exact IR patterns using
FileCheck:bitfield_test.c&bitfield_test.ll: Verifies bitfield read shifts/masks and write updates.memcpy_test.c&memcpy_test.ll: Verifies@llvm.memcpyintrinsic generation for aggregate assignment.sret_test.c&sret_test.ll: Verifies structural return (sret) parameter passing and calls.opaque_pointers.c: Verifies opaque pointer generation and typing.stmt_for.c: Verifies loop basic blocks, conditions, and phi nodes.codegen_cli_test.c: Verifies multi-format output emission (.bc,.o,.s) via CLI options.6.3 Shell Integration Suites (
tests/test_llvm_*.sh)Automated bash test harnesses for integration testing:
test_llvm_abi_alignment.sh: Verifies alignment constraints across struct members and function calls.test_llvm_control_flow.sh: Exercises loops, switches, gotos, and breaks.test_llvm_coverage.sh: Runs coverage verification across the backend.test_llvm_execution.sh: Compiles and executes emitted LLVM IR via JIT/LLI.test_llvm_expressions.sh: Exercises arithmetic, bitwise, logic, casts, and GEP expressions.test_llvm_functions.sh: Tests function definitions, calls, arguments, and return values.test_llvm_globals.sh: Tests global variables, linkages, and static initializers.test_llvm_integration.sh: End-to-end test runner for full C translation units.test_llvm_output_generation.sh: Verifies that.ll,.bc,.s, and.ofiles are generated.test_llvm_stl_headers.sh: Tests lowering of standard library headers.6.4 GCC Torture Harness & STL Header Compilation
dev_tools/bin/run_gcc_torture_llvm.py: Automated harness to execute the GCC C Torture test suite againstcpfewith the LLVM backend.tests/test_llvm_stl_headers.sh: Validates compilation of C and C++ standard library headers.6.5 Continuous Integration & Automated Workflows
.github/workflows/llvm_be_coverage.yml:Dedicated GitHub Actions workflow running under Clang with
lcovandvalgrind(memcheck), enforcing strict 100% line/branch coverage..github/workflows/build-and-test-ci.yml:Updated main CI matrix to include a
coverage-llvmjob buildingcpfewith-DENABLE_LLVM_BACKEND=TRUE -DEDG_CPFE_USE_GCOV=TRUEand validating 100% line execution.7. Complete File-by-File Change Matrix
.github/workflows/build-and-test-ci.ymlcoverage-llvmCI job building with gcov and running test suites..github/workflows/llvm_be_coverage.ymlCMakeLists.txttestssubdirectory underBUILD_TESTING; excludedlldon macOS.Doxyfile.llvm_bedev-init.pydev_tools/CMakeLists.txtdev_tools/bin/run_coverage.shdev_tools/bin/run_gcc_torture_llvm.pycpfe.doc/source/ext_intf.rst--gen_llvm_file_name,--gen_llvm_bc_file_name,--gen_obj_file_name,--gen_asm_file_name.src/CMakeLists.txtENABLE_LLVM_BACKEND, Homebrew LLVM discovery on macOS, backend sources, C++17.src/c_gen_be.cback_end()definition under!BACK_END_IS_LLVM_GEN_BE.src/c_gen_be.hback_end()prototype under!BACK_END_IS_LLVM_GEN_BE.src/cfe.cllvm_gen_be.hand hookedllvm_gen_be()driver call.src/cmake/cpfe/CMakeLists.txtcpfewith required LLVM libraries whenENABLE_LLVM_BACKENDis on.src/cmake/cpfe-cp/CMakeLists.txtcpfe-cpwith LLVM libraries whenENABLE_LLVM_BACKENDis on.src/cmd_line.coptk_gen_llvm_file_name,optk_gen_llvm_bc_file_name,optk_gen_obj_file_name,optk_gen_asm_file_name.src/cmd_line.hsrc/cp_gen_be.cback_end()definition under!BACK_END_IS_LLVM_GEN_BE.src/cp_gen_be.hback_end()prototype under!BACK_END_IS_LLVM_GEN_BE.src/defines.hBACK_END_IS_LLVM_GEN_BEand decoupled C-generator macros.src/fe_wrapup.cllvm_gen_be_cleanup()into frontend wrap-up and memory deallocation.src/host_envir.hsrc/llvm_gen_be.hsrc/llvm_gen_be.cppsrc/llvm_gen_be_internal.hLLVMBackendStatedefinition, caches, and forward declarations.src/llvm_gen_be_error.h[[nodiscard]] llvm_gen_be_error_tenum and error context declarations.src/llvm_gen_be_error.cppsrc/llvm_gen_be_type.hsrc/llvm_gen_be_type.cppsrc/llvm_gen_be_const.hsrc/llvm_gen_be_const.cppsrc/llvm_gen_be_decl.cppsrc/llvm_gen_be_stmt.cppsrc/llvm_gen_be_expr.hsrc/llvm_gen_be_expr.cppsrc/llvm_gen_be_abi_sysv_x86_64.hsrc/llvm_gen_be_abi_sysv_x86_64.cppsrc/llvm_gen_be_abi_aapcs64.hsrc/llvm_gen_be_abi_aapcs64.cppsrc/llvm_gen_be_abi_win64.hsrc/llvm_gen_be_abi_win64.cppsrc/llvm_gen_be_debug.hsrc/llvm_gen_be_debug.cppsrc/llvm_gen_be_debug_scopes.cppsrc/llvm_gen_be_debug_types.cpp@llvm.dbg.declareemission.src/llvm_gen_be_opt.hsrc/llvm_gen_be_opt.cppsrc/llvm_gen_be_codegen.hsrc/llvm_gen_be_codegen.cpp.s/.o.src/lower_il.csrc/targ_def.htests/CMakeLists.txttests/lit/llvm/bitfield_test.ctests/lit/llvm/bitfield_test.lltests/lit/llvm/codegen_cli_test.c.bc,.o,.s).tests/lit/llvm/memcpy_test.ctests/lit/llvm/memcpy_test.ll@llvm.memcpyintrinsic emission.tests/lit/llvm/opaque_pointers.ctests/lit/llvm/sret_test.ctests/lit/llvm/sret_test.llsretattribute emission.tests/lit/llvm/stmt_for.ctests/llvm_ir_backend_tests/abi_aapcs64_test.cpptests/llvm_ir_backend_tests/abi_sysv_integration_test.cpptests/llvm_ir_backend_tests/abi_sysv_test.cpptests/llvm_ir_backend_tests/abi_win64_test.cpptests/llvm_ir_backend_tests/asm_test.cpptests/llvm_ir_backend_tests/codegen_test.cpp.ll/.bc/.s/.ofile generation.tests/llvm_ir_backend_tests/const_test.cpptests/llvm_ir_backend_tests/debug_init_test.cpptests/llvm_ir_backend_tests/debug_scope_test.cpptests/llvm_ir_backend_tests/debug_types_test.cpp@llvm.dbg.declareemission.tests/llvm_ir_backend_tests/eh_test.cpptests/llvm_ir_backend_tests/error_test.cpptests/llvm_ir_backend_tests/fault_injection_test.cpptests/llvm_ir_backend_tests/goto_test.cpptests/llvm_ir_backend_tests/opt_pipeline_test.cpptests/llvm_ir_backend_tests/type_test.cpptests/test_llvm_abi_alignment.shtests/test_llvm_build_config.cpptests/test_llvm_control_flow.shtests/test_llvm_coverage.shtests/test_llvm_datalayout.cpptests/test_llvm_driver_flag.cpptests/test_llvm_execution.shlli.tests/test_llvm_expressions.shtests/test_llvm_functions.shtests/test_llvm_fuzz.cpptests/test_llvm_globals.shtests/test_llvm_integration.shtests/test_llvm_orchestrator.cpptests/test_llvm_output_generation.shtests/test_llvm_stl_headers.shtests/test_llvm_type_translation.cpptests/test_llvm_verifier.cpputil/CMakeLists.txtlldlinker on macOS.8. Commit History & Evolution
The pull request comprises 7 logical, incremental commits:
c3770edf17- LLVM IR backend (initial pass)Initial scaffolding of LLVM backend driver (
llvm_gen_be.h/.cpp), build system integration (ENABLE_LLVM_BACKEND), command-line flags, type translation primitives, basic expression and statement lowerings, and shell test suite.b08d2a4fd9- LLVM IR backend: implement types, control flow, ABI, expressions, and C++ testsComprehensive implementation: dynamic TargetTriple/DataLayout, scoped local symbol table, LValue/RValue semantics with implicit loads, float variants, packed structs with byte padding, unions, bitfields, linkage mappings, TLS, control flow loops/switches/jumps, GEP memory references, and migration of Python test runners to native C++ executables.
72e30b8274- LLVM IR backend: implement exception handling, inline assembly, computed gotos, and test suiteItanium personality setup (
__gxx_personality_v0), landing pads, exception throw/rethrow runtime routines (__cxa_throw,__cxa_allocate_exception), GNU inline assembly lowering (stmk_asmtollvm::InlineAsm), computed gotos (IndirectBrInst), APFloat hex conversions, and CTest integration.c387283f31- LLVM IR backend: add RTTI/EH dispatch, inline asm outputs, opaque ptr support, and verificationModule and function verification pass (
llvm::verifyFunction), typeinfo lowering with EDG mangled names, catch clause typeid dispatch (llvm.eh.typeid.for), multiple outputs in inline asm via struct returns, opaque pointer modernization, and additional lit tests.5cc528b69f- LLVM IR backend: decouple C-backend macros, dynamically resolve target layouts, and refine codegenDecoupled backend macros (
BACK_END_IS_LLVM_GEN_BE) from C-generator assumptions, replaced staticTARG_*macros with dynamictarg_*variables, guardedback_end()inc_gen_be.c/cp_gen_be.c, added IL memory paging (read_memory_region), ensuredi1conditions for conditional branches, and upgraded build to C++17.e06c445859- LLVM IR backend: implement target ABIs, DWARF debug info, code emission, and pass pipelineImplemented target calling convention ABIs (SysV AMD64, AAPCS64, Win64), DWARF debug metadata emission with
DIBuilder(compile units, subprograms, lexical blocks, locations, and type metadata), direct TargetMachine code emission for object files (.o) and assembly (.s), LLVM New Pass Manager optimization pipeline (O0-O3, Os, Oz), centralized error subsystem (llvm_gen_be_error_t), and modularized headers.7fa91abfbf- LLVM IR backend: standardize noexcept error propagation, integrate DWARF scopes, and update test suiteEnforced uniform
[[nodiscard]] llvm_gen_be_error_terror propagation at type definition, qualified 100% of backend functions withnoexcept, migrated APIs to argument-based out-parameters, persistent error context threading, DWARF scope and parameter@llvm.dbg.declareintegration, guarded legacy headers, updated test suite signatures, and aligned lit test expectations.9. Verification Guide & Instructions for Reviewers
9.1 Prerequisites
llvm-dev/brew install llvm)9.2 Building the Compiler with the LLVM Backend
9.3 Running Backend Unit Tests
All unit tests are registered with CTest and can be run directly:
9.4 Running Lit and Shell Integration Suites
9.5 Verifying LLVM IR and Code Emission Directly
Compile sample C code using
cpfewith the new LLVM driver options:9.6 Generating Doxygen API Documentation
doxygen Doxyfile.llvm_be # Open html/index.html to browse the generated documentationNOTE: This is not intended to be merged. Just to start a conversation…