Skip to content

LLVM IR backend - #221

Open
SamuelMarks wants to merge 10 commits into
edgcpp:mainfrom
SamuelMarks:llvm_backend
Open

SamuelMarks wants to merge 10 commits into
edgcpp:mainfrom
SamuelMarks:llvm_backend

Conversation

@SamuelMarks

@SamuelMarks SamuelMarks commented Oct 6, 2026 •

Copy link
Copy Markdown

Native LLVM IR & Machine Code Backend (llvm_gen_be) for the EDG C/C++ Compiler Front End

Executive Summary

This pull request introduces a complete, production-grade native LLVM IR and machine code generation backend (llvm_gen_be) for the EDG C/C++ Front End (cpfe), transforming EDG from a pure parser/C-generating front end (c_gen_be / cp_gen_be) into a standalone, multi-target, optimizing C/C++ compiler and linker driver.

Across 10 commits (169 files changed, +62,404 / -506 lines), this branch implements:

  • 34 modular backend compilation units (src/llvm_gen_be*.cpp) and 30 headers (src/llvm_gen_be*.h) totaling 29,036 lines of C++17, cleanly decoupled from BACK_END_IS_C_GEN_BE and BACK_END_IS_CP_GEN_BE.
  • 12 Target Calling Convention psABIs: System V AMD64 (x86_64), Microsoft Windows x64 (Win64 + __vectorcall), ARM64 (AAPCS64, Darwin arm64, Windows ARM64EC), 32-bit x86 (cdecl, stdcall, fastcall, thiscall, regparm), 32-bit ARM (AAPCS / AAPCS-VFP), RISC-V (RV32 / RV64 lp64d), LoongArch64 (LP64D), MIPS (O32 / N64), PowerPC (PPC32 / PPC64 ELFv1 & ELFv2), SystemZ (s390x), SPARC (V8 / V9), and WebAssembly (wasm32 / wasm64).
  • Dual C++ Object Models (Itanium C++ ABI & Microsoft Visual C++ ABI): Primary and secondary vtables, Virtual Table Tables (VTT), construction vtables (_ZTC), this-adjusting and covariant return thunks, virtual base (vcall / vbase) offsets, vtordisp thunks, Itanium RTTI (__fundamental_type_info, __class_type_info, __si_class_type_info, __vmi_class_type_info, __pointer_type_info, __pointer_to_member_type_info), and MSVC RTTI (_TypeDescriptor, _s__RTTICompleteObjectLocator, _s__RTTIClassHierarchyDescriptor, _s__RTTIBaseClassArray, _s__RTTIBaseClassDescriptor, _ThrowInfo, _CatchableTypeArray).
  • Dual Exception Handling Models: Itanium zero-cost DWARF unwinding (__gxx_personality_v0, landingpad, __cxa_allocate_exception, __cxa_throw, __cxa_begin_catch, __cxa_end_catch, __cxa_rethrow, __cxa_call_unexpected, llvm.eh.typeid.for) and Windows Structured Exception Handling (__CxxFrameHandler3, __C_specific_handler, catchswitch, catchpad, catchret, cleanuppad, cleanupret, llvm.localescape, llvm.localrecover, outlined __finally / __except filter funclets, __leave, and /EHa asynchronous exception attributes).
  • Target Architecture SIMD & System Intrinsics: Native lowering for x86/x86_64 (MMX, SSE–SSE4.2, AVX, AVX2, AVX-512, AMX, BMI1/2, FMA, AES, SHA), ARM/AArch64 (NEON, SVE/SVE2, CRC32, Crypto, memory barriers, mrs/msr system registers), RISC-V (RVV, Zbb/Zbc/Zbs), PowerPC (Altivec/VSX), SystemZ (s390x vector), LoongArch (LSX/LASX), MIPS (MSA), SPARC (VIS), and WebAssembly (SIMD128).
  • OpenMP 4.5 / 5.x Host & GPU Offloading: Outlined microtasks (__kmpc_fork_call, __kmpc_fork_teams), static/dynamic/guided worksharing loops, reductions, tasks (__kmpc_omp_task_alloc, __kmpc_omp_taskloop), synchronization (critical, barrier, master/masked, ordered, flush, atomic), SIMD loop metadata (!llvm.loop.vectorize.enable), vector function ABI mangling (_ZGV...), and libomptarget device offloading (__tgt_target_kernel, __tgt_target_data_begin_mapper, __tgt_target_data_end_mapper, __tgt_target_data_update_mapper) with embedded device image compilation (nvptx64-nvidia-cuda, amdgcn-amd-amdhsa, spirv64).
  • C++20 Coroutines & Modules: Switched-resume coroutine lowering (llvm.coro.id, llvm.coro.size, llvm.coro.begin, llvm.coro.save, llvm.coro.suspend, llvm.coro.end, llvm.coro.free, llvm.coro.resume, llvm.coro.destroy, llvm.coro.promise, llvm.coro.noop) with promise allocation alignment/elision, and C++20 Module metadata (!edg.cpp20.module, !edg.cpp20.imports) with idempotent per-module dynamic initializer guards (__module_init_<name>).
  • DWARF v4/v5, Split DWARF (.dwo), & CodeView (.pdb) Debug Info: Full llvm::DIBuilder integration for compilation units, lexical block scopes, subprograms, local/parameter llvm.dbg.declare / llvm.dbg.value, composite types (classes, base inheritance, vtable holders, unions, bitfields, enums, templates), DIFlagBitField, createFragmentExpression (SROA), inlinedAt chains, DWARF v5 macro information (DIMacroFile, DIMacro), Fortran/C common blocks (DICommonBlock), and using declarations/directives (DIImportedEntity).
  • LLVM New PassManager, Sanitizers, PGO, LTO, & Native Toolchain Driver: Full -O0/-O1/-O2/-O3/-Os/-Oz optimization pipeline, Loop/SLP vectorization, AddressSanitizer (ASan), ThreadSanitizer (TSan), MemorySanitizer (MSan), HWAddressSanitizer (HWASan), UndefinedBehaviorSanitizer (UBSan), SafeStack, ShadowCallStack, Stack Protector (-fstack-protector*), Instrumentation PGO (-fprofile-generate / -fprofile-use), FullLTO and ThinLTO (ModuleSummaryIndex, combined index generation, and multi-TU in-process IR linking), and automated native toolchain/SDK discovery (ld.lld, ld64.lld, lld-link, clang++, CRT startup objects).
  • Strict Reliability & Verification Standards:
    • Universal typedef enum class [[nodiscard]] llvm_gen_be_error_t : int32_t return status across all internal and public backend functions.
    • Universal noexcept enforcement and zero unhandled error paths (LLVM_GEN_BE_CHECK / LLVM_GEN_BE_CHECK_NOT_NULL / LLVM_GEN_BE_RETURN_ERROR).
    • 100.00% Function, Line, Region, and Branch Test Coverage across all 64 src/llvm_gen_be*.{h,cpp} files verified via llvm-cov (dev_tools/check_llvm_be_coverage.py).
    • 100.00% Doxygen Documentation Coverage across all 93 backend and test files (dev_tools/check_doc_coverage.py).

Table of Contents

  1. Architectural Overview & Subsystem Map
  2. Error Handling & [[nodiscard]] noexcept Contract
  3. Deep Dive by Subsystem
  4. Front-End Decoupling & Integration Changes
  5. Chronological Summary of All 10 Commits
  6. Testing, Fuzzing, & 100% Coverage Verification

1. Architectural Overview & Subsystem Map

The backend is organized into 34 implementation files (src/llvm_gen_be*.cpp) and 30 header files (src/llvm_gen_be*.h), coordinated by LLVMBackendState (src/llvm_gen_be_internal.h):

Subsystem Header(s) Implementation(s) LOC Core Responsibilities
Orchestrator & Lifecycle llvm_gen_be.h, llvm_gen_be_internal.h llvm_gen_be.cpp 1,108 back_end(), llvm_gen_be(), DataLayout synthesis, target triple sync, CLI option dispatch, IL verification, multi-TU state reset & cleanup
Error & Diagnostics llvm_gen_be_error.h llvm_gen_be_error.cpp 602 [[nodiscard]] llvm_gen_be_error_t, llvm_gen_be_error_context_t, source-coordinate extraction (conv_seq_to_file_and_line), EDG f_error bridge
Type System & TBAA llvm_gen_be_type.h llvm_gen_be_type.cpp 1,169 Scalar/float/vector/complex/fixed-point/struct/union/array/VLA/function lowering, opaque ptr, !tbaa & !tbaa.struct, GPU address spaces
Constant Evaluator llvm_gen_be_const.h llvm_gen_be_const.cpp 1,309 Integer/FP (APInt/APFloat), UTF-8/16/32 strings, aggregates, bitfield byte packing, relocatable address constants (abk_*), blockaddress
Expression Lowering llvm_gen_be_expr.h llvm_gen_be_expr.cpp 4,829 LValue/RValue evaluation, arithmetic/logic/casts, bitfields, calls, new/delete, C11/C++20 atomics, fold expressions, TR 18037 fixed-point, UBSan traps, builtins
Target Intrinsics llvm_gen_be_intrinsics.h llvm_gen_be_intrinsics.cpp 730 x86 (SSE/AVX/AVX-512/AMX/BMI/AES/SHA), ARM/AArch64 (NEON/SVE/Crypto/barriers/sysregs), RISC-V, PPC, s390x, LoongArch, MIPS, SPARC, Wasm SIMD128
Statements & Control Flow (in internal.h) llvm_gen_be_stmt.cpp 1,463 if, for, while, do-while, switch (case ranges), goto, computed goto (indirectbr), VLAs (stacksave/stackrestore), RAII ScopeCleanupStack
Declarations & Modules (in internal.h) llvm_gen_be_decl.cpp 3,109 Globals, linkage/visibility/COMDAT/TLS, functions, dynamic initializers (llvm.global_ctors/dtors, .CRT$XCU), __cxa_guard_*, C++20 modules, unlowered mangling
Virtual Tables & Thunks llvm_gen_be_vtable.h llvm_gen_be_vtable.cpp 1,377 Itanium vtables (_ZTV), VTTs (_ZTT), construction vtables (_ZTC), this/covariant/virtual thunks, MSVC VFTable/VBTable & vtordisp thunks, devirtualization
RTTI & dynamic_cast llvm_gen_be_rtti.h llvm_gen_be_rtti.cpp 824 Itanium _ZTI/_ZTS descriptors, MSVC _TypeDescriptor & hierarchy descriptors, dynamic_cast (__dynamic_cast / __RTDynamicCast / void*), typeid (__cxa_bad_typeid)
Member Pointers llvm_gen_be_ptrmem.h llvm_gen_be_ptrmem.cpp 694 Itanium {ptr, adj} & {offset} representations, MSVC single/multiple/virtual inheritance models, virtual/non-virtual dispatch, base-to-derived conversions
Exception Handling llvm_gen_be_eh.h llvm_gen_be_eh.cpp 1,236 Itanium landingpad/resume/__cxa_* & noexcept termination (__clang_call_terminate), Windows SEH (catchswitch/catchpad/cleanuppad), outlined filters/cleanups, /EHa
C++20 Coroutines llvm_gen_be_coro.h llvm_gen_be_coro.cpp 790 Coroutine ramp, promise allocation/alignment/elision, initial/final suspend, co_await/co_yield/co_return, llvm.coro.* intrinsics
Inline Assembly llvm_gen_be_asm.h llvm_gen_be_asm.cpp 594 GNU asm / asm goto (callbr), constraint canonicalization, multi-output struct unpacking, memory (*m) & clobber normalization, full x86/x64 MSVC __asm parser
OpenMP 4.5 / 5.x llvm_gen_be_omp.h llvm_gen_be_omp.cpp 2,517 parallel, for, sections, single, master/masked, critical, barrier, task/taskloop/taskwait/taskyield, flush, ordered, atomic, simd, teams distribute, GPU target offloading
Target ABIs (12 Archs) llvm_gen_be_abi_*.h (12) llvm_gen_be_abi_*.cpp (12) 6,645 SysV x86_64, Win64, AAPCS64 (+ARM64EC), x86-32, ARM32, RISC-V 64, LoongArch64, MIPS, PPC64, s390x, SPARC, WebAssembly — classification, coercion, sret/byval, va_list/va_arg
DWARF & CodeView Debug llvm_gen_be_debug.h llvm_gen_be_debug*.cpp (3) 2,098 DIBuilder, compile units, lexical scopes, DILocation (inlinedAt), full type graph (DICompositeType, bitfields, templates), SROA fragments, DWARF v5 macros, CodeView
Optimization Pipeline llvm_gen_be_opt.h llvm_gen_be_opt.cpp 291 New PassBuilder (O0–Oz), Loop/SLP vectorizers, CoroEarly/CoroSplit/CoroElide/CoroCleanup, PGO instrumentation & use, ASan/TSan/MSan/HWASan/SafeStack/ShadowCallStack
Codegen & TargetMachine llvm_gen_be_codegen.h llvm_gen_be_codegen.cpp 515 Target initialization, TargetMachine creation, CPU/feature/reloc/code-model config, .ll, .bc, .s, .o emission, ThinLTO ModuleSummaryIndex, Split DWARF .dwo
Driver & Linker llvm_gen_be_driver.h llvm_gen_be_driver.cpp 568 Host/target SDK & CRT discovery (Linux/macOS/Windows), native linker invocation (lld / ld / clang++), multi-TU ThinLTO/FullLTO combined index & in-process linking

2. Error Handling & [[nodiscard]] noexcept Contract

Every function in the LLVM backend adheres to a strict, zero-exception error-propagation contract defined in src/llvm_gen_be_error.h:

  1. [[nodiscard]] Error Enum (llvm_gen_be_error_t):
    typedef enum class [[nodiscard]] llvm_gen_be_error_t : int32_t {
      ok = 0,
      invalid_argument = 1,
      out_of_memory = 2,
      unsupported_type = 3,
      unsupported_expr = 4,
      unsupported_stmt = 5,
      abi_classification_failed = 6,
      di_metadata_failure = 7,
      pass_pipeline_failure = 8,
      code_gen_failure = 9,
      verification_failure = 10,
      io_error = 11,
      constant_eval_failure = 12,
      symbol_lookup_failure = 13,
      eh_lowering_failure = 14,
      vtable_generation_failure = 15,
      coroutine_lowering_failure = 16,
      inline_asm_failure = 17,
      internal_inconsistency = 18,
      not_implemented = 19,
      omp_lowering_failure = 20,
      offload_bundling_failed = 21,
      lto_indexing_failed = 22,
      module_bmi_corrupt = 23,
      dwarf_macro_emission_failed = 24,
      coro_frame_layout_failed = 25,
      null_pointer = 26,
      type_lowering_failed = 27,
      coro_lowering_failed = 28,
      omp_lowering_failed = 29,
      eh_lowering_failed = 30,
      rtti_vtable_failed = 31,
      debug_info_failed = 32,
      opt_pipeline_failed = 33,
      codegen_emit_failed = 34,
      linker_invocation_failed = 35,
      gpu_offload_failed = 36,
      module_io_failed = 37,
      verification_failed = 38,
      internal_error = 39
    } llvm_gen_be_error_t;
    Attaching [[nodiscard]] directly to the typedef enum class guarantees that the compiler enforces return-value inspection on every backend call site without cluttering individual function declarations.
  2. Universal noexcept & Out-Parameters:
    All backend functions are marked noexcept and return llvm_gen_be_error_t, passing computed llvm::Type*, llvm::Value*, llvm::Constant*, or metadata nodes via validated pointer out-parameters.
  3. Structured Diagnostic Context (llvm_gen_be_error_context_t):
    Captures error_code, file_name, line_number, column_number, EDG seq_number, and a 512-byte formatted diagnostic message via llvm_gen_be_format_diagnostic (resolving EDG a_source_position coordinates via conv_seq_to_file_and_line) and bridges directly to the EDG front-end diagnostic output via llvm_gen_be_report_to_edg_fe.

3. Deep Dive by Subsystem

3.1 Type System, DataLayout, TBAA, & Address Spaces (llvm_gen_be_type.{h,cpp})

  • Dynamic DataLayout Construction (build_data_layout): Queries EDG runtime target configuration variables (targ_little_endian, targ_sizeof_pointer, targ_alignof_pointer, targ_sizeof_short, targ_sizeof_int, targ_sizeof_long, targ_sizeof_long_long, targ_sizeof_float, targ_sizeof_double, targ_sizeof_long_double, targ_Right_Shift_Is_Arithmetic, etc.) rather than static compile-time macros, emitting valid LLVM data layout strings (e/E, m:e/m:o/m:w, p:64:64, i1:8:8-i8:8:8-..., f80:128:128, n8:16:32:64, S128).
  • Scalar & Extended Floating-Point Lowering: Maps all an_integer_kind variants (ik_char through ik_int128 and C23 _BitInt(N) arbitrary bit-width integers iN) and all a_float_kind variants (fk_float -> float, fk_double -> double, fk_long_double -> x86_fp80 / fp128 / ppc_fp128 / double based on target layout and size, fk_float80 -> x86_fp80, fk_float128 -> fp128, fk_fp16 -> half, fk_bfloat16 -> bfloat).
  • Complex, Vector, & Fixed-Point Types:
    • tk_complex lowers to two-element homogeneous structs { T, T }.
    • tk_vector lowers to llvm::FixedVectorType::get(elem_ty, num_elems) or llvm::ScalableVectorType for SVE/RVV scalable vectors.
    • tk_fixed_point (ISO/IEC TR 18037 _Fract / _Accum, signed/unsigned, short/default/long, saturating/non-saturating) lowers to the underlying scaled integer width with exact fractional bit-shift metadata (llvm_get_fixed_point_scale).
  • Aggregates, Bitfields, & Empty Classes:
    • tk_struct / tk_class pre-registers an opaque StructType in be_state->type_cache before lowering field types to break recursive self-referential struct cycles.
    • Inserts explicit [N x i8] padding arrays between fields at non-contiguous byte offsets, packs adjacent bitfields into storage units (i8, i16, i32, i64), and lowers empty C++ classes (size == 1, no fields) to { i8 }.
    • Respects #pragma pack and __attribute__((packed)) by emitting packed llvm::StructType layouts when field offsets violate natural alignment.
    • tk_union selects the largest/most-aligned member and appends tail padding [pad x i8] to match the total EDG union size.
  • Opaque Pointers & Target Address Spaces:
    • Uses modern LLVM opaque pointers (llvm::PointerType::get(ctx, addr_space)).
    • llvm_resolve_target_address_space maps OpenCL/CUDA/HIP/SYCL/target named address spaces (__global, __local/__shared, __constant, __private, __generic, __gs/seg_gs, __fs/seg_fs) to target-specific LLVM address space numbers for nvptx64, amdgcn, spirv64, and x86_64.
  • Type-Based Alias Analysis (TBAA):
    • llvm_get_tbaa_type_node constructs a rooted TBAA hierarchy ("Simple C/C++ TBAA" -> "omnipotent char" (i8) -> scalar/enum/pointer/struct type descriptors).
    • llvm_get_tbaa_access_tag and llvm_attach_tbaa_metadata attach !tbaa access tags to loads/stores, while llvm_get_tbaa_struct_metadata generates !tbaa.struct byte-offset/size/tag triples for aggregate llvm.memcpy operations.

3.2 Constant Evaluation & Bitfield Packing (llvm_gen_be_const.{h,cpp})

  • Scalar & String Constants:
    • ck_integer: Arbitrary-precision conversion from EDG an_integer_value (int_constant_value / uns_constant_value or hex string fallback) to llvm::APInt and llvm::ConstantInt.
    • ck_float: Exact bit-accurate IEEE-754 conversion via fp_to_hex_constant_string / APFloat handling NaN (quiet/signaling), +Inf, -Inf, subnormals, half, bfloat, float, double, x86_fp80, fp128, and ppc_fp128.
    • ck_string: Supports narrow (char / UTF-8), char16_t (uint16_t array), char32_t (uint32_t array), and wchar_t (16-bit on Windows, 32-bit on Unix) string literals with global constant deduplication in be_state->string_literal_cache.
  • Aggregate & Union Constant Initializers:
    • ck_aggregate: Walks first_constant initializer chains alongside tk_struct/tk_class fields, packing adjacent bitfield constants via llvm_pack_constant_bitfield_bytes (handling both little-endian and big-endian bit offsets and multi-byte spans), synthesizing zero-padding [N x i8] arrays for gaps, and handling [N x T] array repeat/tail zero-initialization (ConstantAggregateZero).
    • For tk_union constants, wraps initialized active fields into an anonymous struct constant with tail [pad x i8] zero bytes when the active member is smaller than the union container.
  • Address Constants (ck_address):
    • Supports abk_routine (function addresses), abk_variable (global/static variable addresses), abk_constant (pool constants), abk_string (deduplicated .str globals), abk_temporary (deduplicated .tmp.const globals in be_state->temporary_constant_cache), abk_label (llvm::BlockAddress::get for computed gotos), and abk_param_ref (constexpr parameter slot lookups).
    • Applies non-zero byte offsets via constant i8 getGetElementPtr expressions.

3.3 Expressions, Casts, Atomics, Fixed-Point, & Builtins (llvm_gen_be_expr.{h,cpp})

  • LValue vs. RValue Evaluation (llvm_lower_lvalue / llvm_lower_expression):
    • llvm_lower_lvalue resolves addresses for enk_variable, enk_field (struct GEP + union bitcast), enk_deref, enk_array_sub, enk_operation (eok_indirect, eok_points_to, eok_dot_field, eok_Subscript, eok_comma, eok_question, eok_assign, prefix ++/--, eok_lvalue_cast, eok_ref_cast, eok_base_cast, eok_derived_cast, eok_pm_field, eok_points_to_field), enk_temp_init, and enk_constant.
    • llvm_lower_expression evaluates all 100+ an_expr_operator_kind (eok_*) and an_expr_node_kind (enk_*) variants, including short-circuiting && (eok_land), || (eok_lor), and ternary ? : (eok_question) with proper PHI node merging and boolean i1 conversions.
  • Bitfield Read & Write Bit-Manipulation:
    • Supports arbitrary bitfield widths and byte offsets across struct storage units: extracts bitfields via lshr + mask + shl/ashr sign extension (for signed bitfields), and updates bitfields via read-modify-write masking ((old & ~(mask << shift)) | ((val & mask) << shift)), including compound assignments (+=, |=, etc.) and pre/post increment/decrement.
  • C99/C++ Complex Arithmetic (_Complex / std::complex):
    • Full component-wise lowering for complex addition, subtraction, multiplication ((ac - bd) + i(ad + bc)), division (((ac + bd)/(c^2 + d^2)) + i((bc - ad)/(c^2 + d^2))), negation, conjugation (eok_conj), real/imag projection (eok_real_part / eok_imag_part), equality/inequality, and scalar-to-complex / complex-to-complex conversions.
  • ISO/IEC TR 18037 Fixed-Point Operations:
    • Lowers saturating and non-saturating fixed-point addition (llvm.sadd.sat / llvm.uadd.sat), subtraction (llvm.ssub.sat / llvm.usub.sat), scaled multiplication (llvm.smul.fix / llvm.umul.fix / llvm.smul.fix.sat / llvm.umul.fix.sat), scaled division (llvm.sdiv.fix / llvm.udiv.fix / llvm.sdiv.fix.sat / llvm.udiv.fix.sat), and fixed-point <-> integer/floating-point conversions (ldexp / scaled shifts).
  • Dynamic Memory Management (new / delete / Array Cookies):
    • Lowers eok_new / enk_new_delete for single objects and arrays: computes allocation size with overflow checking (llvm.umul.with.overflow), adds Itanium/MSVC array cookies (sizeof(size_t) / alignment padding) when the element type has a non-trivial destructor or operator delete[](void*, size_t) requires element counts, invokes _Znwm / _Znam / aligned _ZnwmSt11align_val_t (or MSVC ??2@YAPEAX_K@Z), runs element constructors in a loop, and lowers eok_delete (scalar destructor + _ZdlPv or reverse array destruction loop + cookie adjustment + _ZdaPv).
  • C11 / C++20 Atomics (__atomic_* & __sync_*):
    • Maps memory ordering constants (__ATOMIC_RELAXED through __ATOMIC_SEQ_CST) to llvm::AtomicOrdering.
    • Lowers __atomic_load[_n], __atomic_store[_n], __atomic_exchange[_n], __atomic_compare_exchange[_n] (AtomicCmpXchgInst with success/failure orderings and weak/strong flag), __atomic_fetch_{add,sub,and,or,xor,nand}, __atomic_{add,sub,and,or,xor,nand}_fetch, __atomic_test_and_set, __atomic_clear, __atomic_thread_fence, __atomic_signal_fence, and __atomic_is_lock_free / __atomic_always_lock_free.
  • C++17 Fold Expressions & Variadic Packs:
    • llvm_lower_fold_expression lowers unary left/right folds ((... op pack), (pack op ...)) and binary left/right folds ((init op ... op pack), (pack op ... op init)) across all 32 fold-eligible C++17 operators, returning identity elements (true for &&, false for ||, void() for ,) on empty packs.
    • llvm_lower_sizeof_pack evaluates sizeof...(Ts) to a size_t constant.
  • Compiler Builtins (llvm_lower_builtin_operation & Intrinsic Calls):
    • Bit manipulation: __builtin_clz* (llvm.ctlz), __builtin_ctz* (llvm.cttz), __builtin_popcount* (llvm.ctpop), __builtin_bswap{16,32,64} (llvm.bswap), __builtin_bitreverse* (llvm.bitreverse), __builtin_ffs*, __builtin_clrsb*, __builtin_parity*.
    • Checked arithmetic: __builtin_{add,sub,mul}_overflow and *{s,u}{add,sub,mul}*_overflow (llvm.{s,u}{add,sub,mul}.with.overflow).
    • Memory & layout: __builtin_memcpy / memmove / memset, __builtin_bit_cast (bopk_bit_cast), __builtin_offsetof (bopk_offsetof), __builtin_clear_padding (synthesizes per-byte padding mask via llvm_compute_type_padding_mask covering struct alignment holes, bitfield unused bits, and union tail padding), __builtin_launder, __builtin_assume_aligned, __builtin_prefetch.
    • Vector operations: __builtin_shufflevector (bopk_shufflevector), __builtin_convertvector (bopk_convertvector), __builtin_reduce_{add,mul,and,or,xor,min,max}.
    • Control & reflection: __builtin_trap (llvm.trap), __builtin_debugtrap (llvm.debugtrap), __builtin_unreachable, __builtin_expect (llvm.expect), __builtin_assume (llvm.assume), __builtin_constant_p (llvm.is.constant), __builtin_frame_address (llvm.frameaddress), __builtin_return_address (llvm.returnaddress), __builtin_dwarf_cfa (llvm.eh.dwarf.cfa), __builtin_LINE / FILE / FUNCTION / COLUMN / __builtin_source_location (std::source_location::__impl), and MSVC __uuidof (_GUID constant synthesis).
  • UndefinedBehaviorSanitizer (UBSan) Instrumentation:
    • When sanitize_undefined / enable_ubsan_checks is active, emits inline division-by-zero, signed-overflow (INT_MIN / -1), shift-out-of-bounds, and null-pointer checks branching to __ubsan_handle_divrem_overflow, __ubsan_handle_add_overflow, __ubsan_handle_shift_out_of_bounds, or llvm.trap.

3.4 Target Architecture SIMD & System Intrinsics (llvm_gen_be_intrinsics.{h,cpp})

Dedicated target builtin dispatcher (llvm_try_lower_target_builtin) supporting 10 hardware architectures:

  • x86 / x86_64 (llvm_lower_x86_builtin):
    • SSE / SSE2 / SSE3 / SSSE3 / SSE4.1 / SSE4.2: sqrtps/pd/ss/sd, rcpps/rsqrtps, minps/maxps/minpd/maxpd, paddb/w/d/q, psubb/w/d/q, pmullw/d, padds/psubs/paddus/psubus (llvm.sadd.sat/uadd.sat), pshufb, dpps/dppd, blendvps/blendvpd, movmskps/movmskpd/pmovmskb, crc32 (llvm.x86.sse42.crc32.*), pcmpistri/pcmpestri, lfence/sfence/mfence/pause.
    • AVX / AVX2 / FMA: 256-bit vsqrt*, vmin*/vmax*, vfmadd* (llvm.fma.*), vperm2f128/vperm2i128, vpshufb, vpmovmskb, vzeroall/vzeroupper.
    • AVX-512 & AMX: 512-bit masked arithmetic, reductions, vpdpbusd (llvm.x86.avx512.vpdpbusd.*), and AMX tile operations (ldtilecfg, sttilecfg, tilezero, tileloadd64, tilestored64, tdpbssd/tdpbf16ps).
    • BMI1 / BMI2 / AES / SHA / System: bextr, bzhi, pdep, pext, lzcnt/tzcnt, aesenc/aesenclast/aesdec/aesdeclast/aesimc/aeskeygenassist, sha1*/sha256*, rdtsc/rdtscp (llvm.readcyclecounter), rdrand*/rdseed*.
  • ARM / AArch64 (llvm_lower_arm_builtin):
    • NEON: vadd*, vsub*, vmul*, vfma* (llvm.fma), vqadd*/vqsub* (saturating), vmin*/vmax*, vabs*/vneg*, vsqrt*, vaddv*/vminv*/vmaxv* (llvm.vector.reduce.*), vtbl*/vtbx*, vld1*/vst1*.
    • SVE / SVE2: Predicated scalable vector operations (svadd, svsub, svmul, svmad, svmla, svcntb/h/w/d via llvm.vscale, svptrue).
    • CRC32 & Crypto: __crc32b/h/w/d/cb/ch/cw/cd (llvm.aarch64.crc32*), vaeseq_u8, vaesdq_u8, vaesmcq_u8, vaesimc_u8, vsha1*, vsha256*, vsha512*, vsm3*, vsm4*.
    • Barriers & System Registers: __dmb, __dsb, __isb (llvm.aarch64.dmb/dsb/isb), __yield/__wfe/__wfi/__sev/__sevl (llvm.aarch64.hint), __arm_rsr* (llvm.read_register), __arm_wsr* (llvm.write_register), __cls*, __rbit* (llvm.bitreverse).
  • RISC-V (llvm_lower_riscv_builtin):
    • RVV (Vector Extension): vsetvl/vsetvlmax, vector arithmetic (vadd, vsub, vmul, vfmacc), reductions (vredsum, vredmax, vredmin).
    • Zbb / Zbc / Zbs / Zba / Zk (Bitmanip & Scalar Crypto): clz, ctz, cpop, orc.b, rev8, rol, ror, clmul/clmulh/clmulr (llvm.riscv.clmul*), aes64*/sha256*/sha512*/sm3*/sm4*.
  • PowerPC (llvm_lower_ppc_builtin):
    • Altivec / VSX: vec_add, vec_sub, vec_mul, vec_madd (llvm.fma), vec_adds/vec_subs, vec_min/vec_max, vec_perm, vec_ld/vec_vsx_ld, vec_st/vec_vsx_st, __dcbz, __lwsync/__sync/__isync/__eieio.
  • SystemZ s390x (llvm_lower_s390x_builtin):
    • Vector facility builtins (vec_add, vec_sub, vec_mul, vec_madd, vec_perm, vec_cntlz, vec_cnttz, vec_popcnt) and transactional execution (__builtin_tbegin, __builtin_tend, __builtin_tabort).
  • LoongArch LSX/LASX, MIPS MSA, SPARC VIS, & WebAssembly SIMD128 (llvm_lower_other_arch_builtin):
    • LoongArch 128-bit __lsx_* and 256-bit __lasx_* vector arithmetic, cpucfg, crc_w_*, dbar/ibar.
    • MIPS MSA __builtin_msa_* vector arithmetic and min/max.
    • SPARC VIS __builtin_vis_* (faligndata, fpack*, pdist).
    • WebAssembly SIMD128 (wasm_i32x4_*, wasm_f32x4_*, wasm_v128_*, svmin/svmax/avgr/abs/sqrt, memory_size/memory_grow via llvm.wasm.memory.size/grow).

3.5 Control Flow, Statements, VLAs, & Scoped RAII Cleanups (llvm_gen_be_stmt.cpp)

  • Structured & Unstructured Control Flow:
    • Lowers stmk_block, stmk_if, stmk_while, stmk_end_test_while (do-while), stmk_for, stmk_switch (including GNU case ranges case low ... high: expanded into SwitchInst range targets), stmk_goto, stmk_label, and stmk_return.
    • Computed Gotos (stmk_assigned_goto): Collects all address-taken labels in the current routine and emits llvm::IndirectBrInst with exact destination basic block lists.
  • Scoped RAII Destructor & VLA Stack Unwinding (ScopeCleanupStack):
    • Tracks active local variables with non-trivial destructors, VLA stack saves (llvm.stacksave / llvm.stackrestore), thread-safe local static initialization guards (__cxa_guard_abort), and SEH __finally funclets.
    • Every return, break, continue, and goto compares the source cleanup stack depth against the target scope depth (using llvm_precompute_function_labels for forward and backward goto statements) and emits the exact sequence of intervening destructor calls and llvm.stackrestore intrinsics in reverse construction order.
    • When a statement expression ({ ... }) is active, protects enclosing scope cleanups using stmt_expr_cleanup_depths.

3.6 Declarations, Linkage, TLS, C++20 Modules, & Unlowered Name Mangling (llvm_gen_be_decl.cpp)

  • Unlowered C++ Entity Mangler (llvm_mangle_unlowered_entity):
    • Because DO_IL_LOWERING can be disabled or bypassed for templates/inline routines, implements a complete fallback mangler supporting both Itanium C++ ABI (_Z..., nested N...E, St substitution, cv-qualifiers K/V, ref-qualifiers R/O, constructors C1/C2, destructors D0/D1/D2, conversion operators cv<type>, overloaded operators pl/mi/ml/eq/cl/etc., template argument lists I...E, vendor extended types u7__bf16 / Dh / g, and function parameter lists) and Microsoft Visual C++ ABI (?name@scope@@...).
  • Global & Static Variables:
    • Translates EDG storage classes (sc_static, sc_extern, sc_unspecified), weak/inline/template attributes (LinkOnceODRLinkage, WeakODRLinkage, WeakAnyLinkage, CommonLinkage), ELF/Mach-O visibility (Default, Hidden, Protected), Windows dllexport / dllimport (DLLExportStorageClass / DLLImportStorageClass), and custom ELF/Mach-O/COFF __attribute__((section("..."))).
    • Attaches llvm::Comdat groups (Comdat::SelectionKind::Any) for inline variables, template instantiations, vtables, and typeinfo globals on ELF and COFF targets.
  • Thread-Local Storage (TLS) & __tls_init:
    • Maps EDG thread-local variables to llvm::GlobalValue::GeneralDynamicTLSModel, LocalDynamicTLSModel, InitialExecTLSModel, or LocalExecTLSModel.
    • For thread_local variables requiring dynamic initialization, emits a guarded __tls_init function, an WeakODR _ZTH<var> thread-local wrapper alias/stub, and registers thread-local destructors via __cxa_thread_atexit.
  • Function-Local Static Variables & Guard Variables:
    • Emits 64-bit guard variables (_ZGV...) and lowers thread-safe initialization using Itanium __cxa_guard_acquire / __cxa_guard_release / __cxa_guard_abort (with an active ScopeCleanup that invokes __cxa_guard_abort on exception unwind and registers __cxa_atexit for destruction) or MSVC _Init_thread_header / _Init_thread_footer / _Init_thread_abort.
  • Global Constructors & Destructors (llvm.global_ctors / llvm.global_dtors / .CRT$XCU):
    • Synthesizes __sti__<tu> initialization routines for globals in be_state->global_dynamic_inits (handling constructor(priority) attributes, default priority 65535, and __cxa_atexit registration) and appends them to @llvm.global_ctors and @llvm.global_dtors (or .CRT$XCU function pointer tables on Windows MSVC targets).
  • C++20 Modules (llvm_lower_module_metadata):
    • Inspects primary_Scope->module_info and imported module lists to emit module flags (C++20 Module, C++20 Module Partition), !edg.cpp20.module and !edg.cpp20.imports metadata nodes, an idempotent guard variable @__module_init_guard_<mod>, and an external @__module_init_<mod>() routine that initializes imported modules before local TU constructors.

3.7 C++ Object Model: VTables, VTTs, Construction VTables, & Thunks (llvm_gen_be_vtable.{h,cpp})

  • Itanium C++ ABI Virtual Tables (_ZTV, _ZTT, _ZTC):
    • llvm_emit_class_vtables constructs the complete vtable group for polymorphic classes:
      • Primary vtable (vcall / vbase offsets for virtual bases, offset-to-top = 0, @_ZTI<Class> RTTI pointer, and virtual function/thunk pointers, with @__cxa_pure_virtual / @__cxa_deleted_virtual for pure/deleted methods).
      • Secondary vtables for non-primary polymorphic base subobjects (offset-to-top = -base_offset, base vbase offsets, RTTI pointer, and this-adjusted / covariant thunks).
      • Construction VTables (_ZTC<Derived><offset>_<Base>) and Virtual Table Tables (_ZTT<Class>) in preorder inheritance graph order for classes with virtual bases.
  • Microsoft Visual C++ ABI Tables (VFTable & VBTable):
    • Emits ??_7<Class>@@6B@ (VFTable) preceded by a pointer to the Complete Object Locator (??_R4<Class>@@6B@) in a two-element struct { ptr @??_R4, [N x ptr] } so the exported symbol points to [N x ptr] at offset +sizeof(ptr).
    • Emits ??_8<Class>@@7B@ (VBTable) containing [i32 0, i32 vbase_offset_1, ...] for classes with virtual base classes.
  • Virtual Thunks (_ZTv, _ZTh, _ZTch, & MSVC vtordisp):
    • Non-virtual this-adjustment thunks (_ZTh<n>_...): adjusts this by constant byte offset n and tail-calls (musttail when variadic or eligible) the target method.
    • Virtual this-adjustment thunks (_ZTv0_n<vcall>_...): loads the vtable pointer from this, reads the vcall offset at vcall_offset, adds it to this, and dispatches to the target method.
    • Covariant return thunks (_ZTch<this_adj>_h<ret_adj>_... / _ZTcv...): adjusts this on entry, calls the underlying implementation, checks the returned pointer for nullptr, and applies static/virtual base adjustment to the non-null return pointer.
    • MSVC vtordisp thunks (?fn@Class@@$4PPPPPPPM@A@...): reads the 32-bit vtordisp displacement at this - 4, subtracts it together with the static base adjustment, and tail-calls the target method.
  • Speculative Devirtualization (llvm_try_devirtualize_call):
    • Directly resolves virtual calls without vtable loads when the target method or enclosing class is marked final, or when the receiver object's dynamic type is statically proven (local alloca, global variable, or constructor/destructor this).

3.8 Run-Time Type Information (RTTI): Itanium & MSVC (llvm_gen_be_rtti.{h,cpp})

  • Itanium ABI RTTI (get_typeinfo_global):
    • Generates _ZTS<Type> mangled type name strings and _ZTI<Type> descriptors referencing vtable_prefix + 2 * sizeof(ptr):
      • __cxxabiv1::__fundamental_type_info for primitives and void.
      • __cxxabiv1::__pointer_type_info (with cv-qualification bitmasks) for pointers.
      • __cxxabiv1::__pointer_to_member_type_info for pointers to members.
      • __cxxabiv1::__class_type_info for root classes/unions.
      • __cxxabiv1::__si_class_type_info for single public non-virtual inheritance.
      • __cxxabiv1::__vmi_class_type_info for multiple or virtual inheritance, computing diamond/repeated base flags (0x1 non-diamond repeat, 0x2 diamond shaped) and __base_class_type_info arrays with encoded (base_offset << 8) | (is_virtual ? 1 : 0) | (is_public ? 2 : 0) flags.
  • MSVC ABI RTTI (get_msvc_type_descriptor & get_msvc_complete_object_locator):
    • Generates ??_R0?AU<Class>@@@8 (_TypeDescriptor with ??_7type_info@@6B@ vptr, spare, and mangled name), ??_R3 (_s__RTTIClassHierarchyDescriptor), ??_R2 (_s__RTTIBaseClassArray), ??_R1 (_s__RTTIBaseClassDescriptor with mdisp, pdisp, vdisp, and attributes), and ??_R4 (_s__RTTICompleteObjectLocator using 32-bit image-relative offsets on 64-bit Windows and direct pointers on 32-bit Windows).
  • dynamic_cast (llvm_lower_dynamic_cast) & typeid (llvm_lower_typeid):
    • dynamic_cast<void*>(p): checks p != nullptr, loads offset-to-top at vptr[-2], and returns p + offset_to_top.
    • dynamic_cast<Dest*>(p) / dynamic_cast<Dest&>(r): computes src2dst hint (0 public base, -1 unknown, -2 not a public base), calls __dynamic_cast (Itanium) or __RTDynamicCast (MSVC), and for reference casts checks the result for nullptr and branches to __cxa_bad_cast on failure.
    • Polymorphic typeid(*p): checks p == nullptr (branching to __cxa_bad_typeid on null dereference), loads vptr[-1] (Itanium) or invokes __RTtypeid(p) (MSVC).

3.9 Pointers to Members (Data & Function): Itanium & MSVC (llvm_gen_be_ptrmem.{h,cpp})

  • Pointer-to-Member-Function (PMF):
    • Itanium ABI: { i64 ptr, i64 adj } (or { i32, i32 } on 32-bit targets). For non-virtual functions, ptr is the function address and adj is the byte offset adjustment (even on x86/RISC-V; on ARM/AArch64/MIPS, adj bit 0 encodes the virtual indicator while ptr holds the vtable byte offset). Call lowering (llvm_lower_pmf_call) tests the virtual bit, branches between direct call and vtable load (*(vptr + vtable_offset)), adjusts this, and merges via a PHI node.
    • MSVC ABI: Supports Single Inheritance (ptr), Multiple Inheritance ({ ptr, i32 adj }), and Virtual Inheritance ({ ptr, i32 adj, i32 vindex }, loading VBTable at *(this + adj) + vindex).
  • Pointer-to-Data-Member (PDM):
    • Itanium ABI: ptrdiff_t (i64/i32) where -1 (0xfff...) represents nullptr. Field access (llvm_lower_pdm_field) adds the byte offset to the base object pointer; conversions (llvm_lower_pm_conversion) check against -1 before adding/subtracting base subobject offsets.
    • MSVC ABI: i32 where -1 represents nullptr (or { i32 mdisp, i32 pdisp, i32 vdisp } under virtual inheritance).

3.10 Exception Handling: Itanium DWARF Unwinding & Windows SEH (llvm_gen_be_eh.{h,cpp})

  • Itanium C++ ABI Exception Lowering:
    • Attaches @__gxx_personality_v0 to functions with try blocks or active RAII cleanups.
    • Transforms calls inside active current_landing_pads scopes into llvm::InvokeInst.
    • Lowers throw expr (llvm_lower_throw) to @__cxa_allocate_exception, stores/constructs the exception object, and invokes @__cxa_throw(ex_ptr, @_ZTI<T>, @dtor) followed by unreachable; lowers throw; (eok_rethrow) to @__cxa_rethrow().
    • Builds chained landingpad { ptr, i32 } blocks with addClause for catch handlers and setCleanup(true) for RAII destructors, matching catch types via @llvm.eh.typeid.for + icmp eq, extracting exception pointers with @__cxa_begin_catch / @__cxa_end_catch, and resuming unwinding via resume { ptr, i32 } or chaining to outer landing pads (llvm_emit_chained_cleanup_landingpad).
    • For noexcept / throw() functions, routes unhandled exceptions to a catch ptr null terminate landing pad calling @__clang_call_terminate (__cxa_begin_catch -> std::terminate).
    • For dynamic exception specifications (throw(T1, T2)), emits negative filter selector checks (sel < 0) calling @__cxa_call_unexpected.
  • Windows MSVC C++ EH & Structured Exception Handling (SEH):
    • Attaches @__CxxFrameHandler3 (or @__C_specific_handler for C SEH) and lowers try/catch using Windows funclet tokens: catchswitch within ... [label %catch.pad] unwind to caller, catchpad within %cs [ptr @TypeDesc, i32 flags, ptr %catch_var], and catchret from %cp to label %cont.
    • Synthesizes complete MSVC _ThrowInfo (_TI...), _CatchableTypeArray (_CTA...), and _CatchableType (_CT...) descriptors and lowers throw to @_CxxThrowException(ptr %ex_slot, ptr @_TI...).
    • SEH __try / __except / __finally / __leave:
      • Calls @llvm.localescape(...) in the parent function entry block for local variables accessed by filter or finally funclets.
      • Outlines __except(filter_expr) expressions into dedicated filter functions (?filt$0@0@<fn>@@) using @llvm.eh.exceptionpointer / @llvm.eh.exceptioncode (_exception_info() / _exception_code()) and @llvm.localrecover.
      • Outlines __finally blocks into cleanup funclets (?fin$0@0@<fn>@@(i8 abnormal_termination, ptr frame_pointer)) invoked both on normal exit (abnormal_termination = 0) and inside cleanuppad unwind blocks (abnormal_termination = 1).
      • Lowers __leave statements (llvm_lower_seh_leave) by branching to the innermost enclosing __try body exit block (seh_leave_blocks).
      • Supports /EHa asynchronous SEH (llvm_enable_async_seh_attributes) by attaching "async-exceptions"="true" and "seh-asynch"="true" function attributes and modeling volatile memory accesses.

3.11 C++20 Coroutines (llvm_gen_be_coro.{h,cpp})

  • Full switched-resume coroutine lowering (llvm_lower_coroutine_stmt, llvm_lower_coroutine_return, llvm_lower_co_await_or_yield):
    • Emits @llvm.coro.id(i32 align, ptr %promise, ptr null, ptr null), checks @llvm.coro.alloc(token %id) for heap elision, queries @llvm.coro.size.i64() (including over-aligned frame padding when align > __STDCPP_DEFAULT_NEW_ALIGNMENT__), allocates the coroutine frame via _Znwm / operator new, and initializes the frame handle with @llvm.coro.begin(token %id, ptr %mem).
    • Evaluates promise.get_return_object(), co_await promise.initial_suspend(), the coroutine body, promise.return_value(v) / promise.return_void(), promise.unhandled_exception() in the exception landing pad, and co_await promise.final_suspend().
    • Lowers suspension points using @llvm.coro.save(ptr %hdl) and @llvm.coro.suspend(token %save, i1 %is_final) with 3-way switch dispatch (0 -> resume, 1 -> cleanup, default -> suspend block calling @llvm.coro.end(ptr %hdl, i1 false, token none)).
    • Emits frame deallocation via @llvm.coro.free(token %id, ptr %hdl) and _ZdlPv.
    • Lowers __builtin_coro_resume (@llvm.coro.resume), __builtin_coro_destroy (@llvm.coro.destroy), __builtin_coro_done (@llvm.coro.done), __builtin_coro_promise (@llvm.coro.promise), and __builtin_coro_noop (@llvm.coro.noop).

3.12 Inline Assembly: GNU Extended asm / asm goto & MSVC __asm (llvm_gen_be_asm.{h,cpp})

  • GNU Extended Inline Assembly (stmk_asm):
    • Translates GCC/Clang operand templates (%0, %1, %w0, %x0, %k0, %q0, named %[sym], %% -> $$ literal escaping) into LLVM InlineAsm format ($0, ${0:w}, etc.).
    • llvm_canonicalize_asm_constraint normalizes target-specific constraints: tied inputs ("=r,0"), early-clobber ("=&r"), indirect memory outputs/inputs ("=*m", "*m"), architecture-specific register constraints ("a" -> "{eax}", "b" -> "{ebx}", "c" -> "{ecx}", "d" -> "{edx}", "S" -> "{esi}", "D" -> "{edi}", "Yz" -> "{xmm0}"), and clobber lists (~{memory}, ~{cc}, ~{dirflag}, ~{fpsr}, ~{flags}).
    • Multi-output assembly returns an aggregate { T0, T1, ... } unpacked via ExtractValueInst and stored back to each output lvalue (with integer/pointer bitcast/trunc/zext coercion when register width differs from the C lvalue width).
    • asm goto: When jump labels are present on stmk_asm, emits an llvm::CallBrInst with fallthrough and indirect target basic blocks.
  • MSVC __asm Blocks (lower_msvc_inline_asm):
    • Full x86/x86_64 Intel-syntax assembly parser handling multi-line __asm { ... } blocks, comments (;), local labels, data directives (db, dw, dd, dq), rep/lock prefixes, memory addressing ([ebp + var], dword ptr [rax + rcx*4 + 8]), local/global C variable substitution into numbered $0, $1 operands, automatic modified-register clobber detection (~{eax}, ~{ebx}, etc.), and emission with llvm::InlineAsm::AD_Intel.

3.13 OpenMP 4.5 / 5.x Host Directives & GPU Target Offloading (llvm_gen_be_omp.{h,cpp})

  • Host Parallelism & Worksharing (libomp / __kmpc_*):
    • parallel: Captures shared/private/firstprivate variables, outlines .omp_outlined. microtask (i32* .global_tid., i32* .bound_tid., ...), and emits @__kmpc_fork_call(ptr @ident, i32 argc, ptr @.omp_outlined., ...). Also respects if(cond) (__kmpc_serialized_parallel / __kmpc_end_serialized_parallel) and num_threads(n) (__kmpc_push_num_threads).
    • for / distribute: Static (__kmpc_for_static_init_4/8 + __kmpc_for_static_fini) and dynamic/guided/runtime (__kmpc_dispatch_init_4/8 + __kmpc_dispatch_next_4/8) loop chunking.
    • reduction: Emits thread-private accumulators, a .omp.reduction.red_list pointer array, an outlined @.omp_reduction_func, and @__kmpc_reduce_nowait / @__kmpc_end_reduce_nowait with atomic fallback loop.
    • sections & single: @__kmpc_for_static_init_4 section switch dispatch and @__kmpc_single / @__kmpc_end_single (plus copyprivate broadcast via @__kmpc_copyprivate).
    • task, taskloop, taskwait, & taskyield: @__kmpc_omp_task_alloc, @__kmpc_omp_task, @__kmpc_omp_task_with_deps, @__kmpc_omp_taskloop, @__kmpc_omp_taskwait, and @__kmpc_omp_taskyield.
    • Synchronization: @__kmpc_critical / @__kmpc_end_critical (with named critical spinlocks), @__kmpc_barrier, @__kmpc_master / @__kmpc_end_master, @__kmpc_masked / @__kmpc_end_masked, @__kmpc_ordered / @__kmpc_end_ordered, @__kmpc_flush + fence seq_cst, and omp atomic (read, write, update, capture via AtomicRMWInst / AtomicCmpXchgInst).
    • simd & declare simd: Attaches !llvm.loop.vectorize.enable, !llvm.loop.vectorize.width, and !llvm.loop.parallel_accesses metadata to loops, and emits Vector Function ABI (_ZGVbN4v_..., _ZGVdN8v_..., _ZGVeN16v_..., _ZGVnN4v_...) SIMD clones for #pragma omp declare simd.
  • OpenMP 5.x GPU Target Offloading (libomptarget):
    • parse_omp_map_clauses parses map(to:), map(from:), map(tofrom:), map(alloc:), map(release:), and map(delete:) clauses into OMP_TGT_MAPTYPE_* bitmasks (0x01 TO, 0x02 FROM, 0x10 ALWAYS, 0x20 DELETE, 0x200 PARAM, 0x400 IMPLICIT).
    • lower_omp_target constructs .offload_baseptrs, .offload_ptrs, .offload_sizes, and @.offload_maptypes, populates %struct.__tgt_kernel_arguments, invokes @__tgt_target_kernel(ptr @ident, i64 device_id, i32 num_teams, i32 thread_limit, ptr @.__omp_offloading_entry, ptr %kernel_args), and falls back to the host execution region if @__tgt_target_kernel returns non-zero.
    • lower_omp_target_data_region emits @__tgt_target_data_begin_mapper, @__tgt_target_data_end_mapper, and @__tgt_target_data_update_mapper for target data, target enter data, target exit data, and target update.
    • compile_omp_device_module synthesizes a dedicated GPU device llvm::Module for nvptx64-nvidia-cuda or amdgcn-amd-amdhsa (ptx_kernel / amdgpu_kernel calling conventions, !nvvm.annotations), compiles it via TargetMachine (or emits a structured PTX/bitcode image), and embeds it into @.omp_offloading.device_image and .omp_offloading_entries in the host module.

3.14 Multi-Architecture Target Calling Convention ABIs (12 Architectures)

Centralized dispatcher llvm_compute_function_abi_info + 12 dedicated target psABI modules:

  1. System V AMD64 (llvm_gen_be_abi_sysv_x86_64.{h,cpp}): Recursive eightbyte classification (NO_CLASS, INTEGER, SSE, SSEUP, X87, X87UP, COMPLEX_X87, MEMORY) with post-merger cleanups, register pressure tracking (6 GPRs, 8 XMMs), 1- and 2-eightbyte register coercion (i64, double, {i64, i64}, {i64, double}, {double, i64}, {double, double}, <2 x float>), sret/byval, non-trivial C++ aggregate invisible references, and [1 x { i32, i32, ptr, ptr }] va_list / va_arg register-save-area + overflow-area branching.
  2. Windows x64 (llvm_gen_be_abi_win64.{h,cpp}): 4-slot positional register model (RCX/XMM0, RDX/XMM1, R8/XMM2, R9/XMM3), power-of-two integer coercion (i8, i16, i32, i64) vs. indirect pointer passing for composites of size != 1, 2, 4, 8, __vectorcall (X86_VectorCall) HVA support in XMM0–XMM5, and contiguous ptr va_list / va_arg.
  3. ARM64 AAPCS64 & ARM64EC (llvm_gen_be_abi_aapcs64.{h,cpp}): HFA/HVA detection (1–4 homogeneous float/half/double/quad/vector elements passed in V0–V7), composites <= 16 bytes coerced to [N x i64] in X0–X7, composites > 16 bytes passed indirectly by pointer, Darwin arm64 char* va_list vs. Linux ELF [1 x { ptr, ptr, ptr, i32, i32 }] va_list, and Windows ARM64EC emulation-compatible thunk signatures (build_arm64ec_thunk_signature).
  4. x86 32-bit (llvm_gen_be_abi_x86_32.{h,cpp}): cdecl, stdcall (X86_StdCall), fastcall (X86_FastCall), thiscall (X86_ThisCall placing this in ECX), and regparm(1..3) inreg attribute assignment.
  5. ARM 32-bit (llvm_gen_be_abi_arm32.{h,cpp}): AAPCS and AAPCS-VFP HFA detection, 4-byte/8-byte alignment [N x i32] / [N x i64] register coercion, and sret for composites > 4 bytes.
  6. RISC-V 64-bit LP64D (llvm_gen_be_abi_riscv64.{h,cpp}): Hardware FP flattening ({ float, float }, { double, int }, { int, double }), 1x/2x XLEN (i64 / [2 x i64]) coercion for aggregates <= 16 bytes, and indirect reference passing for aggregates > 16 bytes.
  7. LoongArch64 LP64D (llvm_gen_be_abi_loongarch64.{h,cpp}): GAR ($a0–$a7) and FAR ($fa0–$fa7) classification (float_float, integer_float, float_integer, integer_integer, memory).
  8. MIPS O32 & N64 (llvm_gen_be_abi_mips.{h,cpp}): 32-bit O32 and 64-bit N64 register chunk coercion, soft-float vs. hard-float handling, and byval/sret placement.
  9. PowerPC 32 & 64 ELFv1/ELFv2 (llvm_gen_be_abi_ppc64.{h,cpp}): ELFv2 up-to-8-element HFA detection (f1–f13), AltiVec/VSX vector passing (v2–v13), and GPR (r3–r10) octword coercion.
  10. SystemZ s390x (llvm_gen_be_abi_s390x.{h,cpp}): GPR (%r2–%r6) and FPR (%f0, %f2, %f4, %f6) tracking, single-float struct FPR promotion, 1/2/4/8-byte power-of-two struct integer coercion, and [1 x { i64, i64, ptr, ptr }] va_list.
  11. SPARC V8 & V9 (llvm_gen_be_abi_sparc.{h,cpp}): 32-bit V8 indirect byval passing vs. 64-bit V9 register coercion for aggregates up to 32 bytes.
  12. WebAssembly (llvm_gen_be_abi_wasm.{h,cpp}): Direct scalar/single-element struct unpacking and indirect linear-memory pointer passing (byval/sret) for multi-field composites on wasm32 and wasm64.

3.15 Debug Information: DWARF v4/v5, Split DWARF, & CodeView (llvm_gen_be_debug*.{h,cpp})

Split across three focused files (llvm_gen_be_debug.cpp, llvm_gen_be_debug_scopes.cpp, llvm_gen_be_debug_types.cpp):

  • Compilation Units & Formats: Supports DWARF v4 and v5 (Dwarf Version), Split DWARF (splitDebugFilename .dwo), and Windows CodeView (CodeView module flag = 1 for .pdb emission when targeting *-windows-msvc).
  • Lexical Scopes & Locations (llvm_gen_be_debug_scopes.cpp): Maintains a scope stack (DICompileUnit -> DINamespace -> DISubprogram -> DILexicalBlock), maps EDG a_seq_number source coordinates to DIFile + line + column, and supports DILocation::get(..., inlinedAt) for inlined call chains (llvm_debug_create_inlined_location).
  • Complete Type Lowering (llvm_gen_be_debug_types.cpp):
    • Primitives (DIBasicType with DW_ATE_boolean, DW_ATE_signed, DW_ATE_unsigned, DW_ATE_float, DW_ATE_UTF, DW_ATE_complex_float), pointers/references (DIDerivedType), qualifiers (DW_TAG_const_type, DW_TAG_volatile_type, DW_TAG_restrict_type), typedefs (DW_TAG_typedef), arrays/vectors (DICompositeType with DISubrange), and subroutines (DISubroutineType).
    • Structs, classes, and unions: builds forward declarations first to break cyclic graphs, then populates DIDerivedType members (including DIFlagBitField bit offsets/sizes, DIFlagPublic/Protected/Private, static members), createInheritance base classes (with virtual base vtable offsets), vptr holder links, member function declarations, and DITemplateTypeParameter / DITemplateValueParameter lists.
    • Enumerations (DW_TAG_enumeration_type with DIEnumerator constants and DIFlagEnumClass for enum class).
  • Variables, SROA Fragments, Macros, & Imported Entities (llvm_gen_be_debug.cpp):
    • Emits #dbg_declare / llvm.dbg.declare for allocas, #dbg_value / llvm.dbg.value with DIExpression::createFragmentExpression(offset_bits, size_bits) for scalarized struct fragments (llvm_debug_emit_fragment_value), DIGlobalVariableExpression for globals (and DICommonBlock for common blocks), DIImportedEntity for using declarations/directives, and DIMacroFile / DIMacro (DW_MACINFO_define / DW_MACINFO_undef) for DWARF v5 -g3 macro debugging.

3.16 Optimization Pipeline, Sanitizers, PGO, LTO, & Code Emission (llvm_gen_be_opt.{h,cpp}, llvm_gen_be_codegen.{h,cpp})

  • New PassManager Pipeline (run_optimization_pipeline):
    • Registers LoopAnalysisManager, FunctionAnalysisManager, CGSCCAnalysisManager, and ModuleAnalysisManager with PassBuilder.
    • Runs coroutine lowering passes (CoroEarlyPass, CoroSplitPass, CoroElidePass, CoroCleanupPass), Mem2Reg / SROA, and either buildO0DefaultPipeline or buildPerModuleDefaultPipeline (O1, O2, O3, Os, Oz) with configurable Loop and SLP vectorization.
    • Supports ThinLTO pre-link (buildThinLTOPreLinkDefaultPipeline) and FullLTO (buildLTODefaultPipeline) pipelines.
  • Instrumentation PGO & Sanitizers:
    • -fprofile-generate[=<dir>]: Runs PGOInstrumentationGen and sets __llvm_profile_filename when a custom directory/file is specified.
    • -fprofile-use=<profdata>: Runs PGOInstrumentationUse with the supplied .profdata file.
    • Sanitizers (-fsanitize=): Configures and runs AddressSanitizerPass (SanitizeAddress), ThreadSanitizerPass (SanitizeThread), MemorySanitizerPass (SanitizeMemory), HWAddressSanitizerPass (SanitizeHWAddress), and attaches SafeStack (safestack) and ShadowCallStack (shadowcallstack) attributes alongside stack protector modes (ssp, sspstrong, sspreq).
  • TargetMachine & Multi-Format Output (llvm_gen_be_codegen.cpp):
    • Initializes all built-in LLVM targets (InitializeAllTargetInfos, InitializeAllTargets, InitializeAllTargetMCs, InitializeAllAsmParsers, InitializeAllAsmPrinters).
    • Emits textual LLVM IR (.ll), LLVM bitcode (.bc, optionally embedding a ModuleSummaryIndex for ThinLTO), target assembly (.s via CodeGenFileType::AssemblyFile), and native relocatable object code (.o / .obj via CodeGenFileType::ObjectFile).

3.17 Native Toolchain Discovery, Linker Driver, & Front-End CLI Integration (llvm_gen_be_driver.{h,cpp}, cmd_line.{h,c})

  • Native Toolchain & SDK Discovery (discover_target_toolchain & build_native_linker_args):
    • Probes the host/target environment for Linux multiarch/GCC runtime directories (crt1.o/Scrt1.o, crti.o, crtbegin.o, crtend.o, crtn.o), macOS Xcode / CommandLineTools SDKs (xcrun --show-sdk-path, -syslibroot), and Windows MSVC / Windows SDK library paths.
    • Automatically links sanitizer runtimes (-fsanitize=*), PGO profile runtimes (-fprofile-instr-generate), OpenMP runtimes (-fopenmp / -lomp), C++ standard libraries (-lc++ / -lstdc++ / msvcprt.lib), and user -L/-l/-Wl, flags.
  • Multi-TU ThinLTO / FullLTO & In-Process Linking (run_thinlto_combined_index_and_link & llvm_finalize_multi_tu_link):
    • When multiple translation units are compiled (cpfe a.cpp b.cpp -flto=thin -o app), each TU emits bitcode/object files and registers them in be_state->extra_linker_inputs; after the final TU, llvm_finalize_multi_tu_link parses all bitcode modules, builds the combined ModuleSummaryIndex, links the IR modules via llvm::Linker::linkModules, runs the LTO optimization pipeline, emits the native object, and links the final executable.
  • CLI Options Added to cpfe (src/cmd_line.h, src/cmd_line.c):
    • Output flags: --llvm, --gen_llvm_file_name (--emit-llvm), --gen_llvm_bc_file_name (--emit-llvm-bc), --gen_llvm_thinlto_index, --gen_obj_file_name / -c, --gen_asm_file_name / -S, -o <file>.
    • Optimization & LTO/PGO: -O0, -O1, -O2, -O3, -Os, -Oz, --llvm_opt_level, -flto, -flto=thin, -flto=full, -fprofile-generate[=<path>], -fprofile-use=<path>.
    • Debug & Sanitizers: -g, --llvm_debug_info, -gsplit-dwarf[=<dwo>], -fsanitize={address,thread,memory,undefined,hwaddress,safe-stack,shadow-call-stack}, -fstack-protector, -fstack-protector-strong, -fstack-protector-all.
    • Target & Codegen: --target=<triple> / -target <triple>, -mcpu=<cpu> / -march=<arch>, -mattr=<features>, -fPIC / -fpic / -fPIE / -fpie / -fno-pic, -mcmodel={tiny,small,kernel,medium,large}, -fopenmp, -L<dir>, -l<lib>, -Wl,<arg>.

4. Front-End Decoupling & Integration Changes

To ensure the EDG front end operates cleanly as a native compiler front end when BACK_END_IS_LLVM_GEN_BE == 1 without breaking c_gen_be or cp_gen_be builds:

  1. src/host_envir.h & src/target.h:
    • Defined BACK_END_IS_LLVM_GEN_BE (defaulting to FALSE) and guarded BACK_END_IS_C_GEN_BE so the two cannot be simultaneously active.
    • Enabled COMPILE_MULTIPLE_SOURCE_FILES and DO_IL_LOWERING compatibility when BACK_END_IS_LLVM_GEN_BE is enabled.
  2. src/c_gen_be.{h,c} & src/cp_gen_be.{h,c}:
    • Guarded back_end() declarations and definitions with #if !BACK_END_IS_LLVM_GEN_BE so llvm_gen_be.cpp provides the canonical back_end() entry point.
  3. src/cfe.c & src/fe_wrapup.c:
    • Included llvm_gen_be.h when BACK_END_IS_LLVM_GEN_BE is enabled.
    • Hooked llvm_finalize_multi_tu_link() after the multi-TU compilation loop in cfe.c and llvm_gen_be_cleanup() in fe_wrapup.c.
    • Set skip_il_read = TRUE by default for BACK_END_IS_LLVM_GEN_BE so in-memory IL is lowered directly without unnecessary disk serialization, and allowed -o <output> with both single and multiple input source files.
  4. IL Lowering Guards (src/il_alloc.c, src/layout.c, src/lower_c99.c, src/lower_eh.c, src/lower_il.c, src/lower_name.c, src/sizeof.c, src/statements.c, src/sys_predef.c):
    • Updated preprocessor conditions that previously assumed only BACK_END_IS_C_GEN_BE or BACK_END_IS_CP_GEN_BE existed, ensuring proper layout, exception lowering, and predefined macro registration when BACK_END_IS_LLVM_GEN_BE is active.
  5. CMake Build System (CMakeLists.txt, src/CMakeLists.txt, tests/CMakeLists.txt, CMakePresets.json):
    • Upgraded C++ standard in src/CMakeLists.txt to C++17 (CMAKE_CXX_STANDARD 17) required by LLVM headers.
    • Added ENABLE_LLVM_BACKEND and EDG_LLVM_BE_COVERAGE CMake options, automatic Homebrew/system LLVM find_package(LLVM CONFIG) detection, and presets llvm-backend-debug, llvm-backend-release, and llvm-backend-coverage.
    • Added custom build target check_doc_coverage verifying 100% Doxygen coverage on every build.

5. Chronological Summary of All 10 Commits

Commit 1: c3770edf17 — LLVM IR backend (initial pass)

  • Created initial scaffolding for src/llvm_gen_be.cpp and src/llvm_gen_be.h.
  • Wired ENABLE_LLVM_BACKEND into CMakeLists.txt, src/CMakeLists.txt, cmake/macro-conf.cmake, src/host_envir.h, src/cfe.c, and src/cmd_line.{h,c}.
  • Implemented foundational LLVMContext, Module, and IRBuilder initialization, basic primitive integer/float/pointer type translation, simple global/function declaration emission, and basic arithmetic expression lowering.

Commit 2: b08d2a4fd9 — LLVM IR backend: implement types, control flow, ABI, expressions, and C++ tests

  • Implemented scoped local symbol tables (local_vars), LValue vs. RValue evaluation with implicit loads, and dynamic TargetTriple/DataLayout construction.
  • Added struct, union, bitfield packing/masking, array, VLA, and pointer-to-member type lowering.
  • Added global linkage mappings (weak, linkonce, comdat, TLS), recursive constant evaluation, and @llvm.global_ctors / @llvm.global_dtors dynamic initializer registration.
  • Implemented control flow (if, while, do-while, for, switch, break, continue, goto), GEP indexing, direct/indirect/vararg/sret calls, casts, and initial C++ unit tests.

Commit 3: 72e30b8274 — LLVM IR backend: implement exception handling, inline assembly, computed gotos, and test suite

  • Implemented Itanium C++ ABI exception handling (__gxx_personality_v0, landingpad, __cxa_allocate_exception, __cxa_throw, __cxa_rethrow, __cxa_begin_catch, __cxa_end_catch, and invoke lowering).
  • Implemented GNU stmk_asm inline assembly lowering to llvm::InlineAsm with constraint and clobber translation.
  • Implemented computed gotos (stmk_assigned_goto) via llvm::IndirectBrInst and llvm::BlockAddress.
  • Added exact hex floating-point constant parsing (fp_to_hex_constant_string), UTF-16/UTF-32 string constant arrays, and .github/workflows/llvm_be_coverage.yml.

Commit 4: c387283f31 — LLVM IR backend: add RTTI/EH dispatch, inline asm outputs, opaque ptr support, and verification

  • Integrated llvm::verifyFunction and llvm::verifyModule with source position diagnostic reporting.
  • Added RTTI typeinfo global emission (get_typeinfo_global) and catch clause type matching via @llvm.eh.typeid.for.
  • Extended inline assembly to support multiple outputs via struct returns, indirect memory constraints (*m), and extraction into lvalue destinations.
  • Modernized GEP and pointer operations for LLVM opaque pointers (ptr) and added bfloat16, fp16, fp80, and fp128 float/complex mappings.

Commit 5: 5cc528b69f — LLVM IR backend: decouple C-backend macros, dynamically resolve target layouts, and refine codegen

  • Replaced compile-time TARG_* macros in llvm_gen_be with dynamic runtime targ_* variables so cross-target layouts resolve accurately at runtime.
  • Decoupled BACK_END_IS_LLVM_GEN_BE from BACK_END_IS_C_GEN_BE across src/host_envir.h, src/target.h, src/il_alloc.c, src/lower_c99.c, src/lower_eh.c, src/lower_il.c, src/lower_name.c, src/sizeof.c, src/statements.c, and src/sys_predef.c.
  • Added IL memory region paging (read_memory_region in get_scope_for_routine_definition) and guaranteed basic block termination prior to IR verification.

Commit 6: e06c445859 — LLVM IR backend: implement target ABIs, DWARF debug info, code emission, and pass pipeline

  • Modularized backend into dedicated subsystems: llvm_gen_be_error.{h,cpp}, llvm_gen_be_type.{h,cpp}, llvm_gen_be_const.{h,cpp}, llvm_gen_be_expr.{h,cpp}, llvm_gen_be_debug*.{h,cpp}, llvm_gen_be_opt.{h,cpp}, and llvm_gen_be_codegen.{h,cpp}.
  • Implemented calling convention ABI classifiers for System V x86_64 (llvm_gen_be_abi_sysv_x86_64.{h,cpp}), ARM64 AAPCS64 (llvm_gen_be_abi_aapcs64.{h,cpp}), and Windows x64 (llvm_gen_be_abi_win64.{h,cpp}).
  • Implemented DIBuilder DWARF debug metadata emission, LLVM New PassManager (O0–Oz) optimization pipelines, and TargetMachine .o / .s / .bc emission.

Commit 7: 7fa91abfbf — LLVM IR backend: standardize noexcept error propagation, integrate DWARF scopes, and update test suite

  • Decorated llvm_gen_be_error_t with [[nodiscard]] at the type definition and annotated all backend APIs with noexcept, migrating all internal and external helpers to return llvm_gen_be_error_t with pointer out-parameters.
  • Threaded persistent be_state->err_context across codegen and pass execution.
  • Integrated DWARF DISubprogram, DILexicalBlock scopes, and llvm.dbg.declare parameter/local variable metadata directly into routine lowering, and hooked llvm_gen_be_cleanup() into src/fe_wrapup.c.

Commit 8: 7f49d998df — LLVM IR backend: modularize vtables, EH, inline asm, coroutines, atomics, and revamp test suite

  • Extracted C++ object model and advanced language features into dedicated modules: llvm_gen_be_vtable.{h,cpp}, llvm_gen_be_rtti.{h,cpp}, llvm_gen_be_eh.{h,cpp}, llvm_gen_be_asm.{h,cpp}, llvm_gen_be_coro.{h,cpp}, llvm_gen_be_decl.cpp, llvm_gen_be_stmt.cpp, and llvm_gen_be_abi_riscv64.{h,cpp}.
  • Implemented C++20 coroutine lowering (llvm.coro.*), C11/C++20 atomic builtins (__atomic_*), and Windows SEH funclet unwinding (catchswitch/catchpad/cleanuppad).
  • Added dev_tools/check_doc_coverage.py and Doxyfile.llvm_be enforcing 100% Doxygen documentation coverage, and consolidated the test suite into self-contained C++ unit test binaries (tests/test_llvm_*.cpp).

Commit 9: d9b6bcef10 — LLVM IR backend: implement multi-target ABIs, member pointers, OpenMP, PGO/LTO pipelines, and expanded test coverage

  • Added 8 additional target calling convention ABI subsystems: llvm_gen_be_abi_arm32, llvm_gen_be_abi_loongarch64, llvm_gen_be_abi_mips, llvm_gen_be_abi_ppc64, llvm_gen_be_abi_s390x, llvm_gen_be_abi_sparc, llvm_gen_be_abi_wasm, and llvm_gen_be_abi_x86_32.
  • Implemented pointer-to-member lowering (llvm_gen_be_ptrmem.{h,cpp}) for both Itanium and MSVC (single, multiple, and virtual inheritance) models.
  • Implemented OpenMP runtime lowering (llvm_gen_be_omp.{h,cpp}) and native linker driver orchestration (llvm_gen_be_driver.{h,cpp}) with PGO (-fprofile-generate/-fprofile-use), ThinLTO/FullLTO, and sanitizer pipelines.

Commit 10: 9ab18501e1 — LLVM IR backend: implement target intrinsics, OpenMP 5.x offloading, TBAA, and 100% coverage

  • Implemented src/llvm_gen_be_intrinsics.{h,cpp} covering SIMD and system builtins across x86/x86_64 (SSE–AVX-512, AMX, BMI, AES, SHA), ARM/AArch64 (NEON, SVE, CRC32, Crypto, barriers, sysregs), RISC-V (RVV, Zbb/Zbc/Zbs), PowerPC (Altivec/VSX), s390x, LoongArch (LSX/LASX), MIPS (MSA), SPARC (VIS), and WebAssembly (SIMD128).
  • Added OpenMP 5.x GPU target offloading (__tgt_target_kernel, __tgt_target_data_*_mapper, nvptx64/amdgcn device module compilation) and constructs for simd, teams distribute, taskloop, taskyield, flush, ordered, master/masked, atomic, declare simd, and declare reduction.
  • Added TBAA metadata (!tbaa, !tbaa.struct), ISO/IEC TR 18037 fixed-point intrinsics, C++17 fold expressions (enk_fold), sizeof...(pack), new/delete array cookies, __builtin_clear_padding masks, unlowered C++ entity mangling, C++20 module initializer guards, construction vtables (_ZTC), MSVC vtordisp thunks and _ThrowInfo, full MSVC __asm parsing, DWARF v5 macros/fragments/inlinedAt, and multi-TU ThinLTO/FullLTO linking.
  • Added dev_tools/check_llvm_be_coverage.py and expanded the unit test suite to achieve 100.00% function, line, region, branch, and Doxygen coverage.

6. Testing, Fuzzing, & 100% Coverage Verification

Unit & Integration Test Suite (tests/)

The branch includes 29 standalone C++ test executables (27,486 lines of test code in tests/test_llvm_*.cpp) plus differential fuzzing and integration suites:

Test Target Source File LOC Coverage Scope
test_llvm_expressions tests/test_llvm_expressions.cpp 4,993 All arithmetic/logical/bitwise/comparison ops, bitfields, casts, complex numbers, new/delete cookies, calls, atomics, fold expressions, fixed-point, UBSan
test_llvm_declarations tests/test_llvm_declarations.cpp 3,194 Globals, linkage/visibility/COMDAT, TLS & __tls_init, local static guards, global_ctors/dtors, .CRT$XCU, C++20 modules, unlowered Itanium/MSVC mangling
test_llvm_abi tests/test_llvm_abi.cpp 2,555 All 12 target psABIs (SysV x86_64, Win64, AAPCS64/ARM64EC, x86-32, ARM32, RISC-V 64, LoongArch64, MIPS, PPC64, s390x, SPARC, Wasm), coercion, sret, byval, va_arg
test_llvm_Control_Flow tests/test_llvm_control_flow.cpp 1,471 if/else, while, do-while, for, switch (case ranges), goto, computed goto (indirectbr), VLAs, scoped RAII destructor cleanups
test_llvm_vtable_rtti tests/test_llvm_vtable_rtti.cpp 1,469 Itanium _ZTV/_ZTT/_ZTC, this/covariant/virtual thunks, MSVC VFTable/VBTable/vtordisp, Itanium & MSVC RTTI, dynamic_cast, typeid, devirtualization
test_llvm_const_evaluation tests/test_llvm_const_evaluation.cpp 1,262 Integers, IEEE-754 floats (NaN/Inf/fp80/fp128/half/bfloat), UTF-8/16/32 strings, nested struct/union/array aggregates, bitfield packing, address constants
test_llvm_type_lowering tests/test_llvm_type_lowering.cpp 1,210 Primitives, _BitInt, vectors, complex, fixed-point, recursive/packed structs, bitfields, unions, VLAs, functions, TBAA hierarchies (!tbaa, !tbaa.struct), GPU addr spaces
test_llvm_orchestrator tests/test_llvm_orchestrator.cpp 1,133 back_end(), llvm_gen_be(), DataLayout, target triple sync, CLI options, native toolchain discovery, linker args, multi-TU ThinLTO/FullLTO linking
test_llvm_debug_info tests/test_llvm_debug_info.cpp 920 DWARF v4/v5, CodeView, Split DWARF, lexical scopes, inlinedAt, composite/template/bitfield/enum types, SROA fragments, DWARF v5 macros, DIImportedEntity, DICommonBlock
test_llvm_builtins tests/test_llvm_builtins.cpp 778 Bit manipulation, overflow intrinsics, bit_cast, offsetof, shufflevector, convertvector, __builtin_clear_padding, source_location, __uuidof
test_llvm_exceptions tests/test_llvm_exceptions.cpp 726 Itanium landingpad/__cxa_throw/__cxa_begin_catch/noexcept terminate/dynamic specs, Windows SEH catchswitch/catchpad/cleanuppad, __leave, /EHa, _ThrowInfo
test_llvm_omp tests/test_llvm_omp.cpp 694 OpenMP parallel, for (static/dynamic), reduction, sections, single, task/taskloop, critical, barrier, ordered, flush, atomic, simd, declare simd, GPU target offloading
test_llvm_coro_atomics tests/test_llvm_coro_atomics.cpp 653 C++20 coroutine ramp/suspend/resume/destroy/promise/alignment/elision, @llvm.coro.* intrinsics, C11/C++20 atomic operations & fences
test_llvm_decl tests/test_llvm_decl.cpp 500 Additional scope traversal, dynamic initialization (dik_*), and multi-TU state reset validation
test_llvm_target_intrinsics tests/test_llvm_target_intrinsics.cpp 375 x86 (SSE/AVX/AVX-512/AMX/BMI/AES/SHA), ARM/AArch64 (NEON/SVE/CRC32/Crypto/barriers/sysregs), RISC-V, PPC, s390x, LoongArch, MIPS, SPARC, Wasm SIMD128
test_llvm_inline_asm tests/test_llvm_inline_asm.cpp 346 GNU extended asm, multi-output structs, constraint canonicalization, indirect memory *m, register clobbers, asm goto (callbr)
test_llvm_msvc_asm tests/test_llvm_msvc_asm.cpp 313 MSVC __asm Intel syntax parser, local/global variable substitution, addressing modes, directives, clobber inference
test_llvm_error tests/test_llvm_error.cpp 298 llvm_gen_be_error_t status codes, llvm_gen_be_error_context_t, source coordinate formatting, EDG front-end diagnostic bridge
test_llvm_type_translation tests/test_llvm_type_translation.cpp 232 End-to-end EDG type -> LLVM IR type equivalence tests
test_llvm_opt_pipeline tests/test_llvm_opt_pipeline.cpp 167 New PassBuilder (O0–Oz), vectorizers, coroutine passes, PGO gen/use, ASan/TSan/MSan/HWASan/SafeStack/ShadowCallStack
test_llvm_codegen tests/test_llvm_codegen.cpp 153 TargetMachine initialization, .ll/.bc/.s/.o emission, Split DWARF .dwo, ThinLTO summary emission
test_llvm_fuzz / fuzz_llvm_backend tests/test_llvm_fuzz.cpp 173 Differential fuzzing & libFuzzer entry point (LLVMFuzzerTestOneInput)
test_llvm_datalayout / lto / pgo / driver_flag / build_config / verifier / modules / stmt tests/test_llvm_*.cpp 730 Specialized verification for DataLayout strings, ThinLTO/FullLTO, PGO profiles, CLI flags, IR verifier, and C++20 modules

Reproducing Build, Test, & 100% Coverage Checks Locally

# 1. Verify 100% Doxygen Documentation Coverage across all 93 backend & test files:
python3 dev_tools/check_doc_coverage.py
# -> 100% Documentation Coverage Verified across 93 files!

# 2. Configure & Build with Clang Source-Based Coverage:
cmake --preset llvm-backend-coverage
cmake --build build/llvm-coverage -j

# 3. Execute all 29 test suites, merge profraw profiles, and assert 100.00% coverage:
EDG_COVERAGE_BUILD_DIR=build/llvm-coverage python3 dev_tools/check_llvm_be_coverage.py
# -> TOTAL: 0 missed functions, 0 missed lines, 0 missed regions, 0 missed branches
# -> 100.00% Function, Line, Region, and Branch Coverage Verified across all LLVM backend files!

… 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.
@wchilders-nvidia

Copy link
Copy Markdown
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
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 []
…TBAA, and 100% coverage

Expand the LLVM IR backend with target architecture SIMD/system intrinsics,
OpenMP 5.x device offloading and directives, TBAA and fixed-point support,
multi-TU LTO linking, enhanced C++ ABI/EH/debug emission, and 100% test and
documentation coverage:

- Target Architecture Intrinsics (src/llvm_gen_be_intrinsics.{h,cpp}):
  - Implement target-specific builtin lowering across x86/x86_64 (MMX, SSE,
    AVX, AVX2, AVX-512, AMX, BMI, AES, SHA), ARM/AArch64 (NEON, SVE/SVE2,
    CRC32, Crypto, barriers, system registers), RISC-V (RVV, Zbb/Zbc/Zbs),
    PowerPC (Altivec/VSX), s390x, LoongArch (LSX/LASX), MIPS, SPARC, and
    WebAssembly SIMD128.
- Expressions, Builtins, and Fixed-Point (src/llvm_gen_be_expr.{h,cpp}):
  - Add lowering for C++ new/delete (with array cookies), C++17 fold
    expressions (enk_fold), sizeof...(pack), ISO/IEC TR 18037 fixed-point
    arithmetic intrinsics, builtin operations (bit_cast, offsetof, shuffle,
    convertvector, source_location, uuidof), and padding masks for
    __builtin_clear_padding.
- Types, TBAA, and Address Spaces (src/llvm_gen_be_type.{h,cpp}):
  - Add LLVM TBAA type descriptors, access tags (!tbaa), and aggregate
    struct metadata (!tbaa.struct), fixed-point scaling, and symbolic GPU/target
    address-space mapping (nvptx64, amdgcn, spirv64).
- OpenMP 5.x Offloading and Directives (src/llvm_gen_be_omp.{h,cpp}):
  - Implement map/to/from clause parsing, target data/enter/exit/update
    mapper emission, GPU device module compilation (nvptx64/amdgcn), and
    constructs for simd, teams distribute, taskloop, taskyield, flush,
    ordered, master/masked, atomic, declare simd, and declare reduction.
- Declarations, VTables, RTTI, and EH (src/llvm_gen_be_decl.cpp,
  src/llvm_gen_be_vtable.{h,cpp}, src/llvm_gen_be_rtti.{h,cpp},
  src/llvm_gen_be_eh.{h,cpp}):
  - Add unlowered C++ entity mangling (Itanium and MSVC), C++20 module
    initializer guards, construction vtables, virtual/covariant and MSVC
    vtordisp thunks, MSVC _TypeDescriptor/_ThrowInfo emission, chained
    cleanup landing pads, SEH __leave, and /EHa async exception attributes.
- Inline Assembly, Coroutines, and Debug Info (src/llvm_gen_be_asm.{h,cpp},
  src/llvm_gen_be_coro.{h,cpp}, src/llvm_gen_be_debug*.{h,cpp}):
  - Add full MSVC __asm block parsing and GCC constraint canonicalization,
    coroutine ramp/suspend/destroy lowering, and DWARF 5/CodeView metadata
    for macros, imported entities, common blocks, fragments, and inlinedAt.
- Driver, CLI, and Build Integration (src/llvm_gen_be_driver.{h,cpp},
  src/cmd_line.{h,cpp}, src/cfe.c, cmake/):
  - Add native toolchain discovery, multi-TU ThinLTO/FullLTO linking, target
    configuration synchronization, expanded CLI flags (-O0..-Oz, -g,
    -gsplit-dwarf, -mcpu/-march/-mattr, -fPIC/-fPIE, -mcmodel, -fopenmp,
    -fstack-protector*, -fsanitize=hwaddress/safe-stack/shadow-call-stack),
    and CMake presets for debug, release, and coverage builds.
- Verification and Coverage (tests/, dev_tools/):
  - Add test_llvm_target_intrinsics and check_llvm_be_coverage.py, and
    expand unit, integration, and doc-coverage suites to verify 100%
    function, line, region, branch, and Doxygen coverage.
@SamuelMarks SamuelMarks changed the title LLVM IR backend (initial pass) LLVM IR backend Oct 17, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants