Browse Source

Merge pull request #2805 from odin-lang/llvm-17

Support LLVM 17.0.1
gingerBill 1 year ago
parent
commit
77227c2ff5
60 changed files with 3725 additions and 1277 deletions
  1. BIN
      LLVM-C.dll
  2. BIN
      bin/llvm/windows/LLVM-C.lib
  3. BIN
      bin/llvm/windows/clang_rt.asan-x86_64.lib
  4. 1 1
      build.bat
  5. 14 0
      core/runtime/core.odin
  6. 15 11
      core/runtime/internal.odin
  7. 8 0
      src/array.cpp
  8. 46 1
      src/build_settings.cpp
  9. 0 4
      src/check_decl.cpp
  10. 0 11
      src/check_expr.cpp
  11. 0 18
      src/check_type.cpp
  12. 31 1
      src/checker.cpp
  13. 2 4
      src/docs_writer.cpp
  14. 7 2
      src/llvm-c/BitReader.h
  15. 12 2
      src/llvm-c/Comdat.h
  16. 1 1
      src/llvm-c/Config/abi-breaking.h
  17. 3 3
      src/llvm-c/Config/llvm-config.h
  18. 181 94
      src/llvm-c/Core.h
  19. 72 36
      src/llvm-c/DebugInfo.h
  20. 38 0
      src/llvm-c/Deprecated.h
  21. 20 10
      src/llvm-c/DisassemblerTypes.h
  22. 11 0
      src/llvm-c/Error.h
  23. 12 2
      src/llvm-c/ErrorHandling.h
  24. 2 2
      src/llvm-c/ExternC.h
  25. 11 0
      src/llvm-c/IRReader.h
  26. 0 53
      src/llvm-c/Initialization.h
  27. 251 0
      src/llvm-c/LLJIT.h
  28. 0 66
      src/llvm-c/LinkTimeOptimizer.h
  29. 11 0
      src/llvm-c/Linker.h
  30. 18 16
      src/llvm-c/Object.h
  31. 1292 0
      src/llvm-c/Orc.h
  32. 0 169
      src/llvm-c/OrcBindings.h
  33. 103 0
      src/llvm-c/OrcEE.h
  34. 10 0
      src/llvm-c/Support.h
  35. 13 13
      src/llvm-c/Target.h
  36. 13 1
      src/llvm-c/TargetMachine.h
  37. 0 40
      src/llvm-c/Transforms/AggressiveInstCombine.h
  38. 0 56
      src/llvm-c/Transforms/Coroutines.h
  39. 0 96
      src/llvm-c/Transforms/IPO.h
  40. 0 40
      src/llvm-c/Transforms/InstCombine.h
  41. 116 0
      src/llvm-c/Transforms/PassBuilder.h
  42. 0 87
      src/llvm-c/Transforms/PassManagerBuilder.h
  43. 0 170
      src/llvm-c/Transforms/Scalar.h
  44. 0 50
      src/llvm-c/Transforms/Utils.h
  45. 0 47
      src/llvm-c/Transforms/Vectorize.h
  46. 0 3
      src/llvm-c/Types.h
  47. 79 0
      src/llvm-c/blake3.h
  48. 28 2
      src/llvm-c/lto.h
  49. 7 7
      src/llvm_abi.cpp
  50. 191 74
      src/llvm_backend.cpp
  51. 29 7
      src/llvm_backend.hpp
  52. 12 19
      src/llvm_backend_const.cpp
  53. 1 1
      src/llvm_backend_expr.cpp
  54. 55 4
      src/llvm_backend_general.cpp
  55. 12 4
      src/llvm_backend_opt.cpp
  56. 28 4
      src/llvm_backend_proc.cpp
  57. 915 41
      src/llvm_backend_type.cpp
  58. 13 2
      src/llvm_backend_utility.cpp
  59. 40 2
      src/main.cpp
  60. 1 0
      src/parser.hpp

BIN
LLVM-C.dll


BIN
bin/llvm/windows/LLVM-C.lib


BIN
bin/llvm/windows/clang_rt.asan-x86_64.lib


+ 1 - 1
build.bat

@@ -114,4 +114,4 @@ if %release_mode% EQU 0 odin run examples/demo
 
 
 del *.obj > NUL 2> NUL
 del *.obj > NUL 2> NUL
 
 
-:end_of_build
+:end_of_build

+ 14 - 0
core/runtime/core.odin

@@ -254,6 +254,7 @@ Typeid_Kind :: enum u8 {
 	Relative_Pointer,
 	Relative_Pointer,
 	Relative_Multi_Pointer,
 	Relative_Multi_Pointer,
 	Matrix,
 	Matrix,
+	Soa_Pointer,
 }
 }
 #assert(len(Typeid_Kind) < 32)
 #assert(len(Typeid_Kind) < 32)
 
 
@@ -510,6 +511,19 @@ Odin_Endian_Type :: type_of(ODIN_ENDIAN)
 */
 */
 Odin_Platform_Subtarget_Type :: type_of(ODIN_PLATFORM_SUBTARGET)
 Odin_Platform_Subtarget_Type :: type_of(ODIN_PLATFORM_SUBTARGET)
 
 
+/*
+	// Defined internally by the compiler
+	Odin_Sanitizer_Flag :: enum u32 {
+		Address = 0,
+		Memory  = 1,
+		Thread  = 2,
+	}
+	Odin_Sanitizer_Flags :: distinct bitset[Odin_Sanitizer_Flag; u32]
+
+	ODIN_SANITIZER_FLAGS // is a constant
+*/
+Odin_Sanitizer_Flags :: type_of(ODIN_SANITIZER_FLAGS)
+
 
 
 /////////////////////////////
 /////////////////////////////
 // Init Startup Procedures //
 // Init Startup Procedures //

+ 15 - 11
core/runtime/internal.odin

@@ -13,6 +13,9 @@ RUNTIME_LINKAGE :: "strong" when (
 	!IS_WASM) else "internal"
 	!IS_WASM) else "internal"
 RUNTIME_REQUIRE :: !ODIN_TILDE
 RUNTIME_REQUIRE :: !ODIN_TILDE
 
 
+@(private)
+__float16 :: f16 when __ODIN_LLVM_F16_SUPPORTED else u16
+
 
 
 @(private)
 @(private)
 byte_slice :: #force_inline proc "contextless" (data: rawptr, len: int) -> []byte #no_bounds_check {
 byte_slice :: #force_inline proc "contextless" (data: rawptr, len: int) -> []byte #no_bounds_check {
@@ -797,7 +800,7 @@ quo_quaternion256 :: proc "contextless" (q, r: quaternion256) -> quaternion256 {
 }
 }
 
 
 @(link_name="__truncsfhf2", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
 @(link_name="__truncsfhf2", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
-truncsfhf2 :: proc "c" (value: f32) -> u16 {
+truncsfhf2 :: proc "c" (value: f32) -> __float16 {
 	v: struct #raw_union { i: u32, f: f32 }
 	v: struct #raw_union { i: u32, f: f32 }
 	i, s, e, m: i32
 	i, s, e, m: i32
 
 
@@ -811,7 +814,7 @@ truncsfhf2 :: proc "c" (value: f32) -> u16 {
 
 
 	if e <= 0 {
 	if e <= 0 {
 		if e < -10 {
 		if e < -10 {
-			return u16(s)
+			return transmute(__float16)u16(s)
 		}
 		}
 		m = (m | 0x00800000) >> u32(1 - e)
 		m = (m | 0x00800000) >> u32(1 - e)
 
 
@@ -819,14 +822,14 @@ truncsfhf2 :: proc "c" (value: f32) -> u16 {
 			m += 0x00002000
 			m += 0x00002000
 		}
 		}
 
 
-		return u16(s | (m >> 13))
+		return transmute(__float16)u16(s | (m >> 13))
 	} else if e == 0xff - (127 - 15) {
 	} else if e == 0xff - (127 - 15) {
 		if m == 0 {
 		if m == 0 {
-			return u16(s | 0x7c00) /* NOTE(bill): infinity */
+			return transmute(__float16)u16(s | 0x7c00) /* NOTE(bill): infinity */
 		} else {
 		} else {
 			/* NOTE(bill): NAN */
 			/* NOTE(bill): NAN */
 			m >>= 13
 			m >>= 13
-			return u16(s | 0x7c00 | m | i32(m == 0))
+			return transmute(__float16)u16(s | 0x7c00 | m | i32(m == 0))
 		}
 		}
 	} else {
 	} else {
 		if m & 0x00001000 != 0 {
 		if m & 0x00001000 != 0 {
@@ -846,23 +849,24 @@ truncsfhf2 :: proc "c" (value: f32) -> u16 {
 				intrinsics.volatile_store(&f, g)
 				intrinsics.volatile_store(&f, g)
 			}
 			}
 
 
-			return u16(s | 0x7c00)
+			return transmute(__float16)u16(s | 0x7c00)
 		}
 		}
 
 
-		return u16(s | (e << 10) | (m >> 13))
+		return transmute(__float16)u16(s | (e << 10) | (m >> 13))
 	}
 	}
 }
 }
 
 
 
 
 @(link_name="__truncdfhf2", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
 @(link_name="__truncdfhf2", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
-truncdfhf2 :: proc "c" (value: f64) -> u16 {
+truncdfhf2 :: proc "c" (value: f64) -> __float16 {
 	return truncsfhf2(f32(value))
 	return truncsfhf2(f32(value))
 }
 }
 
 
 @(link_name="__gnu_h2f_ieee", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
 @(link_name="__gnu_h2f_ieee", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
-gnu_h2f_ieee :: proc "c" (value: u16) -> f32 {
+gnu_h2f_ieee :: proc "c" (value_: __float16) -> f32 {
 	fp32 :: struct #raw_union { u: u32, f: f32 }
 	fp32 :: struct #raw_union { u: u32, f: f32 }
 
 
+	value := transmute(u16)value_
 	v: fp32
 	v: fp32
 	magic, inf_or_nan: fp32
 	magic, inf_or_nan: fp32
 	magic.u = u32((254 - 15) << 23)
 	magic.u = u32((254 - 15) << 23)
@@ -879,12 +883,12 @@ gnu_h2f_ieee :: proc "c" (value: u16) -> f32 {
 
 
 
 
 @(link_name="__gnu_f2h_ieee", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
 @(link_name="__gnu_f2h_ieee", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
-gnu_f2h_ieee :: proc "c" (value: f32) -> u16 {
+gnu_f2h_ieee :: proc "c" (value: f32) -> __float16 {
 	return truncsfhf2(value)
 	return truncsfhf2(value)
 }
 }
 
 
 @(link_name="__extendhfsf2", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
 @(link_name="__extendhfsf2", linkage=RUNTIME_LINKAGE, require=RUNTIME_REQUIRE)
-extendhfsf2 :: proc "c" (value: u16) -> f32 {
+extendhfsf2 :: proc "c" (value: __float16) -> f32 {
 	return gnu_h2f_ieee(value)
 	return gnu_h2f_ieee(value)
 }
 }
 
 

+ 8 - 0
src/array.cpp

@@ -314,6 +314,14 @@ gb_internal void array_add(Array<T> *array, T const &t) {
 	array->count++;
 	array->count++;
 }
 }
 
 
+gb_internal void array_add(Array<char const *> *array, char const *t) {
+	if (array->capacity < array->count+1) {
+		array__grow(array, 0);
+	}
+	array->data[array->count] = t;
+	array->count++;
+}
+
 template <typename T>
 template <typename T>
 gb_internal T *array_add_and_get(Array<T> *array) {
 gb_internal T *array_add_and_get(Array<T> *array) {
 	if (array->count < array->capacity) {
 	if (array->count < array->capacity) {

+ 46 - 1
src/build_settings.cpp

@@ -264,6 +264,14 @@ u64 get_vet_flag_from_name(String const &name) {
 }
 }
 
 
 
 
+enum SanitizerFlags : u32 {
+	SanitizerFlag_NONE = 0,
+	SanitizerFlag_Address = 1u<<0,
+	SanitizerFlag_Memory  = 1u<<1,
+	SanitizerFlag_Thread  = 1u<<2,
+};
+
+
 
 
 // This stores the information for the specify architecture of this build
 // This stores the information for the specify architecture of this build
 struct BuildContext {
 struct BuildContext {
@@ -305,6 +313,7 @@ struct BuildContext {
 	String pdb_filepath;
 	String pdb_filepath;
 
 
 	u64 vet_flags;
 	u64 vet_flags;
+	u32 sanitizer_flags;
 
 
 	bool   has_resource;
 	bool   has_resource;
 	String link_flags;
 	String link_flags;
@@ -1381,7 +1390,7 @@ gb_internal void init_build_context(TargetMetrics *cross_target, Subtarget subta
 		bc->optimization_level = -1; // -o:none
 		bc->optimization_level = -1; // -o:none
 	}
 	}
 
 
-	bc->optimization_level = gb_clamp(bc->optimization_level, -1, 2);
+	bc->optimization_level = gb_clamp(bc->optimization_level, -1, 3);
 
 
 	// ENFORCE DYNAMIC MAP CALLS
 	// ENFORCE DYNAMIC MAP CALLS
 	bc->dynamic_map_calls = true;
 	bc->dynamic_map_calls = true;
@@ -1738,6 +1747,42 @@ gb_internal bool init_build_paths(String init_filename) {
 		return false;
 		return false;
 	}
 	}
 
 
+	if (build_context.sanitizer_flags & SanitizerFlag_Address) {
+		switch (build_context.metrics.os) {
+		case TargetOs_windows:
+		case TargetOs_linux:
+		case TargetOs_darwin:
+			break;
+		default:
+			gb_printf_err("-sanitize:address is only supported on windows, linux, and darwin\n");
+			return false;
+		}
+	}
+
+	if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
+		switch (build_context.metrics.os) {
+		case TargetOs_linux:
+			break;
+		default:
+			gb_printf_err("-sanitize:memory is only supported on linux\n");
+			return false;
+		}
+		if (build_context.metrics.os != TargetOs_linux) {
+			return false;
+		}
+	}
+
+	if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
+		switch (build_context.metrics.os) {
+		case TargetOs_linux:
+		case TargetOs_darwin:
+			break;
+		default:
+			gb_printf_err("-sanitize:thread is only supported on linux and darwin\n");
+			return false;
+		}
+	}
+
 
 
 	if (bc->target_features_string.len != 0) {
 	if (bc->target_features_string.len != 0) {
 		enable_target_feature({}, bc->target_features_string);
 		enable_target_feature({}, bc->target_features_string);

+ 0 - 4
src/check_decl.cpp

@@ -1336,10 +1336,6 @@ gb_internal void check_proc_group_decl(CheckerContext *ctx, Entity *pg_entity, D
 				is_invalid = true;
 				is_invalid = true;
 				break;
 				break;
 			case ProcOverload_Polymorphic:
 			case ProcOverload_Polymorphic:
-				#if 0
-				error(p->token, "Overloaded procedure '%.*s' has a polymorphic counterpart in the procedure group '%.*s' which is not allowed", LIT(name), LIT(proc_group_name));
-				is_invalid = true;
-				#endif
 				break;
 				break;
 			case ProcOverload_ParamCount:
 			case ProcOverload_ParamCount:
 			case ProcOverload_ParamTypes:
 			case ProcOverload_ParamTypes:

+ 0 - 11
src/check_expr.cpp

@@ -3683,18 +3683,7 @@ gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Typ
 		ExactValue b = y->value;
 		ExactValue b = y->value;
 
 
 		if (!is_type_constant_type(x->type)) {
 		if (!is_type_constant_type(x->type)) {
-		#if 0
-			gbString xt = type_to_string(x->type);
-			gbString err_str = expr_to_string(node);
-			error(op, "Invalid type, '%s', for constant binary expression '%s'", xt, err_str);
-			gb_string_free(err_str);
-			gb_string_free(xt);
-			x->mode = Addressing_Invalid;
-		#else
-			// NOTE(bill, 2021-04-21): The above is literally a useless error message.
-			// Why did I add it in the first place?!
 			x->mode = Addressing_Value;
 			x->mode = Addressing_Value;
-		#endif
 			return;
 			return;
 		}
 		}
 
 

+ 0 - 18
src/check_type.cpp

@@ -1059,24 +1059,6 @@ gb_internal void check_bit_set_type(CheckerContext *c, Type *type, Type *named_t
 	} else {
 	} else {
 		Type *elem = check_type_expr(c, bs->elem, nullptr);
 		Type *elem = check_type_expr(c, bs->elem, nullptr);
 
 
-		#if 0
-		if (named_type != nullptr && named_type->kind == Type_Named &&
-		    elem->kind == Type_Enum) {
-			// NOTE(bill): Anonymous enumeration
-
-			String prefix = named_type->Named.name;
-			String enum_name = concatenate_strings(heap_allocator(), prefix, str_lit(".enum"));
-
-			Token token = make_token_ident(enum_name);
-
-			Entity *e = alloc_entity_type_name(nullptr, token, nullptr, EntityState_Resolved);
-			Type *named = alloc_type_named(enum_name, elem, e);
-			e->type = named;
-			e->TypeName.is_type_alias = true;
-			elem = named;
-		}
-		#endif
-
 		type->BitSet.elem = elem;
 		type->BitSet.elem = elem;
 		if (!is_type_valid_bit_set_elem(elem)) {
 		if (!is_type_valid_bit_set_elem(elem)) {
 			error(bs->elem, "Expected an enum type for a bit_set");
 			error(bs->elem, "Expected an enum type for a bit_set");

+ 31 - 1
src/checker.cpp

@@ -858,7 +858,7 @@ gb_internal AstPackage *create_builtin_package(char const *name) {
 	gbAllocator a = permanent_allocator();
 	gbAllocator a = permanent_allocator();
 	AstPackage *pkg = gb_alloc_item(a, AstPackage);
 	AstPackage *pkg = gb_alloc_item(a, AstPackage);
 	pkg->name = make_string_c(name);
 	pkg->name = make_string_c(name);
-	pkg->kind = Package_Normal;
+	pkg->kind = Package_Builtin;
 
 
 	pkg->scope = create_scope(nullptr, nullptr);
 	pkg->scope = create_scope(nullptr, nullptr);
 	pkg->scope->flags |= ScopeFlag_Pkg | ScopeFlag_Global | ScopeFlag_Builtin;
 	pkg->scope->flags |= ScopeFlag_Pkg | ScopeFlag_Global | ScopeFlag_Builtin;
@@ -935,6 +935,7 @@ gb_internal i64 odin_compile_timestamp(void) {
 	return ns_after_1970;
 	return ns_after_1970;
 }
 }
 
 
+gb_internal bool lb_use_new_pass_system(void);
 
 
 gb_internal void init_universal(void) {
 gb_internal void init_universal(void) {
 	BuildContext *bc = &build_context;
 	BuildContext *bc = &build_context;
@@ -1083,6 +1084,35 @@ gb_internal void init_universal(void) {
 
 
 	add_global_constant("ODIN_COMPILE_TIMESTAMP", t_untyped_integer, exact_value_i64(odin_compile_timestamp()));
 	add_global_constant("ODIN_COMPILE_TIMESTAMP", t_untyped_integer, exact_value_i64(odin_compile_timestamp()));
 
 
+	add_global_bool_constant("__ODIN_LLVM_F16_SUPPORTED", lb_use_new_pass_system());
+
+	{
+		GlobalEnumValue values[3] = {
+			{"Address", 0},
+			{"Memory",  1},
+			{"Thread",  2},
+		};
+
+		Type *enum_type = nullptr;
+		auto flags = add_global_enum_type(str_lit("Odin_Sanitizer_Flag"), values, gb_count_of(values), &enum_type);
+		Type *bit_set_type = alloc_type_bit_set();
+		bit_set_type->BitSet.elem = enum_type;
+		bit_set_type->BitSet.underlying = t_u32;
+		bit_set_type->BitSet.lower = 0;
+		bit_set_type->BitSet.upper = 2;
+		type_size_of(bit_set_type);
+
+		String type_name = str_lit("Odin_Sanitizer_Flags");
+		Scope *scope = create_scope(nullptr, builtin_pkg->scope);
+		Entity *entity = alloc_entity_type_name(scope, make_token_ident(type_name), nullptr, EntityState_Resolved);
+
+		Type *named_type = alloc_type_named(type_name, bit_set_type, entity);
+		set_base_type(named_type, bit_set_type);
+
+		add_global_constant("ODIN_SANITIZER_FLAGS", named_type, exact_value_u64(bc->sanitizer_flags));
+	}
+
+
 
 
 // Builtin Procedures
 // Builtin Procedures
 	for (isize i = 0; i < gb_count_of(builtin_procs); i++) {
 	for (isize i = 0; i < gb_count_of(builtin_procs); i++) {

+ 2 - 4
src/docs_writer.cpp

@@ -1101,11 +1101,9 @@ gb_internal void odin_doc_write_docs(OdinDocWriter *w) {
 		case Package_Init:
 		case Package_Init:
 			pkg_flags |= OdinDocPkgFlag_Init;
 			pkg_flags |= OdinDocPkgFlag_Init;
 			break;
 			break;
-		}
-		if (pkg->name == "builtin") {
-			pkg_flags |= OdinDocPkgFlag_Builtin;
-		} else if (pkg->name == "intrinsics") {
+		case Package_Builtin:
 			pkg_flags |= OdinDocPkgFlag_Builtin;
 			pkg_flags |= OdinDocPkgFlag_Builtin;
+			break;
 		}
 		}
 
 
 		OdinDocPkg doc_pkg = {};
 		OdinDocPkg doc_pkg = {};

+ 7 - 2
src/llvm-c/BitReader.h

@@ -61,8 +61,13 @@ LLVMBool LLVMGetBitcodeModuleInContext(LLVMContextRef ContextRef,
                                        LLVMMemoryBufferRef MemBuf,
                                        LLVMMemoryBufferRef MemBuf,
                                        LLVMModuleRef *OutM, char **OutMessage);
                                        LLVMModuleRef *OutM, char **OutMessage);
 
 
-/** Reads a module from the specified path, returning via the OutMP parameter a
- * module provider which performs lazy deserialization. Returns 0 on success. */
+/** Reads a module from the given memory buffer, returning via the OutMP
+ * parameter a module provider which performs lazy deserialization.
+ *
+ * Returns 0 on success.
+ *
+ * Takes ownership of \p MemBuf if (and only if) the module was read
+ * successfully. */
 LLVMBool LLVMGetBitcodeModuleInContext2(LLVMContextRef ContextRef,
 LLVMBool LLVMGetBitcodeModuleInContext2(LLVMContextRef ContextRef,
                                         LLVMMemoryBufferRef MemBuf,
                                         LLVMMemoryBufferRef MemBuf,
                                         LLVMModuleRef *OutM);
                                         LLVMModuleRef *OutM);

+ 12 - 2
src/llvm-c/Comdat.h

@@ -19,14 +19,20 @@
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @defgroup LLVMCCoreComdat Comdats
+ * @ingroup LLVMCCore
+ *
+ * @{
+ */
+
 typedef enum {
 typedef enum {
   LLVMAnyComdatSelectionKind,        ///< The linker may choose any COMDAT.
   LLVMAnyComdatSelectionKind,        ///< The linker may choose any COMDAT.
   LLVMExactMatchComdatSelectionKind, ///< The data referenced by the COMDAT must
   LLVMExactMatchComdatSelectionKind, ///< The data referenced by the COMDAT must
                                      ///< be the same.
                                      ///< be the same.
   LLVMLargestComdatSelectionKind,    ///< The linker will choose the largest
   LLVMLargestComdatSelectionKind,    ///< The linker will choose the largest
                                      ///< COMDAT.
                                      ///< COMDAT.
-  LLVMNoDuplicatesComdatSelectionKind, ///< No other Module may specify this
-                                       ///< COMDAT.
+  LLVMNoDeduplicateComdatSelectionKind, ///< No deduplication is performed.
   LLVMSameSizeComdatSelectionKind ///< The data referenced by the COMDAT must be
   LLVMSameSizeComdatSelectionKind ///< The data referenced by the COMDAT must be
                                   ///< the same size.
                                   ///< the same size.
 } LLVMComdatSelectionKind;
 } LLVMComdatSelectionKind;
@@ -67,6 +73,10 @@ LLVMComdatSelectionKind LLVMGetComdatSelectionKind(LLVMComdatRef C);
  */
  */
 void LLVMSetComdatSelectionKind(LLVMComdatRef C, LLVMComdatSelectionKind Kind);
 void LLVMSetComdatSelectionKind(LLVMComdatRef C, LLVMComdatSelectionKind Kind);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 1 - 1
src/llvm-c/Config/abi-breaking.h

@@ -1,4 +1,4 @@
-/*===------- llvm/Config/abi-breaking.h - llvm configuration -------*- C -*-===*/
+/*===------- llvm-c/Config//abi-breaking.h - llvm configuration -------*- C -*-===*/
 /*                                                                            */
 /*                                                                            */
 /* Part of the LLVM Project, under the Apache License v2.0 with LLVM          */
 /* Part of the LLVM Project, under the Apache License v2.0 with LLVM          */
 /* Exceptions.                                                                */
 /* Exceptions.                                                                */

+ 3 - 3
src/llvm-c/Config/llvm-config.h

@@ -1,4 +1,4 @@
-/*===------- llvm/Config/llvm-config.h - llvm configuration -------*- C -*-===*/
+/*===------- llvm-c/Config//llvm-config.h - llvm configuration -------*- C -*-===*/
 /*                                                                            */
 /*                                                                            */
 /* Part of the LLVM Project, under the Apache License v2.0 with LLVM          */
 /* Part of the LLVM Project, under the Apache License v2.0 with LLVM          */
 /* Exceptions.                                                                */
 /* Exceptions.                                                                */
@@ -66,7 +66,7 @@
 #define LLVM_USE_PERF 0
 #define LLVM_USE_PERF 0
 
 
 /* Major version of the LLVM API */
 /* Major version of the LLVM API */
-#define LLVM_VERSION_MAJOR 12
+#define LLVM_VERSION_MAJOR 17
 
 
 /* Minor version of the LLVM API */
 /* Minor version of the LLVM API */
 #define LLVM_VERSION_MINOR 0
 #define LLVM_VERSION_MINOR 0
@@ -75,7 +75,7 @@
 #define LLVM_VERSION_PATCH 1
 #define LLVM_VERSION_PATCH 1
 
 
 /* LLVM version string */
 /* LLVM version string */
-#define LLVM_VERSION_STRING "12.0.1"
+#define LLVM_VERSION_STRING "17.0.1"
 
 
 /* Whether LLVM records statistics for use with GetStatistics(),
 /* Whether LLVM records statistics for use with GetStatistics(),
  * PrintStatistics() or PrintStatisticsJSON()
  * PrintStatistics() or PrintStatisticsJSON()

+ 181 - 94
src/llvm-c/Core.h

@@ -15,8 +15,10 @@
 #ifndef LLVM_C_CORE_H
 #ifndef LLVM_C_CORE_H
 #define LLVM_C_CORE_H
 #define LLVM_C_CORE_H
 
 
+#include "llvm-c/Deprecated.h"
 #include "llvm-c/ErrorHandling.h"
 #include "llvm-c/ErrorHandling.h"
 #include "llvm-c/ExternC.h"
 #include "llvm-c/ExternC.h"
+
 #include "llvm-c/Types.h"
 #include "llvm-c/Types.h"
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
@@ -163,7 +165,8 @@ typedef enum {
   LLVMTokenTypeKind,     /**< Tokens */
   LLVMTokenTypeKind,     /**< Tokens */
   LLVMScalableVectorTypeKind, /**< Scalable SIMD vector type */
   LLVMScalableVectorTypeKind, /**< Scalable SIMD vector type */
   LLVMBFloatTypeKind,    /**< 16 bit brain floating point type */
   LLVMBFloatTypeKind,    /**< 16 bit brain floating point type */
-  LLVMX86_AMXTypeKind    /**< X86 AMX */
+  LLVMX86_AMXTypeKind,   /**< X86 AMX */
+  LLVMTargetExtTypeKind, /**< Target extension type */
 } LLVMTypeKind;
 } LLVMTypeKind;
 
 
 typedef enum {
 typedef enum {
@@ -282,7 +285,8 @@ typedef enum {
   LLVMInlineAsmValueKind,
   LLVMInlineAsmValueKind,
 
 
   LLVMInstructionValueKind,
   LLVMInstructionValueKind,
-  LLVMPoisonValueValueKind
+  LLVMPoisonValueValueKind,
+  LLVMConstantTargetNoneValueKind,
 } LLVMValueKind;
 } LLVMValueKind;
 
 
 typedef enum {
 typedef enum {
@@ -379,8 +383,14 @@ typedef enum {
                               the old one */
                               the old one */
     LLVMAtomicRMWBinOpFAdd, /**< Add a floating point value and return the
     LLVMAtomicRMWBinOpFAdd, /**< Add a floating point value and return the
                               old one */
                               old one */
-    LLVMAtomicRMWBinOpFSub /**< Subtract a floating point value and return the
-                             old one */
+    LLVMAtomicRMWBinOpFSub, /**< Subtract a floating point value and return the
+                            old one */
+    LLVMAtomicRMWBinOpFMax, /**< Sets the value if it's greater than the
+                             original using an floating point comparison and
+                             return the old one */
+    LLVMAtomicRMWBinOpFMin, /**< Sets the value if it's smaller than the
+                             original using an floating point comparison and
+                             return the old one */
 } LLVMAtomicRMWBinOp;
 } LLVMAtomicRMWBinOp;
 
 
 typedef enum {
 typedef enum {
@@ -464,13 +474,21 @@ typedef unsigned LLVMAttributeIndex;
  * @}
  * @}
  */
  */
 
 
-void LLVMInitializeCore(LLVMPassRegistryRef R);
-
 /** Deallocate and destroy all ManagedStatic variables.
 /** Deallocate and destroy all ManagedStatic variables.
     @see llvm::llvm_shutdown
     @see llvm::llvm_shutdown
     @see ManagedStatic */
     @see ManagedStatic */
 void LLVMShutdown(void);
 void LLVMShutdown(void);
 
 
+/*===-- Version query -----------------------------------------------------===*/
+
+/**
+ * Return the major, minor, and patch version of LLVM
+ *
+ * The version components are returned via the function's three output
+ * parameters or skipped if a NULL pointer was supplied.
+ */
+void LLVMGetVersion(unsigned *Major, unsigned *Minor, unsigned *Patch);
+
 /*===-- Error handling ----------------------------------------------------===*/
 /*===-- Error handling ----------------------------------------------------===*/
 
 
 char *LLVMCreateMessage(const char *Message);
 char *LLVMCreateMessage(const char *Message);
@@ -872,11 +890,11 @@ void LLVMAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm, size_t Len);
  *
  *
  * @see InlineAsm::get()
  * @see InlineAsm::get()
  */
  */
-LLVMValueRef LLVMGetInlineAsm(LLVMTypeRef Ty,
-                              char *AsmString, size_t AsmStringSize,
-                              char *Constraints, size_t ConstraintsSize,
-                              LLVMBool HasSideEffects, LLVMBool IsAlignStack,
-                              LLVMInlineAsmDialect Dialect);
+LLVMValueRef LLVMGetInlineAsm(LLVMTypeRef Ty, char *AsmString,
+                              size_t AsmStringSize, char *Constraints,
+                              size_t ConstraintsSize, LLVMBool HasSideEffects,
+                              LLVMBool IsAlignStack,
+                              LLVMInlineAsmDialect Dialect, LLVMBool CanThrow);
 
 
 /**
 /**
  * Obtain the context to which this module is associated.
  * Obtain the context to which this module is associated.
@@ -1389,9 +1407,7 @@ LLVMBool LLVMIsLiteralStruct(LLVMTypeRef StructTy);
  */
  */
 
 
 /**
 /**
- * Obtain the type of elements within a sequential type.
- *
- * This works on array, vector, and pointer types.
+ * Obtain the element type of an array or vector type.
  *
  *
  * @see llvm::SequentialType::getElementType()
  * @see llvm::SequentialType::getElementType()
  */
  */
@@ -1417,19 +1433,42 @@ unsigned LLVMGetNumContainedTypes(LLVMTypeRef Tp);
  * The created type will exist in the context that its element type
  * The created type will exist in the context that its element type
  * exists in.
  * exists in.
  *
  *
+ * @deprecated LLVMArrayType is deprecated in favor of the API accurate
+ * LLVMArrayType2
  * @see llvm::ArrayType::get()
  * @see llvm::ArrayType::get()
  */
  */
 LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount);
 LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount);
 
 
+/**
+ * Create a fixed size array type that refers to a specific type.
+ *
+ * The created type will exist in the context that its element type
+ * exists in.
+ *
+ * @see llvm::ArrayType::get()
+ */
+LLVMTypeRef LLVMArrayType2(LLVMTypeRef ElementType, uint64_t ElementCount);
+
 /**
 /**
  * Obtain the length of an array type.
  * Obtain the length of an array type.
  *
  *
  * This only works on types that represent arrays.
  * This only works on types that represent arrays.
  *
  *
+ * @deprecated LLVMGetArrayLength is deprecated in favor of the API accurate
+ * LLVMGetArrayLength2
  * @see llvm::ArrayType::getNumElements()
  * @see llvm::ArrayType::getNumElements()
  */
  */
 unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
 unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
 
 
+/**
+ * Obtain the length of an array type.
+ *
+ * This only works on types that represent arrays.
+ *
+ * @see llvm::ArrayType::getNumElements()
+ */
+uint64_t LLVMGetArrayLength2(LLVMTypeRef ArrayTy);
+
 /**
 /**
  * Create a pointer type that points to a defined type.
  * Create a pointer type that points to a defined type.
  *
  *
@@ -1440,6 +1479,22 @@ unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
  */
  */
 LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace);
 LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace);
 
 
+/**
+ * Determine whether a pointer is opaque.
+ *
+ * True if this is an instance of an opaque PointerType.
+ *
+ * @see llvm::Type::isOpaquePointerTy()
+ */
+LLVMBool LLVMPointerTypeIsOpaque(LLVMTypeRef Ty);
+
+/**
+ * Create an opaque pointer type in a context.
+ *
+ * @see llvm::PointerType::get()
+ */
+LLVMTypeRef LLVMPointerTypeInContext(LLVMContextRef C, unsigned AddressSpace);
+
 /**
 /**
  * Obtain the address space of a pointer type.
  * Obtain the address space of a pointer type.
  *
  *
@@ -1530,6 +1585,15 @@ LLVMTypeRef LLVMLabelType(void);
 LLVMTypeRef LLVMX86MMXType(void);
 LLVMTypeRef LLVMX86MMXType(void);
 LLVMTypeRef LLVMX86AMXType(void);
 LLVMTypeRef LLVMX86AMXType(void);
 
 
+/**
+ * Create a target extension type in LLVM context.
+ */
+LLVMTypeRef LLVMTargetExtTypeInContext(LLVMContextRef C, const char *Name,
+                                       LLVMTypeRef *TypeParams,
+                                       unsigned TypeParamCount,
+                                       unsigned *IntParams,
+                                       unsigned IntParamCount);
+
 /**
 /**
  * @}
  * @}
  */
  */
@@ -1580,10 +1644,10 @@ LLVMTypeRef LLVMX86AMXType(void);
       macro(ConstantVector)                 \
       macro(ConstantVector)                 \
       macro(GlobalValue)                    \
       macro(GlobalValue)                    \
         macro(GlobalAlias)                  \
         macro(GlobalAlias)                  \
-        macro(GlobalIFunc)                  \
         macro(GlobalObject)                 \
         macro(GlobalObject)                 \
           macro(Function)                   \
           macro(Function)                   \
           macro(GlobalVariable)             \
           macro(GlobalVariable)             \
+          macro(GlobalIFunc)                \
       macro(UndefValue)                     \
       macro(UndefValue)                     \
       macro(PoisonValue)                    \
       macro(PoisonValue)                    \
     macro(Instruction)                      \
     macro(Instruction)                      \
@@ -1740,6 +1804,7 @@ LLVMBool LLVMIsPoison(LLVMValueRef Val);
 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST)
 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST)
 
 
 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val);
 LLVMValueRef LLVMIsAMDNode(LLVMValueRef Val);
+LLVMValueRef LLVMIsAValueAsMetadata(LLVMValueRef Val);
 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val);
 LLVMValueRef LLVMIsAMDString(LLVMValueRef Val);
 
 
 /** Deprecated: Use LLVMGetValueName2 instead. */
 /** Deprecated: Use LLVMGetValueName2 instead. */
@@ -2072,11 +2137,21 @@ LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
 /**
 /**
  * Create a ConstantArray from values.
  * Create a ConstantArray from values.
  *
  *
+ * @deprecated LLVMConstArray is deprecated in favor of the API accurate
+ * LLVMConstArray2
  * @see llvm::ConstantArray::get()
  * @see llvm::ConstantArray::get()
  */
  */
 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
                             LLVMValueRef *ConstantVals, unsigned Length);
                             LLVMValueRef *ConstantVals, unsigned Length);
 
 
+/**
+ * Create a ConstantArray from values.
+ *
+ * @see llvm::ConstantArray::get()
+ */
+LLVMValueRef LLVMConstArray2(LLVMTypeRef ElementTy, LLVMValueRef *ConstantVals,
+                             uint64_t Length);
+
 /**
 /**
  * Create a non-anonymous ConstantStruct from values.
  * Create a non-anonymous ConstantStruct from values.
  *
  *
@@ -2086,12 +2161,24 @@ LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
                                   LLVMValueRef *ConstantVals,
                                   LLVMValueRef *ConstantVals,
                                   unsigned Count);
                                   unsigned Count);
 
 
+/**
+ * Get element of a constant aggregate (struct, array or vector) at the
+ * specified index. Returns null if the index is out of range, or it's not
+ * possible to determine the element (e.g., because the constant is a
+ * constant expression.)
+ *
+ * @see llvm::Constant::getAggregateElement()
+ */
+LLVMValueRef LLVMGetAggregateElement(LLVMValueRef C, unsigned Idx);
+
 /**
 /**
  * Get an element at specified index as a constant.
  * Get an element at specified index as a constant.
  *
  *
  * @see ConstantDataSequential::getElementAsConstant()
  * @see ConstantDataSequential::getElementAsConstant()
  */
  */
-LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx);
+LLVM_ATTRIBUTE_C_DEPRECATED(
+    LLVMValueRef LLVMGetElementAsConstant(LLVMValueRef C, unsigned idx),
+    "Use LLVMGetAggregateElement instead");
 
 
 /**
 /**
  * Create a ConstantVector from values.
  * Create a ConstantVector from values.
@@ -2119,28 +2206,16 @@ LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty);
 LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNeg(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNSWNeg(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNUWNeg(LLVMValueRef ConstantVal);
-LLVMValueRef LLVMConstFNeg(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstNot(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNSWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNUWAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstFAdd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNSWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNUWSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstFSub(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNSWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstNUWMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstFMul(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstExactUDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstExactSDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstFDiv(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstURem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstSRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstFRem(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstAnd(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstOr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstXor(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
@@ -2151,13 +2226,8 @@ LLVMValueRef LLVMConstFCmp(LLVMRealPredicate Predicate,
 LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstShl(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstLShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
 LLVMValueRef LLVMConstAShr(LLVMValueRef LHSConstant, LLVMValueRef RHSConstant);
-LLVMValueRef LLVMConstGEP(LLVMValueRef ConstantVal,
-                          LLVMValueRef *ConstantIndices, unsigned NumIndices);
 LLVMValueRef LLVMConstGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
 LLVMValueRef LLVMConstGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
                            LLVMValueRef *ConstantIndices, unsigned NumIndices);
                            LLVMValueRef *ConstantIndices, unsigned NumIndices);
-LLVMValueRef LLVMConstInBoundsGEP(LLVMValueRef ConstantVal,
-                                  LLVMValueRef *ConstantIndices,
-                                  unsigned NumIndices);
 LLVMValueRef LLVMConstInBoundsGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
 LLVMValueRef LLVMConstInBoundsGEP2(LLVMTypeRef Ty, LLVMValueRef ConstantVal,
                                    LLVMValueRef *ConstantIndices,
                                    LLVMValueRef *ConstantIndices,
                                    unsigned NumIndices);
                                    unsigned NumIndices);
@@ -2185,9 +2255,6 @@ LLVMValueRef LLVMConstPointerCast(LLVMValueRef ConstantVal,
 LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
 LLVMValueRef LLVMConstIntCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType,
                               LLVMBool isSigned);
                               LLVMBool isSigned);
 LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
 LLVMValueRef LLVMConstFPCast(LLVMValueRef ConstantVal, LLVMTypeRef ToType);
-LLVMValueRef LLVMConstSelect(LLVMValueRef ConstantCondition,
-                             LLVMValueRef ConstantIfTrue,
-                             LLVMValueRef ConstantIfFalse);
 LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
 LLVMValueRef LLVMConstExtractElement(LLVMValueRef VectorConstant,
                                      LLVMValueRef IndexConstant);
                                      LLVMValueRef IndexConstant);
 LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
 LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
@@ -2196,11 +2263,6 @@ LLVMValueRef LLVMConstInsertElement(LLVMValueRef VectorConstant,
 LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
 LLVMValueRef LLVMConstShuffleVector(LLVMValueRef VectorAConstant,
                                     LLVMValueRef VectorBConstant,
                                     LLVMValueRef VectorBConstant,
                                     LLVMValueRef MaskConstant);
                                     LLVMValueRef MaskConstant);
-LLVMValueRef LLVMConstExtractValue(LLVMValueRef AggConstant, unsigned *IdxList,
-                                   unsigned NumIdx);
-LLVMValueRef LLVMConstInsertValue(LLVMValueRef AggConstant,
-                                  LLVMValueRef ElementValueConstant,
-                                  unsigned *IdxList, unsigned NumIdx);
 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB);
 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB);
 
 
 /** Deprecated: Use LLVMGetInlineAsm instead. */
 /** Deprecated: Use LLVMGetInlineAsm instead. */
@@ -2261,6 +2323,8 @@ void LLVMSetUnnamedAddr(LLVMValueRef Global, LLVMBool HasUnnamedAddr);
  * @see llvm::AllocaInst::getAlignment()
  * @see llvm::AllocaInst::getAlignment()
  * @see llvm::LoadInst::getAlignment()
  * @see llvm::LoadInst::getAlignment()
  * @see llvm::StoreInst::getAlignment()
  * @see llvm::StoreInst::getAlignment()
+ * @see llvm::AtomicRMWInst::setAlignment()
+ * @see llvm::AtomicCmpXchgInst::setAlignment()
  * @see llvm::GlobalValue::getAlignment()
  * @see llvm::GlobalValue::getAlignment()
  */
  */
 unsigned LLVMGetAlignment(LLVMValueRef V);
 unsigned LLVMGetAlignment(LLVMValueRef V);
@@ -2270,6 +2334,8 @@ unsigned LLVMGetAlignment(LLVMValueRef V);
  * @see llvm::AllocaInst::setAlignment()
  * @see llvm::AllocaInst::setAlignment()
  * @see llvm::LoadInst::setAlignment()
  * @see llvm::LoadInst::setAlignment()
  * @see llvm::StoreInst::setAlignment()
  * @see llvm::StoreInst::setAlignment()
+ * @see llvm::AtomicRMWInst::setAlignment()
+ * @see llvm::AtomicCmpXchgInst::setAlignment()
  * @see llvm::GlobalValue::setAlignment()
  * @see llvm::GlobalValue::setAlignment()
  */
  */
 void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes);
 void LLVMSetAlignment(LLVMValueRef V, unsigned Bytes);
@@ -2373,8 +2439,15 @@ void LLVMSetExternallyInitialized(LLVMValueRef GlobalVar, LLVMBool IsExtInit);
  *
  *
  * @{
  * @{
  */
  */
-LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Aliasee,
-                          const char *Name);
+
+/**
+ * Add a GlobalAlias with the given value type, address space and aliasee.
+ *
+ * @see llvm::GlobalAlias::create()
+ */
+LLVMValueRef LLVMAddAlias2(LLVMModuleRef M, LLVMTypeRef ValueTy,
+                           unsigned AddrSpace, LLVMValueRef Aliasee,
+                           const char *Name);
 
 
 /**
 /**
  * Obtain a GlobalAlias value from a Module by its name.
  * Obtain a GlobalAlias value from a Module by its name.
@@ -2510,6 +2583,12 @@ LLVMTypeRef LLVMIntrinsicGetType(LLVMContextRef Ctx, unsigned ID,
  */
  */
 const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength);
 const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength);
 
 
+/** Deprecated: Use LLVMIntrinsicCopyOverloadedName2 instead. */
+const char *LLVMIntrinsicCopyOverloadedName(unsigned ID,
+                                            LLVMTypeRef *ParamTypes,
+                                            size_t ParamCount,
+                                            size_t *NameLength);
+
 /**
 /**
  * Copies the name of an overloaded intrinsic identified by a given list of
  * Copies the name of an overloaded intrinsic identified by a given list of
  * parameter types.
  * parameter types.
@@ -2517,12 +2596,14 @@ const char *LLVMIntrinsicGetName(unsigned ID, size_t *NameLength);
  * Unlike LLVMIntrinsicGetName, the caller is responsible for freeing the
  * Unlike LLVMIntrinsicGetName, the caller is responsible for freeing the
  * returned string.
  * returned string.
  *
  *
+ * This version also supports unnamed types.
+ *
  * @see llvm::Intrinsic::getName()
  * @see llvm::Intrinsic::getName()
  */
  */
-const char *LLVMIntrinsicCopyOverloadedName(unsigned ID,
-                                            LLVMTypeRef *ParamTypes,
-                                            size_t ParamCount,
-                                            size_t *NameLength);
+const char *LLVMIntrinsicCopyOverloadedName2(LLVMModuleRef Mod, unsigned ID,
+                                             LLVMTypeRef *ParamTypes,
+                                             size_t ParamCount,
+                                             size_t *NameLength);
 
 
 /**
 /**
  * Obtain if the intrinsic identified by the given ID is overloaded.
  * Obtain if the intrinsic identified by the given ID is overloaded.
@@ -2860,6 +2941,14 @@ unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V);
  */
  */
 void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest);
 void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest);
 
 
+/**
+ * Replace an operand at a specific index in a llvm::MDNode value.
+ *
+ * @see llvm::MDNode::replaceOperandWith()
+ */
+void LLVMReplaceMDNodeOperandWith(LLVMValueRef V, unsigned Index,
+                                  LLVMMetadataRef Replacement);
+
 /** Deprecated: Use LLVMMDStringInContext2 instead. */
 /** Deprecated: Use LLVMMDStringInContext2 instead. */
 LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
 LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
                                    unsigned SLen);
                                    unsigned SLen);
@@ -3167,7 +3256,7 @@ LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst);
 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst);
 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst);
 
 
 /**
 /**
- * Remove and delete an instruction.
+ * Remove an instruction.
  *
  *
  * The instruction specified is removed from its containing building
  * The instruction specified is removed from its containing building
  * block but is kept alive.
  * block but is kept alive.
@@ -3186,6 +3275,16 @@ void LLVMInstructionRemoveFromParent(LLVMValueRef Inst);
  */
  */
 void LLVMInstructionEraseFromParent(LLVMValueRef Inst);
 void LLVMInstructionEraseFromParent(LLVMValueRef Inst);
 
 
+/**
+ * Delete an instruction.
+ *
+ * The instruction specified is deleted. It must have previously been
+ * removed from its containing building block.
+ *
+ * @see llvm::Value::deleteValue()
+ */
+void LLVMDeleteInstruction(LLVMValueRef Inst);
+
 /**
 /**
  * Obtain the code opcode for an individual instruction.
  * Obtain the code opcode for an individual instruction.
  *
  *
@@ -3275,7 +3374,7 @@ void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC);
  */
  */
 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr);
 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr);
 
 
-void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,
+void LLVMSetInstrParamAlignment(LLVMValueRef Instr, LLVMAttributeIndex Idx,
                                 unsigned Align);
                                 unsigned Align);
 
 
 void LLVMAddCallSiteAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
 void LLVMAddCallSiteAttribute(LLVMValueRef C, LLVMAttributeIndex Idx,
@@ -3474,7 +3573,7 @@ LLVMTypeRef LLVMGetAllocatedType(LLVMValueRef Alloca);
  */
  */
 
 
 /**
 /**
- * Check whether the given GEP instruction is inbounds.
+ * Check whether the given GEP operator is inbounds.
  */
  */
 LLVMBool LLVMIsInBounds(LLVMValueRef GEP);
 LLVMBool LLVMIsInBounds(LLVMValueRef GEP);
 
 
@@ -3483,6 +3582,11 @@ LLVMBool LLVMIsInBounds(LLVMValueRef GEP);
  */
  */
 void LLVMSetIsInBounds(LLVMValueRef GEP, LLVMBool InBounds);
 void LLVMSetIsInBounds(LLVMValueRef GEP, LLVMBool InBounds);
 
 
+/**
+ * Get the source element type of the given GEP operator.
+ */
+LLVMTypeRef LLVMGetGEPSourceElementType(LLVMValueRef GEP);
+
 /**
 /**
  * @}
  * @}
  */
  */
@@ -3533,7 +3637,7 @@ LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Index);
 
 
 /**
 /**
  * Obtain the number of indices.
  * Obtain the number of indices.
- * NB: This also works on GEP.
+ * NB: This also works on GEP operators.
  */
  */
 unsigned LLVMGetNumIndices(LLVMValueRef Inst);
 unsigned LLVMGetNumIndices(LLVMValueRef Inst);
 
 
@@ -3599,10 +3703,20 @@ void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Builder, LLVMMetadataRef Loc);
  * current debug location for the given builder.  If the builder has no current
  * current debug location for the given builder.  If the builder has no current
  * debug location, this function is a no-op.
  * debug location, this function is a no-op.
  *
  *
+ * @deprecated LLVMSetInstDebugLocation is deprecated in favor of the more general
+ *             LLVMAddMetadataToInst.
+ *
  * @see llvm::IRBuilder::SetInstDebugLocation()
  * @see llvm::IRBuilder::SetInstDebugLocation()
  */
  */
 void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst);
 void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst);
 
 
+/**
+ * Adds the metadata registered with the given builder to the given instruction.
+ *
+ * @see llvm::IRBuilder::AddMetadataToInst()
+ */
+void LLVMAddMetadataToInst(LLVMBuilderRef Builder, LLVMValueRef Inst);
+
 /**
 /**
  * Get the dafult floating-point math metadata for a given builder.
  * Get the dafult floating-point math metadata for a given builder.
  *
  *
@@ -3643,12 +3757,6 @@ LLVMValueRef LLVMBuildSwitch(LLVMBuilderRef, LLVMValueRef V,
                              LLVMBasicBlockRef Else, unsigned NumCases);
                              LLVMBasicBlockRef Else, unsigned NumCases);
 LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,
 LLVMValueRef LLVMBuildIndirectBr(LLVMBuilderRef B, LLVMValueRef Addr,
                                  unsigned NumDests);
                                  unsigned NumDests);
-// LLVMBuildInvoke is deprecated in favor of LLVMBuildInvoke2, in preparation
-// for opaque pointer types.
-LLVMValueRef LLVMBuildInvoke(LLVMBuilderRef, LLVMValueRef Fn,
-                             LLVMValueRef *Args, unsigned NumArgs,
-                             LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
-                             const char *Name);
 LLVMValueRef LLVMBuildInvoke2(LLVMBuilderRef, LLVMTypeRef Ty, LLVMValueRef Fn,
 LLVMValueRef LLVMBuildInvoke2(LLVMBuilderRef, LLVMTypeRef Ty, LLVMValueRef Fn,
                               LLVMValueRef *Args, unsigned NumArgs,
                               LLVMValueRef *Args, unsigned NumArgs,
                               LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
                               LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
@@ -3805,6 +3913,13 @@ LLVMValueRef LLVMBuildNUWNeg(LLVMBuilderRef B, LLVMValueRef V,
 LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef, LLVMValueRef V, const char *Name);
 LLVMValueRef LLVMBuildFNeg(LLVMBuilderRef, LLVMValueRef V, const char *Name);
 LLVMValueRef LLVMBuildNot(LLVMBuilderRef, LLVMValueRef V, const char *Name);
 LLVMValueRef LLVMBuildNot(LLVMBuilderRef, LLVMValueRef V, const char *Name);
 
 
+LLVMBool LLVMGetNUW(LLVMValueRef ArithInst);
+void LLVMSetNUW(LLVMValueRef ArithInst, LLVMBool HasNUW);
+LLVMBool LLVMGetNSW(LLVMValueRef ArithInst);
+void LLVMSetNSW(LLVMValueRef ArithInst, LLVMBool HasNSW);
+LLVMBool LLVMGetExact(LLVMValueRef DivOrShrInst);
+void LLVMSetExact(LLVMValueRef DivOrShrInst, LLVMBool IsExact);
+
 /* Memory */
 /* Memory */
 LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
 LLVMValueRef LLVMBuildMalloc(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
 LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef, LLVMTypeRef Ty,
 LLVMValueRef LLVMBuildArrayMalloc(LLVMBuilderRef, LLVMTypeRef Ty,
@@ -3842,23 +3957,9 @@ LLVMValueRef LLVMBuildAlloca(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
 LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef, LLVMTypeRef Ty,
 LLVMValueRef LLVMBuildArrayAlloca(LLVMBuilderRef, LLVMTypeRef Ty,
                                   LLVMValueRef Val, const char *Name);
                                   LLVMValueRef Val, const char *Name);
 LLVMValueRef LLVMBuildFree(LLVMBuilderRef, LLVMValueRef PointerVal);
 LLVMValueRef LLVMBuildFree(LLVMBuilderRef, LLVMValueRef PointerVal);
-// LLVMBuildLoad is deprecated in favor of LLVMBuildLoad2, in preparation for
-// opaque pointer types.
-LLVMValueRef LLVMBuildLoad(LLVMBuilderRef, LLVMValueRef PointerVal,
-                           const char *Name);
 LLVMValueRef LLVMBuildLoad2(LLVMBuilderRef, LLVMTypeRef Ty,
 LLVMValueRef LLVMBuildLoad2(LLVMBuilderRef, LLVMTypeRef Ty,
                             LLVMValueRef PointerVal, const char *Name);
                             LLVMValueRef PointerVal, const char *Name);
 LLVMValueRef LLVMBuildStore(LLVMBuilderRef, LLVMValueRef Val, LLVMValueRef Ptr);
 LLVMValueRef LLVMBuildStore(LLVMBuilderRef, LLVMValueRef Val, LLVMValueRef Ptr);
-// LLVMBuildGEP, LLVMBuildInBoundsGEP, and LLVMBuildStructGEP are deprecated in
-// favor of LLVMBuild*GEP2, in preparation for opaque pointer types.
-LLVMValueRef LLVMBuildGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
-                          LLVMValueRef *Indices, unsigned NumIndices,
-                          const char *Name);
-LLVMValueRef LLVMBuildInBoundsGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
-                                  LLVMValueRef *Indices, unsigned NumIndices,
-                                  const char *Name);
-LLVMValueRef LLVMBuildStructGEP(LLVMBuilderRef B, LLVMValueRef Pointer,
-                                unsigned Idx, const char *Name);
 LLVMValueRef LLVMBuildGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
 LLVMValueRef LLVMBuildGEP2(LLVMBuilderRef B, LLVMTypeRef Ty,
                            LLVMValueRef Pointer, LLVMValueRef *Indices,
                            LLVMValueRef Pointer, LLVMValueRef *Indices,
                            unsigned NumIndices, const char *Name);
                            unsigned NumIndices, const char *Name);
@@ -3928,6 +4029,9 @@ LLVMValueRef LLVMBuildFPCast(LLVMBuilderRef, LLVMValueRef Val,
 LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef, LLVMValueRef Val, /*Signed cast!*/
 LLVMValueRef LLVMBuildIntCast(LLVMBuilderRef, LLVMValueRef Val, /*Signed cast!*/
                               LLVMTypeRef DestTy, const char *Name);
                               LLVMTypeRef DestTy, const char *Name);
 
 
+LLVMOpcode LLVMGetCastOpcode(LLVMValueRef Src, LLVMBool SrcIsSigned,
+                             LLVMTypeRef DestTy, LLVMBool DestIsSigned);
+
 /* Comparisons */
 /* Comparisons */
 LLVMValueRef LLVMBuildICmp(LLVMBuilderRef, LLVMIntPredicate Op,
 LLVMValueRef LLVMBuildICmp(LLVMBuilderRef, LLVMIntPredicate Op,
                            LLVMValueRef LHS, LLVMValueRef RHS,
                            LLVMValueRef LHS, LLVMValueRef RHS,
@@ -3938,11 +4042,6 @@ LLVMValueRef LLVMBuildFCmp(LLVMBuilderRef, LLVMRealPredicate Op,
 
 
 /* Miscellaneous instructions */
 /* Miscellaneous instructions */
 LLVMValueRef LLVMBuildPhi(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
 LLVMValueRef LLVMBuildPhi(LLVMBuilderRef, LLVMTypeRef Ty, const char *Name);
-// LLVMBuildCall is deprecated in favor of LLVMBuildCall2, in preparation for
-// opaque pointer types.
-LLVMValueRef LLVMBuildCall(LLVMBuilderRef, LLVMValueRef Fn,
-                           LLVMValueRef *Args, unsigned NumArgs,
-                           const char *Name);
 LLVMValueRef LLVMBuildCall2(LLVMBuilderRef, LLVMTypeRef, LLVMValueRef Fn,
 LLVMValueRef LLVMBuildCall2(LLVMBuilderRef, LLVMTypeRef, LLVMValueRef Fn,
                             LLVMValueRef *Args, unsigned NumArgs,
                             LLVMValueRef *Args, unsigned NumArgs,
                             const char *Name);
                             const char *Name);
@@ -3971,8 +4070,9 @@ LLVMValueRef LLVMBuildIsNull(LLVMBuilderRef, LLVMValueRef Val,
                              const char *Name);
                              const char *Name);
 LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef, LLVMValueRef Val,
 LLVMValueRef LLVMBuildIsNotNull(LLVMBuilderRef, LLVMValueRef Val,
                                 const char *Name);
                                 const char *Name);
-LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef, LLVMValueRef LHS,
-                              LLVMValueRef RHS, const char *Name);
+LLVMValueRef LLVMBuildPtrDiff2(LLVMBuilderRef, LLVMTypeRef ElemTy,
+                               LLVMValueRef LHS, LLVMValueRef RHS,
+                               const char *Name);
 LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering ordering,
 LLVMValueRef LLVMBuildFence(LLVMBuilderRef B, LLVMAtomicOrdering ordering,
                             LLVMBool singleThread, const char *Name);
                             LLVMBool singleThread, const char *Name);
 LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B, LLVMAtomicRMWBinOp op,
 LLVMValueRef LLVMBuildAtomicRMW(LLVMBuilderRef B, LLVMAtomicRMWBinOp op,
@@ -4000,8 +4100,8 @@ int LLVMGetUndefMaskElem(void);
  * Get the mask value at position Elt in the mask of a ShuffleVector
  * Get the mask value at position Elt in the mask of a ShuffleVector
  * instruction.
  * instruction.
  *
  *
- * \Returns the result of \c LLVMGetUndefMaskElem() if the mask value is undef
- * at that position.
+ * \Returns the result of \c LLVMGetUndefMaskElem() if the mask value is
+ * poison at that position.
  */
  */
 int LLVMGetMaskValue(LLVMValueRef ShuffleVectorInst, unsigned Elt);
 int LLVMGetMaskValue(LLVMValueRef ShuffleVectorInst, unsigned Elt);
 
 
@@ -4063,26 +4163,13 @@ const char *LLVMGetBufferStart(LLVMMemoryBufferRef MemBuf);
 size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf);
 size_t LLVMGetBufferSize(LLVMMemoryBufferRef MemBuf);
 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf);
 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf);
 
 
-/**
- * @}
- */
-
-/**
- * @defgroup LLVMCCorePassRegistry Pass Registry
- *
- * @{
- */
-
-/** Return the global pass registry, for use with initialization functions.
-    @see llvm::PassRegistry::getPassRegistry */
-LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void);
-
 /**
 /**
  * @}
  * @}
  */
  */
 
 
 /**
 /**
  * @defgroup LLVMCCorePassManagers Pass Managers
  * @defgroup LLVMCCorePassManagers Pass Managers
+ * @ingroup LLVMCCore
  *
  *
  * @{
  * @{
  */
  */

+ 72 - 36
src/llvm-c/DebugInfo.h

@@ -16,11 +16,18 @@
 #ifndef LLVM_C_DEBUGINFO_H
 #ifndef LLVM_C_DEBUGINFO_H
 #define LLVM_C_DEBUGINFO_H
 #define LLVM_C_DEBUGINFO_H
 
 
-#include "llvm-c/Core.h"
 #include "llvm-c/ExternC.h"
 #include "llvm-c/ExternC.h"
+#include "llvm-c/Types.h"
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @defgroup LLVMCCoreDebugInfo Debug Information
+ * @ingroup LLVMCCore
+ *
+ * @{
+ */
+
 /**
 /**
  * Debug info flags.
  * Debug info flags.
  */
  */
@@ -109,6 +116,16 @@ typedef enum {
   LLVMDWARFSourceLanguageFortran08,
   LLVMDWARFSourceLanguageFortran08,
   LLVMDWARFSourceLanguageRenderScript,
   LLVMDWARFSourceLanguageRenderScript,
   LLVMDWARFSourceLanguageBLISS,
   LLVMDWARFSourceLanguageBLISS,
+  LLVMDWARFSourceLanguageKotlin,
+  LLVMDWARFSourceLanguageZig,
+  LLVMDWARFSourceLanguageCrystal,
+  LLVMDWARFSourceLanguageC_plus_plus_17,
+  LLVMDWARFSourceLanguageC_plus_plus_20,
+  LLVMDWARFSourceLanguageC17,
+  LLVMDWARFSourceLanguageFortran18,
+  LLVMDWARFSourceLanguageAda2005,
+  LLVMDWARFSourceLanguageAda2012,
+  LLVMDWARFSourceLanguageMojo,
   // Vendor extensions:
   // Vendor extensions:
   LLVMDWARFSourceLanguageMips_Assembler,
   LLVMDWARFSourceLanguageMips_Assembler,
   LLVMDWARFSourceLanguageGOOGLE_RenderScript,
   LLVMDWARFSourceLanguageGOOGLE_RenderScript,
@@ -161,7 +178,9 @@ enum {
   LLVMDIMacroFileMetadataKind,
   LLVMDIMacroFileMetadataKind,
   LLVMDICommonBlockMetadataKind,
   LLVMDICommonBlockMetadataKind,
   LLVMDIStringTypeMetadataKind,
   LLVMDIStringTypeMetadataKind,
-  LLVMDIGenericSubrangeMetadataKind
+  LLVMDIGenericSubrangeMetadataKind,
+  LLVMDIArgListMetadataKind,
+  LLVMDIAssignIDMetadataKind,
 };
 };
 typedef unsigned LLVMMetadataKind;
 typedef unsigned LLVMMetadataKind;
 
 
@@ -225,6 +244,13 @@ void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder);
  */
  */
 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder);
 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder);
 
 
+/**
+ * Finalize a specific subprogram.
+ * No new variables may be added to this subprogram afterwards.
+ */
+void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
+                                     LLVMMetadataRef Subprogram);
+
 /**
 /**
  * A CompileUnit provides an anchor for all debugging
  * A CompileUnit provides an anchor for all debugging
  * information generated during this instance of compilation.
  * information generated during this instance of compilation.
@@ -388,48 +414,48 @@ LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
  * \param ImportedEntity Previous imported entity to alias.
  * \param ImportedEntity Previous imported entity to alias.
  * \param File           File where the declaration is located.
  * \param File           File where the declaration is located.
  * \param Line           Line number of the declaration.
  * \param Line           Line number of the declaration.
+ * \param Elements       Renamed elements.
+ * \param NumElements    Number of renamed elements.
  */
  */
-LLVMMetadataRef
-LLVMDIBuilderCreateImportedModuleFromAlias(LLVMDIBuilderRef Builder,
-                                           LLVMMetadataRef Scope,
-                                           LLVMMetadataRef ImportedEntity,
-                                           LLVMMetadataRef File,
-                                           unsigned Line);
+LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
+    LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
+    LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
+    LLVMMetadataRef *Elements, unsigned NumElements);
 
 
 /**
 /**
  * Create a descriptor for an imported module.
  * Create a descriptor for an imported module.
- * \param Builder    The \c DIBuilder.
- * \param Scope      The scope this module is imported into
- * \param M          The module being imported here
- * \param File       File where the declaration is located.
- * \param Line       Line number of the declaration.
+ * \param Builder        The \c DIBuilder.
+ * \param Scope          The scope this module is imported into
+ * \param M              The module being imported here
+ * \param File           File where the declaration is located.
+ * \param Line           Line number of the declaration.
+ * \param Elements       Renamed elements.
+ * \param NumElements    Number of renamed elements.
  */
  */
-LLVMMetadataRef
-LLVMDIBuilderCreateImportedModuleFromModule(LLVMDIBuilderRef Builder,
-                                            LLVMMetadataRef Scope,
-                                            LLVMMetadataRef M,
-                                            LLVMMetadataRef File,
-                                            unsigned Line);
+LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
+    LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
+    LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
+    unsigned NumElements);
 
 
 /**
 /**
  * Create a descriptor for an imported function, type, or variable.  Suitable
  * Create a descriptor for an imported function, type, or variable.  Suitable
  * for e.g. FORTRAN-style USE declarations.
  * for e.g. FORTRAN-style USE declarations.
- * \param Builder    The DIBuilder.
- * \param Scope      The scope this module is imported into.
- * \param Decl       The declaration (or definition) of a function, type,
-                     or variable.
- * \param File       File where the declaration is located.
- * \param Line       Line number of the declaration.
- * \param Name       A name that uniquely identifies this imported declaration.
- * \param NameLen    The length of the C string passed to \c Name.
+ * \param Builder        The DIBuilder.
+ * \param Scope          The scope this module is imported into.
+ * \param Decl           The declaration (or definition) of a function, type,
+                         or variable.
+ * \param File           File where the declaration is located.
+ * \param Line           Line number of the declaration.
+ * \param Name           A name that uniquely identifies this imported
+ declaration.
+ * \param NameLen        The length of the C string passed to \c Name.
+ * \param Elements       Renamed elements.
+ * \param NumElements    Number of renamed elements.
  */
  */
-LLVMMetadataRef
-LLVMDIBuilderCreateImportedDeclaration(LLVMDIBuilderRef Builder,
-                                       LLVMMetadataRef Scope,
-                                       LLVMMetadataRef Decl,
-                                       LLVMMetadataRef File,
-                                       unsigned Line,
-                                       const char *Name, size_t NameLen);
+LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
+    LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
+    LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
+    LLVMMetadataRef *Elements, unsigned NumElements);
 
 
 /**
 /**
  * Creates a new DebugLocation that describes a source location.
  * Creates a new DebugLocation that describes a source location.
@@ -1087,7 +1113,7 @@ LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
  * \param Length      Length of the address operation array.
  * \param Length      Length of the address operation array.
  */
  */
 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
-                                              int64_t *Addr, size_t Length);
+                                              uint64_t *Addr, size_t Length);
 
 
 /**
 /**
  * Create a new descriptor for the specified variable that does not have an
  * Create a new descriptor for the specified variable that does not have an
@@ -1097,7 +1123,7 @@ LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
  */
  */
 LLVMMetadataRef
 LLVMMetadataRef
 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
-                                           int64_t Value);
+                                           uint64_t Value);
 
 
 /**
 /**
  * Create a new descriptor for the specified variable.
  * Create a new descriptor for the specified variable.
@@ -1124,6 +1150,12 @@ LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
     unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
     LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits);
     LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits);
 
 
+
+/**
+ * Get the dwarf::Tag of a DINode
+ */
+uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD);
+
 /**
 /**
  * Retrieves the \c DIVariable associated with this global variable expression.
  * Retrieves the \c DIVariable associated with this global variable expression.
  * \param GVE    The global variable expression.
  * \param GVE    The global variable expression.
@@ -1359,6 +1391,10 @@ void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc);
  */
  */
 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata);
 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 38 - 0
src/llvm-c/Deprecated.h

@@ -0,0 +1,38 @@
+/*===-- llvm-c/Deprecated.h - Deprecation macro -------------------*- C -*-===*\
+|*                                                                            *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
+|* Exceptions.                                                                *|
+|* See https://llvm.org/LICENSE.txt for license information.                  *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
+|*                                                                            *|
+|*===----------------------------------------------------------------------===*|
+|*                                                                            *|
+|* This header declares LLVM_ATTRIBUTE_C_DEPRECATED() macro, which can be     *|
+|* used to deprecate functions in the C interface.                            *|
+|*                                                                            *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_DEPRECATED_H
+#define LLVM_C_DEPRECATED_H
+
+#ifndef __has_feature
+# define __has_feature(x) 0
+#endif
+
+// This is a variant of LLVM_ATTRIBUTE_DEPRECATED() that is compatible with
+// C compilers.
+#if __has_feature(attribute_deprecated_with_message)
+# define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \
+  decl __attribute__((deprecated(message)))
+#elif defined(__GNUC__)
+# define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \
+  decl __attribute__((deprecated))
+#elif defined(_MSC_VER)
+# define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \
+  __declspec(deprecated(message)) decl
+#else
+# define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \
+  decl
+#endif
+
+#endif /* LLVM_C_DEPRECATED_H */

+ 20 - 10
src/llvm-c/DisassemblerTypes.h

@@ -7,8 +7,8 @@
 |*                                                                            *|
 |*                                                                            *|
 |*===----------------------------------------------------------------------===*/
 |*===----------------------------------------------------------------------===*/
 
 
-#ifndef LLVM_DISASSEMBLER_TYPES_H
-#define LLVM_DISASSEMBLER_TYPES_H
+#ifndef LLVM_C_DISASSEMBLERTYPES_H
+#define LLVM_C_DISASSEMBLERTYPES_H
 
 
 #include "llvm-c/DataTypes.h"
 #include "llvm-c/DataTypes.h"
 #ifdef __cplusplus
 #ifdef __cplusplus
@@ -17,6 +17,12 @@
 #include <stddef.h>
 #include <stddef.h>
 #endif
 #endif
 
 
+/**
+ * @addtogroup LLVMCDisassembler
+ *
+ * @{
+ */
+
 /**
 /**
  * An opaque reference to a disassembler context.
  * An opaque reference to a disassembler context.
  */
  */
@@ -32,15 +38,15 @@ typedef void *LLVMDisasmContextRef;
  * one operand with symbolic information.  To determine the symbolic operand
  * one operand with symbolic information.  To determine the symbolic operand
  * information for each operand, the bytes for the specific operand in the
  * information for each operand, the bytes for the specific operand in the
  * instruction are specified by the Offset parameter and its byte widith is the
  * instruction are specified by the Offset parameter and its byte widith is the
- * size parameter.  For instructions sets with fixed widths and one symbolic
- * operand per instruction, the Offset parameter will be zero and Size parameter
- * will be the instruction width.  The information is returned in TagBuf and is
- * Triple specific with its specific information defined by the value of
- * TagType for that Triple.  If symbolic information is returned the function
- * returns 1, otherwise it returns 0.
+ * OpSize parameter.  For instructions sets with fixed widths and one symbolic
+ * operand per instruction, the Offset parameter will be zero and InstSize
+ * parameter will be the instruction width.  The information is returned in
+ * TagBuf and is Triple specific with its specific information defined by the
+ * value of TagType for that Triple.  If symbolic information is returned the
+ * function * returns 1, otherwise it returns 0.
  */
  */
-typedef int (*LLVMOpInfoCallback)(void *DisInfo, uint64_t PC,
-                                  uint64_t Offset, uint64_t Size,
+typedef int (*LLVMOpInfoCallback)(void *DisInfo, uint64_t PC, uint64_t Offset,
+                                  uint64_t OpSize, uint64_t InstSize,
                                   int TagType, void *TagBuf);
                                   int TagType, void *TagBuf);
 
 
 /**
 /**
@@ -157,4 +163,8 @@ typedef const char *(*LLVMSymbolLookupCallback)(void *DisInfo,
 /* The output reference is to a C++ symbol name. */
 /* The output reference is to a C++ symbol name. */
 #define LLVMDisassembler_ReferenceType_DeMangled_Name 9
 #define LLVMDisassembler_ReferenceType_DeMangled_Name 9
 
 
+/**
+ * @}
+ */
+
 #endif
 #endif

+ 11 - 0
src/llvm-c/Error.h

@@ -18,6 +18,13 @@
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @defgroup LLVMCError Error Handling
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
 #define LLVMErrorSuccess 0
 #define LLVMErrorSuccess 0
 
 
 /**
 /**
@@ -67,6 +74,10 @@ LLVMErrorTypeId LLVMGetStringErrorTypeId(void);
  */
  */
 LLVMErrorRef LLVMCreateStringError(const char *ErrMsg);
 LLVMErrorRef LLVMCreateStringError(const char *ErrMsg);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 12 - 2
src/llvm-c/ErrorHandling.h

@@ -11,13 +11,19 @@
 |*                                                                            *|
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 \*===----------------------------------------------------------------------===*/
 
 
-#ifndef LLVM_C_ERROR_HANDLING_H
-#define LLVM_C_ERROR_HANDLING_H
+#ifndef LLVM_C_ERRORHANDLING_H
+#define LLVM_C_ERRORHANDLING_H
 
 
 #include "llvm-c/ExternC.h"
 #include "llvm-c/ExternC.h"
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @addtogroup LLVMCError
+ *
+ * @{
+ */
+
 typedef void (*LLVMFatalErrorHandler)(const char *Reason);
 typedef void (*LLVMFatalErrorHandler)(const char *Reason);
 
 
 /**
 /**
@@ -42,6 +48,10 @@ void LLVMResetFatalErrorHandler(void);
  */
  */
 void LLVMEnablePrettyStackTrace(void);
 void LLVMEnablePrettyStackTrace(void);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 2 - 2
src/llvm-c/ExternC.h

@@ -11,8 +11,8 @@
 |*                                                                            *|
 |*                                                                            *|
 \*===----------------------------------------------------------------------===*/
 \*===----------------------------------------------------------------------===*/
 
 
-#ifndef LLVM_C_EXTERN_C_H
-#define LLVM_C_EXTERN_C_H
+#ifndef LLVM_C_EXTERNC_H
+#define LLVM_C_EXTERNC_H
 
 
 #ifdef __clang__
 #ifdef __clang__
 #define LLVM_C_STRICT_PROTOTYPES_BEGIN                                         \
 #define LLVM_C_STRICT_PROTOTYPES_BEGIN                                         \

+ 11 - 0
src/llvm-c/IRReader.h

@@ -19,6 +19,13 @@
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @defgroup LLVMCCoreIRReader IR Reader
+ * @ingroup LLVMCCore
+ *
+ * @{
+ */
+
 /**
 /**
  * Read LLVM IR from a memory buffer and convert it into an in-memory Module
  * Read LLVM IR from a memory buffer and convert it into an in-memory Module
  * object. Returns 0 on success.
  * object. Returns 0 on success.
@@ -32,6 +39,10 @@ LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef,
                               LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
                               LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
                               char **OutMessage);
                               char **OutMessage);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 0 - 53
src/llvm-c/Initialization.h

@@ -1,53 +0,0 @@
-/*===-- llvm-c/Initialization.h - Initialization C Interface ------*- C -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to LLVM initialization routines,      *|
-|* which must be called before you can use the functionality provided by      *|
-|* the corresponding LLVM library.                                            *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_INITIALIZATION_H
-#define LLVM_C_INITIALIZATION_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCInitialization Initialization Routines
- * @ingroup LLVMC
- *
- * This module contains routines used to initialize the LLVM system.
- *
- * @{
- */
-
-void LLVMInitializeCore(LLVMPassRegistryRef R);
-void LLVMInitializeTransformUtils(LLVMPassRegistryRef R);
-void LLVMInitializeScalarOpts(LLVMPassRegistryRef R);
-void LLVMInitializeObjCARCOpts(LLVMPassRegistryRef R);
-void LLVMInitializeVectorization(LLVMPassRegistryRef R);
-void LLVMInitializeInstCombine(LLVMPassRegistryRef R);
-void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R);
-void LLVMInitializeIPO(LLVMPassRegistryRef R);
-void LLVMInitializeInstrumentation(LLVMPassRegistryRef R);
-void LLVMInitializeAnalysis(LLVMPassRegistryRef R);
-void LLVMInitializeIPA(LLVMPassRegistryRef R);
-void LLVMInitializeCodeGen(LLVMPassRegistryRef R);
-void LLVMInitializeTarget(LLVMPassRegistryRef R);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif

+ 251 - 0
src/llvm-c/LLJIT.h

@@ -0,0 +1,251 @@
+/*===----------- llvm-c/LLJIT.h - OrcV2 LLJIT C bindings --------*- C++ -*-===*\
+|*                                                                            *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
+|* Exceptions.                                                                *|
+|* See https://llvm.org/LICENSE.txt for license information.                  *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
+|*                                                                            *|
+|*===----------------------------------------------------------------------===*|
+|*                                                                            *|
+|* This header declares the C interface to the LLJIT class in                 *|
+|* libLLVMOrcJIT.a, which provides a simple MCJIT-like ORC JIT.               *|
+|*                                                                            *|
+|* Many exotic languages can interoperate with C code but have a harder time  *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages.                                           *|
+|*                                                                            *|
+|* Note: This interface is experimental. It is *NOT* stable, and may be       *|
+|*       changed without warning. Only C API usage documentation is           *|
+|*       provided. See the C++ documentation for all higher level ORC API     *|
+|*       details.                                                             *|
+|*                                                                            *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_LLJIT_H
+#define LLVM_C_LLJIT_H
+
+#include "llvm-c/Error.h"
+#include "llvm-c/Orc.h"
+#include "llvm-c/TargetMachine.h"
+#include "llvm-c/Types.h"
+
+LLVM_C_EXTERN_C_BEGIN
+
+/**
+ * @defgroup LLVMCExecutionEngineLLJIT LLJIT
+ * @ingroup LLVMCExecutionEngine
+ *
+ * @{
+ */
+
+/**
+ * A function for constructing an ObjectLinkingLayer instance to be used
+ * by an LLJIT instance.
+ *
+ * Clients can call LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator to
+ * set the creator function to use when constructing an LLJIT instance.
+ * This can be used to override the default linking layer implementation
+ * that would otherwise be chosen by LLJITBuilder.
+ *
+ * Object linking layers returned by this function will become owned by the
+ * LLJIT instance. The client is not responsible for managing their lifetimes
+ * after the function returns.
+ */
+typedef LLVMOrcObjectLayerRef (
+    *LLVMOrcLLJITBuilderObjectLinkingLayerCreatorFunction)(
+    void *Ctx, LLVMOrcExecutionSessionRef ES, const char *Triple);
+
+/**
+ * A reference to an orc::LLJITBuilder instance.
+ */
+typedef struct LLVMOrcOpaqueLLJITBuilder *LLVMOrcLLJITBuilderRef;
+
+/**
+ * A reference to an orc::LLJIT instance.
+ */
+typedef struct LLVMOrcOpaqueLLJIT *LLVMOrcLLJITRef;
+
+/**
+ * Create an LLVMOrcLLJITBuilder.
+ *
+ * The client owns the resulting LLJITBuilder and should dispose of it using
+ * LLVMOrcDisposeLLJITBuilder once they are done with it.
+ */
+LLVMOrcLLJITBuilderRef LLVMOrcCreateLLJITBuilder(void);
+
+/**
+ * Dispose of an LLVMOrcLLJITBuilderRef. This should only be called if ownership
+ * has not been passed to LLVMOrcCreateLLJIT (e.g. because some error prevented
+ * that function from being called).
+ */
+void LLVMOrcDisposeLLJITBuilder(LLVMOrcLLJITBuilderRef Builder);
+
+/**
+ * Set the JITTargetMachineBuilder to be used when constructing the LLJIT
+ * instance. Calling this function is optional: if it is not called then the
+ * LLJITBuilder will use JITTargeTMachineBuilder::detectHost to construct a
+ * JITTargetMachineBuilder.
+ *
+ * This function takes ownership of the JTMB argument: clients should not
+ * dispose of the JITTargetMachineBuilder after calling this function.
+ */
+void LLVMOrcLLJITBuilderSetJITTargetMachineBuilder(
+    LLVMOrcLLJITBuilderRef Builder, LLVMOrcJITTargetMachineBuilderRef JTMB);
+
+/**
+ * Set an ObjectLinkingLayer creator function for this LLJIT instance.
+ */
+void LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator(
+    LLVMOrcLLJITBuilderRef Builder,
+    LLVMOrcLLJITBuilderObjectLinkingLayerCreatorFunction F, void *Ctx);
+
+/**
+ * Create an LLJIT instance from an LLJITBuilder.
+ *
+ * This operation takes ownership of the Builder argument: clients should not
+ * dispose of the builder after calling this function (even if the function
+ * returns an error). If a null Builder argument is provided then a
+ * default-constructed LLJITBuilder will be used.
+ *
+ * On success the resulting LLJIT instance is uniquely owned by the client and
+ * automatically manages the memory of all JIT'd code and all modules that are
+ * transferred to it (e.g. via LLVMOrcLLJITAddLLVMIRModule). Disposing of the
+ * LLJIT instance will free all memory managed by the JIT, including JIT'd code
+ * and not-yet compiled modules.
+ */
+LLVMErrorRef LLVMOrcCreateLLJIT(LLVMOrcLLJITRef *Result,
+                                LLVMOrcLLJITBuilderRef Builder);
+
+/**
+ * Dispose of an LLJIT instance.
+ */
+LLVMErrorRef LLVMOrcDisposeLLJIT(LLVMOrcLLJITRef J);
+
+/**
+ * Get a reference to the ExecutionSession for this LLJIT instance.
+ *
+ * The ExecutionSession is owned by the LLJIT instance. The client is not
+ * responsible for managing its memory.
+ */
+LLVMOrcExecutionSessionRef LLVMOrcLLJITGetExecutionSession(LLVMOrcLLJITRef J);
+
+/**
+ * Return a reference to the Main JITDylib.
+ *
+ * The JITDylib is owned by the LLJIT instance. The client is not responsible
+ * for managing its memory.
+ */
+LLVMOrcJITDylibRef LLVMOrcLLJITGetMainJITDylib(LLVMOrcLLJITRef J);
+
+/**
+ * Return the target triple for this LLJIT instance. This string is owned by
+ * the LLJIT instance and should not be freed by the client.
+ */
+const char *LLVMOrcLLJITGetTripleString(LLVMOrcLLJITRef J);
+
+/**
+ * Returns the global prefix character according to the LLJIT's DataLayout.
+ */
+char LLVMOrcLLJITGetGlobalPrefix(LLVMOrcLLJITRef J);
+
+/**
+ * Mangles the given string according to the LLJIT instance's DataLayout, then
+ * interns the result in the SymbolStringPool and returns a reference to the
+ * pool entry. Clients should call LLVMOrcReleaseSymbolStringPoolEntry to
+ * decrement the ref-count on the pool entry once they are finished with this
+ * value.
+ */
+LLVMOrcSymbolStringPoolEntryRef
+LLVMOrcLLJITMangleAndIntern(LLVMOrcLLJITRef J, const char *UnmangledName);
+
+/**
+ * Add a buffer representing an object file to the given JITDylib in the given
+ * LLJIT instance. This operation transfers ownership of the buffer to the
+ * LLJIT instance. The buffer should not be disposed of or referenced once this
+ * function returns.
+ *
+ * Resources associated with the given object will be tracked by the given
+ * JITDylib's default resource tracker.
+ */
+LLVMErrorRef LLVMOrcLLJITAddObjectFile(LLVMOrcLLJITRef J, LLVMOrcJITDylibRef JD,
+                                       LLVMMemoryBufferRef ObjBuffer);
+
+/**
+ * Add a buffer representing an object file to the given ResourceTracker's
+ * JITDylib in the given LLJIT instance. This operation transfers ownership of
+ * the buffer to the LLJIT instance. The buffer should not be disposed of or
+ * referenced once this function returns.
+ *
+ * Resources associated with the given object will be tracked by ResourceTracker
+ * RT.
+ */
+LLVMErrorRef LLVMOrcLLJITAddObjectFileWithRT(LLVMOrcLLJITRef J,
+                                             LLVMOrcResourceTrackerRef RT,
+                                             LLVMMemoryBufferRef ObjBuffer);
+
+/**
+ * Add an IR module to the given JITDylib in the given LLJIT instance. This
+ * operation transfers ownership of the TSM argument to the LLJIT instance.
+ * The TSM argument should not be disposed of or referenced once this
+ * function returns.
+ *
+ * Resources associated with the given Module will be tracked by the given
+ * JITDylib's default resource tracker.
+ */
+LLVMErrorRef LLVMOrcLLJITAddLLVMIRModule(LLVMOrcLLJITRef J,
+                                         LLVMOrcJITDylibRef JD,
+                                         LLVMOrcThreadSafeModuleRef TSM);
+
+/**
+ * Add an IR module to the given ResourceTracker's JITDylib in the given LLJIT
+ * instance. This operation transfers ownership of the TSM argument to the LLJIT
+ * instance. The TSM argument should not be disposed of or referenced once this
+ * function returns.
+ *
+ * Resources associated with the given Module will be tracked by ResourceTracker
+ * RT.
+ */
+LLVMErrorRef LLVMOrcLLJITAddLLVMIRModuleWithRT(LLVMOrcLLJITRef J,
+                                               LLVMOrcResourceTrackerRef JD,
+                                               LLVMOrcThreadSafeModuleRef TSM);
+
+/**
+ * Look up the given symbol in the main JITDylib of the given LLJIT instance.
+ *
+ * This operation does not take ownership of the Name argument.
+ */
+LLVMErrorRef LLVMOrcLLJITLookup(LLVMOrcLLJITRef J,
+                                LLVMOrcExecutorAddress *Result,
+                                const char *Name);
+
+/**
+ * Returns a non-owning reference to the LLJIT instance's object linking layer.
+ */
+LLVMOrcObjectLayerRef LLVMOrcLLJITGetObjLinkingLayer(LLVMOrcLLJITRef J);
+
+/**
+ * Returns a non-owning reference to the LLJIT instance's object linking layer.
+ */
+LLVMOrcObjectTransformLayerRef
+LLVMOrcLLJITGetObjTransformLayer(LLVMOrcLLJITRef J);
+
+/**
+ * Returns a non-owning reference to the LLJIT instance's IR transform layer.
+ */
+LLVMOrcIRTransformLayerRef LLVMOrcLLJITGetIRTransformLayer(LLVMOrcLLJITRef J);
+
+/**
+ * Get the LLJIT instance's default data layout string.
+ *
+ * This string is owned by the LLJIT instance and does not need to be freed
+ * by the caller.
+ */
+const char *LLVMOrcLLJITGetDataLayoutStr(LLVMOrcLLJITRef J);
+
+/**
+ * @}
+ */
+
+LLVM_C_EXTERN_C_END
+
+#endif /* LLVM_C_LLJIT_H */

+ 0 - 66
src/llvm-c/LinkTimeOptimizer.h

@@ -1,66 +0,0 @@
-//===-- llvm/LinkTimeOptimizer.h - LTO Public C Interface -------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This header provides a C API to use the LLVM link time optimization
-// library. This is intended to be used by linkers which are C-only in
-// their implementation for performing LTO.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef LLVM_C_LINKTIMEOPTIMIZER_H
-#define LLVM_C_LINKTIMEOPTIMIZER_H
-
-#include "ExternC.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCLinkTimeOptimizer Link Time Optimization
- * @ingroup LLVMC
- *
- * @{
- */
-
-  /// This provides a dummy type for pointers to the LTO object.
-  typedef void* llvm_lto_t;
-
-  /// This provides a C-visible enumerator to manage status codes.
-  /// This should map exactly onto the C++ enumerator LTOStatus.
-  typedef enum llvm_lto_status {
-    LLVM_LTO_UNKNOWN,
-    LLVM_LTO_OPT_SUCCESS,
-    LLVM_LTO_READ_SUCCESS,
-    LLVM_LTO_READ_FAILURE,
-    LLVM_LTO_WRITE_FAILURE,
-    LLVM_LTO_NO_TARGET,
-    LLVM_LTO_NO_WORK,
-    LLVM_LTO_MODULE_MERGE_FAILURE,
-    LLVM_LTO_ASM_FAILURE,
-
-    //  Added C-specific error codes
-    LLVM_LTO_NULL_OBJECT
-  } llvm_lto_status_t;
-
-  /// This provides C interface to initialize link time optimizer. This allows
-  /// linker to use dlopen() interface to dynamically load LinkTimeOptimizer.
-  /// extern "C" helps, because dlopen() interface uses name to find the symbol.
-  extern llvm_lto_t llvm_create_optimizer(void);
-  extern void llvm_destroy_optimizer(llvm_lto_t lto);
-
-  extern llvm_lto_status_t llvm_read_object_file
-    (llvm_lto_t lto, const char* input_filename);
-  extern llvm_lto_status_t llvm_optimize_modules
-    (llvm_lto_t lto, const char* output_filename);
-
-/**
- * @}
- */
-
-  LLVM_C_EXTERN_C_END
-
-#endif

+ 11 - 0
src/llvm-c/Linker.h

@@ -19,6 +19,13 @@
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @defgroup LLVMCCoreLinker Linker
+ * @ingroup LLVMCCore
+ *
+ * @{
+ */
+
 /* This enum is provided for backwards-compatibility only. It has no effect. */
 /* This enum is provided for backwards-compatibility only. It has no effect. */
 typedef enum {
 typedef enum {
   LLVMLinkerDestroySource = 0, /* This is the default behavior. */
   LLVMLinkerDestroySource = 0, /* This is the default behavior. */
@@ -35,4 +42,8 @@ LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src);
 
 
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
+/**
+ * @}
+ */
+
 #endif
 #endif

+ 18 - 16
src/llvm-c/Object.h

@@ -21,7 +21,7 @@
 
 
 #include "llvm-c/ExternC.h"
 #include "llvm-c/ExternC.h"
 #include "llvm-c/Types.h"
 #include "llvm-c/Types.h"
-#include "llvm-c/Config/llvm-config.h"
+#include "llvm-c/Config//llvm-config.h"
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
@@ -38,21 +38,23 @@ typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef;
 typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef;
 typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef;
 
 
 typedef enum {
 typedef enum {
-  LLVMBinaryTypeArchive,                /**< Archive file. */
-  LLVMBinaryTypeMachOUniversalBinary,   /**< Mach-O Universal Binary file. */
-  LLVMBinaryTypeCOFFImportFile,         /**< COFF Import file. */
-  LLVMBinaryTypeIR,                     /**< LLVM IR. */
-  LLVMBinaryTypeWinRes,                 /**< Windows resource (.res) file. */
-  LLVMBinaryTypeCOFF,                   /**< COFF Object file. */
-  LLVMBinaryTypeELF32L,                 /**< ELF 32-bit, little endian. */
-  LLVMBinaryTypeELF32B,                 /**< ELF 32-bit, big endian. */
-  LLVMBinaryTypeELF64L,                 /**< ELF 64-bit, little endian. */
-  LLVMBinaryTypeELF64B,                 /**< ELF 64-bit, big endian. */
-  LLVMBinaryTypeMachO32L,               /**< MachO 32-bit, little endian. */
-  LLVMBinaryTypeMachO32B,               /**< MachO 32-bit, big endian. */
-  LLVMBinaryTypeMachO64L,               /**< MachO 64-bit, little endian. */
-  LLVMBinaryTypeMachO64B,               /**< MachO 64-bit, big endian. */
-  LLVMBinaryTypeWasm,                   /**< Web Assembly. */
+  LLVMBinaryTypeArchive,              /**< Archive file. */
+  LLVMBinaryTypeMachOUniversalBinary, /**< Mach-O Universal Binary file. */
+  LLVMBinaryTypeCOFFImportFile,       /**< COFF Import file. */
+  LLVMBinaryTypeIR,                   /**< LLVM IR. */
+  LLVMBinaryTypeWinRes,               /**< Windows resource (.res) file. */
+  LLVMBinaryTypeCOFF,                 /**< COFF Object file. */
+  LLVMBinaryTypeELF32L,               /**< ELF 32-bit, little endian. */
+  LLVMBinaryTypeELF32B,               /**< ELF 32-bit, big endian. */
+  LLVMBinaryTypeELF64L,               /**< ELF 64-bit, little endian. */
+  LLVMBinaryTypeELF64B,               /**< ELF 64-bit, big endian. */
+  LLVMBinaryTypeMachO32L,             /**< MachO 32-bit, little endian. */
+  LLVMBinaryTypeMachO32B,             /**< MachO 32-bit, big endian. */
+  LLVMBinaryTypeMachO64L,             /**< MachO 64-bit, little endian. */
+  LLVMBinaryTypeMachO64B,             /**< MachO 64-bit, big endian. */
+  LLVMBinaryTypeWasm,                 /**< Web Assembly. */
+  LLVMBinaryTypeOffload,              /**< Offloading fatbinary. */
+
 } LLVMBinaryType;
 } LLVMBinaryType;
 
 
 /**
 /**

+ 1292 - 0
src/llvm-c/Orc.h

@@ -0,0 +1,1292 @@
+/*===---------------- llvm-c/Orc.h - OrcV2 C bindings -----------*- C++ -*-===*\
+|*                                                                            *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
+|* Exceptions.                                                                *|
+|* See https://llvm.org/LICENSE.txt for license information.                  *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
+|*                                                                            *|
+|*===----------------------------------------------------------------------===*|
+|*                                                                            *|
+|* This header declares the C interface to libLLVMOrcJIT.a, which implements  *|
+|* JIT compilation of LLVM IR. Minimal documentation of C API specific issues *|
+|* (especially memory ownership rules) is provided. Core Orc concepts are     *|
+|* documented in llvm/docs/ORCv2.rst and APIs are documented in the C++       *|
+|* headers                                                                    *|
+|*                                                                            *|
+|* Many exotic languages can interoperate with C code but have a harder time  *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages.                                           *|
+|*                                                                            *|
+|* Note: This interface is experimental. It is *NOT* stable, and may be       *|
+|*       changed without warning. Only C API usage documentation is           *|
+|*       provided. See the C++ documentation for all higher level ORC API     *|
+|*       details.                                                             *|
+|*                                                                            *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_ORC_H
+#define LLVM_C_ORC_H
+
+#include "llvm-c/Error.h"
+#include "llvm-c/TargetMachine.h"
+#include "llvm-c/Types.h"
+
+LLVM_C_EXTERN_C_BEGIN
+
+/**
+ * @defgroup LLVMCExecutionEngineORC On-Request-Compilation
+ * @ingroup LLVMCExecutionEngine
+ *
+ * @{
+ */
+
+/**
+ * Represents an address in the executor process.
+ */
+typedef uint64_t LLVMOrcJITTargetAddress;
+
+/**
+ * Represents an address in the executor process.
+ */
+typedef uint64_t LLVMOrcExecutorAddress;
+
+/**
+ * Represents generic linkage flags for a symbol definition.
+ */
+typedef enum {
+  LLVMJITSymbolGenericFlagsNone = 0,
+  LLVMJITSymbolGenericFlagsExported = 1U << 0,
+  LLVMJITSymbolGenericFlagsWeak = 1U << 1,
+  LLVMJITSymbolGenericFlagsCallable = 1U << 2,
+  LLVMJITSymbolGenericFlagsMaterializationSideEffectsOnly = 1U << 3
+} LLVMJITSymbolGenericFlags;
+
+/**
+ * Represents target specific flags for a symbol definition.
+ */
+typedef uint8_t LLVMJITSymbolTargetFlags;
+
+/**
+ * Represents the linkage flags for a symbol definition.
+ */
+typedef struct {
+  uint8_t GenericFlags;
+  uint8_t TargetFlags;
+} LLVMJITSymbolFlags;
+
+/**
+ * Represents an evaluated symbol address and flags.
+ */
+typedef struct {
+  LLVMOrcExecutorAddress Address;
+  LLVMJITSymbolFlags Flags;
+} LLVMJITEvaluatedSymbol;
+
+/**
+ * A reference to an orc::ExecutionSession instance.
+ */
+typedef struct LLVMOrcOpaqueExecutionSession *LLVMOrcExecutionSessionRef;
+
+/**
+ * Error reporter function.
+ */
+typedef void (*LLVMOrcErrorReporterFunction)(void *Ctx, LLVMErrorRef Err);
+
+/**
+ * A reference to an orc::SymbolStringPool.
+ */
+typedef struct LLVMOrcOpaqueSymbolStringPool *LLVMOrcSymbolStringPoolRef;
+
+/**
+ * A reference to an orc::SymbolStringPool table entry.
+ */
+typedef struct LLVMOrcOpaqueSymbolStringPoolEntry
+    *LLVMOrcSymbolStringPoolEntryRef;
+
+/**
+ * Represents a pair of a symbol name and LLVMJITSymbolFlags.
+ */
+typedef struct {
+  LLVMOrcSymbolStringPoolEntryRef Name;
+  LLVMJITSymbolFlags Flags;
+} LLVMOrcCSymbolFlagsMapPair;
+
+/**
+ * Represents a list of (SymbolStringPtr, JITSymbolFlags) pairs that can be used
+ * to construct a SymbolFlagsMap.
+ */
+typedef LLVMOrcCSymbolFlagsMapPair *LLVMOrcCSymbolFlagsMapPairs;
+
+/**
+ * Represents a pair of a symbol name and an evaluated symbol.
+ */
+typedef struct {
+  LLVMOrcSymbolStringPoolEntryRef Name;
+  LLVMJITEvaluatedSymbol Sym;
+} LLVMOrcCSymbolMapPair;
+
+/**
+ * Represents a list of (SymbolStringPtr, JITEvaluatedSymbol) pairs that can be
+ * used to construct a SymbolMap.
+ */
+typedef LLVMOrcCSymbolMapPair *LLVMOrcCSymbolMapPairs;
+
+/**
+ * Represents a SymbolAliasMapEntry
+ */
+typedef struct {
+  LLVMOrcSymbolStringPoolEntryRef Name;
+  LLVMJITSymbolFlags Flags;
+} LLVMOrcCSymbolAliasMapEntry;
+
+/**
+ * Represents a pair of a symbol name and SymbolAliasMapEntry.
+ */
+typedef struct {
+  LLVMOrcSymbolStringPoolEntryRef Name;
+  LLVMOrcCSymbolAliasMapEntry Entry;
+} LLVMOrcCSymbolAliasMapPair;
+
+/**
+ * Represents a list of (SymbolStringPtr, (SymbolStringPtr, JITSymbolFlags))
+ * pairs that can be used to construct a SymbolFlagsMap.
+ */
+typedef LLVMOrcCSymbolAliasMapPair *LLVMOrcCSymbolAliasMapPairs;
+
+/**
+ * A reference to an orc::JITDylib instance.
+ */
+typedef struct LLVMOrcOpaqueJITDylib *LLVMOrcJITDylibRef;
+
+/**
+ * Represents a list of LLVMOrcSymbolStringPoolEntryRef and the associated
+ * length.
+ */
+typedef struct {
+  LLVMOrcSymbolStringPoolEntryRef *Symbols;
+  size_t Length;
+} LLVMOrcCSymbolsList;
+
+/**
+ * Represents a pair of a JITDylib and LLVMOrcCSymbolsList.
+ */
+typedef struct {
+  LLVMOrcJITDylibRef JD;
+  LLVMOrcCSymbolsList Names;
+} LLVMOrcCDependenceMapPair;
+
+/**
+ * Represents a list of (JITDylibRef, (LLVMOrcSymbolStringPoolEntryRef*,
+ * size_t)) pairs that can be used to construct a SymbolDependenceMap.
+ */
+typedef LLVMOrcCDependenceMapPair *LLVMOrcCDependenceMapPairs;
+
+/**
+ * Lookup kind. This can be used by definition generators when deciding whether
+ * to produce a definition for a requested symbol.
+ *
+ * This enum should be kept in sync with llvm::orc::LookupKind.
+ */
+typedef enum {
+  LLVMOrcLookupKindStatic,
+  LLVMOrcLookupKindDLSym
+} LLVMOrcLookupKind;
+
+/**
+ * JITDylib lookup flags. This can be used by definition generators when
+ * deciding whether to produce a definition for a requested symbol.
+ *
+ * This enum should be kept in sync with llvm::orc::JITDylibLookupFlags.
+ */
+typedef enum {
+  LLVMOrcJITDylibLookupFlagsMatchExportedSymbolsOnly,
+  LLVMOrcJITDylibLookupFlagsMatchAllSymbols
+} LLVMOrcJITDylibLookupFlags;
+
+/**
+ * An element type for a JITDylib search order.
+ */
+typedef struct {
+  LLVMOrcJITDylibRef JD;
+  LLVMOrcJITDylibLookupFlags JDLookupFlags;
+} LLVMOrcCJITDylibSearchOrderElement;
+
+/**
+ * A JITDylib search order.
+ *
+ * The list is terminated with an element containing a null pointer for the JD
+ * field.
+ */
+typedef LLVMOrcCJITDylibSearchOrderElement *LLVMOrcCJITDylibSearchOrder;
+
+/**
+ * Symbol lookup flags for lookup sets. This should be kept in sync with
+ * llvm::orc::SymbolLookupFlags.
+ */
+typedef enum {
+  LLVMOrcSymbolLookupFlagsRequiredSymbol,
+  LLVMOrcSymbolLookupFlagsWeaklyReferencedSymbol
+} LLVMOrcSymbolLookupFlags;
+
+/**
+ * An element type for a symbol lookup set.
+ */
+typedef struct {
+  LLVMOrcSymbolStringPoolEntryRef Name;
+  LLVMOrcSymbolLookupFlags LookupFlags;
+} LLVMOrcCLookupSetElement;
+
+/**
+ * A set of symbols to look up / generate.
+ *
+ * The list is terminated with an element containing a null pointer for the
+ * Name field.
+ *
+ * If a client creates an instance of this type then they are responsible for
+ * freeing it, and for ensuring that all strings have been retained over the
+ * course of its life. Clients receiving a copy from a callback are not
+ * responsible for managing lifetime or retain counts.
+ */
+typedef LLVMOrcCLookupSetElement *LLVMOrcCLookupSet;
+
+/**
+ * A reference to a uniquely owned orc::MaterializationUnit instance.
+ */
+typedef struct LLVMOrcOpaqueMaterializationUnit *LLVMOrcMaterializationUnitRef;
+
+/**
+ * A reference to a uniquely owned orc::MaterializationResponsibility instance.
+ *
+ * Ownership must be passed to a lower-level layer in a JIT stack.
+ */
+typedef struct LLVMOrcOpaqueMaterializationResponsibility
+    *LLVMOrcMaterializationResponsibilityRef;
+
+/**
+ * A MaterializationUnit materialize callback.
+ *
+ * Ownership of the Ctx and MR arguments passes to the callback which must
+ * adhere to the LLVMOrcMaterializationResponsibilityRef contract (see comment
+ * for that type).
+ *
+ * If this callback is called then the LLVMOrcMaterializationUnitDestroy
+ * callback will NOT be called.
+ */
+typedef void (*LLVMOrcMaterializationUnitMaterializeFunction)(
+    void *Ctx, LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * A MaterializationUnit discard callback.
+ *
+ * Ownership of JD and Symbol remain with the caller: These arguments should
+ * not be disposed of or released.
+ */
+typedef void (*LLVMOrcMaterializationUnitDiscardFunction)(
+    void *Ctx, LLVMOrcJITDylibRef JD, LLVMOrcSymbolStringPoolEntryRef Symbol);
+
+/**
+ * A MaterializationUnit destruction callback.
+ *
+ * If a custom MaterializationUnit is destroyed before its Materialize
+ * function is called then this function will be called to provide an
+ * opportunity for the underlying program representation to be destroyed.
+ */
+typedef void (*LLVMOrcMaterializationUnitDestroyFunction)(void *Ctx);
+
+/**
+ * A reference to an orc::ResourceTracker instance.
+ */
+typedef struct LLVMOrcOpaqueResourceTracker *LLVMOrcResourceTrackerRef;
+
+/**
+ * A reference to an orc::DefinitionGenerator.
+ */
+typedef struct LLVMOrcOpaqueDefinitionGenerator
+    *LLVMOrcDefinitionGeneratorRef;
+
+/**
+ * An opaque lookup state object. Instances of this type can be captured to
+ * suspend a lookup while a custom generator function attempts to produce a
+ * definition.
+ *
+ * If a client captures a lookup state object then they must eventually call
+ * LLVMOrcLookupStateContinueLookup to restart the lookup. This is required
+ * in order to release memory allocated for the lookup state, even if errors
+ * have occurred while the lookup was suspended (if these errors have made the
+ * lookup impossible to complete then it will issue its own error before
+ * destruction).
+ */
+typedef struct LLVMOrcOpaqueLookupState *LLVMOrcLookupStateRef;
+
+/**
+ * A custom generator function. This can be used to create a custom generator
+ * object using LLVMOrcCreateCustomCAPIDefinitionGenerator. The resulting
+ * object can be attached to a JITDylib, via LLVMOrcJITDylibAddGenerator, to
+ * receive callbacks when lookups fail to match existing definitions.
+ *
+ * GeneratorObj will contain the address of the custom generator object.
+ *
+ * Ctx will contain the context object passed to
+ * LLVMOrcCreateCustomCAPIDefinitionGenerator.
+ *
+ * LookupState will contain a pointer to an LLVMOrcLookupStateRef object. This
+ * can optionally be modified to make the definition generation process
+ * asynchronous: If the LookupStateRef value is copied, and the original
+ * LLVMOrcLookupStateRef set to null, the lookup will be suspended. Once the
+ * asynchronous definition process has been completed clients must call
+ * LLVMOrcLookupStateContinueLookup to continue the lookup (this should be
+ * done unconditionally, even if errors have occurred in the mean time, to
+ * free the lookup state memory and notify the query object of the failures).
+ * If LookupState is captured this function must return LLVMErrorSuccess.
+ *
+ * The Kind argument can be inspected to determine the lookup kind (e.g.
+ * as-if-during-static-link, or as-if-during-dlsym).
+ *
+ * The JD argument specifies which JITDylib the definitions should be generated
+ * into.
+ *
+ * The JDLookupFlags argument can be inspected to determine whether the original
+ * lookup included non-exported symobls.
+ *
+ * Finally, the LookupSet argument contains the set of symbols that could not
+ * be found in JD already (the set of generation candidates).
+ */
+typedef LLVMErrorRef (*LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction)(
+    LLVMOrcDefinitionGeneratorRef GeneratorObj, void *Ctx,
+    LLVMOrcLookupStateRef *LookupState, LLVMOrcLookupKind Kind,
+    LLVMOrcJITDylibRef JD, LLVMOrcJITDylibLookupFlags JDLookupFlags,
+    LLVMOrcCLookupSet LookupSet, size_t LookupSetSize);
+
+/**
+ * Disposer for a custom generator.
+ *
+ * Will be called by ORC when the JITDylib that the generator is attached to
+ * is destroyed.
+ */
+typedef void (*LLVMOrcDisposeCAPIDefinitionGeneratorFunction)(void *Ctx);
+
+/**
+ * Predicate function for SymbolStringPoolEntries.
+ */
+typedef int (*LLVMOrcSymbolPredicate)(void *Ctx,
+                                      LLVMOrcSymbolStringPoolEntryRef Sym);
+
+/**
+ * A reference to an orc::ThreadSafeContext instance.
+ */
+typedef struct LLVMOrcOpaqueThreadSafeContext *LLVMOrcThreadSafeContextRef;
+
+/**
+ * A reference to an orc::ThreadSafeModule instance.
+ */
+typedef struct LLVMOrcOpaqueThreadSafeModule *LLVMOrcThreadSafeModuleRef;
+
+/**
+ * A function for inspecting/mutating IR modules, suitable for use with
+ * LLVMOrcThreadSafeModuleWithModuleDo.
+ */
+typedef LLVMErrorRef (*LLVMOrcGenericIRModuleOperationFunction)(
+    void *Ctx, LLVMModuleRef M);
+
+/**
+ * A reference to an orc::JITTargetMachineBuilder instance.
+ */
+typedef struct LLVMOrcOpaqueJITTargetMachineBuilder
+    *LLVMOrcJITTargetMachineBuilderRef;
+
+/**
+ * A reference to an orc::ObjectLayer instance.
+ */
+typedef struct LLVMOrcOpaqueObjectLayer *LLVMOrcObjectLayerRef;
+
+/**
+ * A reference to an orc::ObjectLinkingLayer instance.
+ */
+typedef struct LLVMOrcOpaqueObjectLinkingLayer *LLVMOrcObjectLinkingLayerRef;
+
+/**
+ * A reference to an orc::IRTransformLayer instance.
+ */
+typedef struct LLVMOrcOpaqueIRTransformLayer *LLVMOrcIRTransformLayerRef;
+
+/**
+ * A function for applying transformations as part of an transform layer.
+ *
+ * Implementations of this type are responsible for managing the lifetime
+ * of the Module pointed to by ModInOut: If the LLVMModuleRef value is
+ * overwritten then the function is responsible for disposing of the incoming
+ * module. If the module is simply accessed/mutated in-place then ownership
+ * returns to the caller and the function does not need to do any lifetime
+ * management.
+ *
+ * Clients can call LLVMOrcLLJITGetIRTransformLayer to obtain the transform
+ * layer of a LLJIT instance, and use LLVMOrcIRTransformLayerSetTransform
+ * to set the function. This can be used to override the default transform
+ * layer.
+ */
+typedef LLVMErrorRef (*LLVMOrcIRTransformLayerTransformFunction)(
+    void *Ctx, LLVMOrcThreadSafeModuleRef *ModInOut,
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * A reference to an orc::ObjectTransformLayer instance.
+ */
+typedef struct LLVMOrcOpaqueObjectTransformLayer
+    *LLVMOrcObjectTransformLayerRef;
+
+/**
+ * A function for applying transformations to an object file buffer.
+ *
+ * Implementations of this type are responsible for managing the lifetime
+ * of the memory buffer pointed to by ObjInOut: If the LLVMMemoryBufferRef
+ * value is overwritten then the function is responsible for disposing of the
+ * incoming buffer. If the buffer is simply accessed/mutated in-place then
+ * ownership returns to the caller and the function does not need to do any
+ * lifetime management.
+ *
+ * The transform is allowed to return an error, in which case the ObjInOut
+ * buffer should be disposed of and set to null.
+ */
+typedef LLVMErrorRef (*LLVMOrcObjectTransformLayerTransformFunction)(
+    void *Ctx, LLVMMemoryBufferRef *ObjInOut);
+
+/**
+ * A reference to an orc::IndirectStubsManager instance.
+ */
+typedef struct LLVMOrcOpaqueIndirectStubsManager
+    *LLVMOrcIndirectStubsManagerRef;
+
+/**
+ * A reference to an orc::LazyCallThroughManager instance.
+ */
+typedef struct LLVMOrcOpaqueLazyCallThroughManager
+    *LLVMOrcLazyCallThroughManagerRef;
+
+/**
+ * A reference to an orc::DumpObjects object.
+ *
+ * Can be used to dump object files to disk with unique names. Useful as an
+ * ObjectTransformLayer transform.
+ */
+typedef struct LLVMOrcOpaqueDumpObjects *LLVMOrcDumpObjectsRef;
+
+/**
+ * Attach a custom error reporter function to the ExecutionSession.
+ *
+ * The error reporter will be called to deliver failure notices that can not be
+ * directly reported to a caller. For example, failure to resolve symbols in
+ * the JIT linker is typically reported via the error reporter (callers
+ * requesting definitions from the JIT will typically be delivered a
+ * FailureToMaterialize error instead).
+ */
+void LLVMOrcExecutionSessionSetErrorReporter(
+    LLVMOrcExecutionSessionRef ES, LLVMOrcErrorReporterFunction ReportError,
+    void *Ctx);
+
+/**
+ * Return a reference to the SymbolStringPool for an ExecutionSession.
+ *
+ * Ownership of the pool remains with the ExecutionSession: The caller is
+ * not required to free the pool.
+ */
+LLVMOrcSymbolStringPoolRef
+LLVMOrcExecutionSessionGetSymbolStringPool(LLVMOrcExecutionSessionRef ES);
+
+/**
+ * Clear all unreferenced symbol string pool entries.
+ *
+ * This can be called at any time to release unused entries in the
+ * ExecutionSession's string pool. Since it locks the pool (preventing
+ * interning of any new strings) it is recommended that it only be called
+ * infrequently, ideally when the caller has reason to believe that some
+ * entries will have become unreferenced, e.g. after removing a module or
+ * closing a JITDylib.
+ */
+void LLVMOrcSymbolStringPoolClearDeadEntries(LLVMOrcSymbolStringPoolRef SSP);
+
+/**
+ * Intern a string in the ExecutionSession's SymbolStringPool and return a
+ * reference to it. This increments the ref-count of the pool entry, and the
+ * returned value should be released once the client is done with it by
+ * calling LLVMOrReleaseSymbolStringPoolEntry.
+ *
+ * Since strings are uniqued within the SymbolStringPool
+ * LLVMOrcSymbolStringPoolEntryRefs can be compared by value to test string
+ * equality.
+ *
+ * Note that this function does not perform linker-mangling on the string.
+ */
+LLVMOrcSymbolStringPoolEntryRef
+LLVMOrcExecutionSessionIntern(LLVMOrcExecutionSessionRef ES, const char *Name);
+
+/**
+ * Callback type for ExecutionSession lookups.
+ *
+ * If Err is LLVMErrorSuccess then Result will contain a pointer to a
+ * list of ( SymbolStringPtr, JITEvaluatedSymbol ) pairs of length NumPairs.
+ *
+ * If Err is a failure value then Result and Ctx are undefined and should
+ * not be accessed. The Callback is responsible for handling the error
+ * value (e.g. by calling LLVMGetErrorMessage + LLVMDisposeErrorMessage).
+ *
+ * The caller retains ownership of the Result array and will release all
+ * contained symbol names. Clients are responsible for retaining any symbol
+ * names that they wish to hold after the function returns.
+ */
+typedef void (*LLVMOrcExecutionSessionLookupHandleResultFunction)(
+    LLVMErrorRef Err, LLVMOrcCSymbolMapPairs Result, size_t NumPairs,
+    void *Ctx);
+
+/**
+ * Look up symbols in an execution session.
+ *
+ * This is a wrapper around the general ExecutionSession::lookup function.
+ *
+ * The SearchOrder argument contains a list of (JITDylibs, JITDylibSearchFlags)
+ * pairs that describe the search order. The JITDylibs will be searched in the
+ * given order to try to find the symbols in the Symbols argument.
+ *
+ * The Symbols argument should contain a null-terminated array of
+ * (SymbolStringPtr, SymbolLookupFlags) pairs describing the symbols to be
+ * searched for. This function takes ownership of the elements of the Symbols
+ * array. The Name fields of the Symbols elements are taken to have been
+ * retained by the client for this function. The client should *not* release the
+ * Name fields, but are still responsible for destroying the array itself.
+ *
+ * The HandleResult function will be called once all searched for symbols have
+ * been found, or an error occurs. The HandleResult function will be passed an
+ * LLVMErrorRef indicating success or failure, and (on success) a
+ * null-terminated LLVMOrcCSymbolMapPairs array containing the function result,
+ * and the Ctx value passed to the lookup function.
+ *
+ * The client is fully responsible for managing the lifetime of the Ctx object.
+ * A common idiom is to allocate the context prior to the lookup and deallocate
+ * it in the handler.
+ *
+ * THIS API IS EXPERIMENTAL AND LIKELY TO CHANGE IN THE NEAR FUTURE!
+ */
+void LLVMOrcExecutionSessionLookup(
+    LLVMOrcExecutionSessionRef ES, LLVMOrcLookupKind K,
+    LLVMOrcCJITDylibSearchOrder SearchOrder, size_t SearchOrderSize,
+    LLVMOrcCLookupSet Symbols, size_t SymbolsSize,
+    LLVMOrcExecutionSessionLookupHandleResultFunction HandleResult, void *Ctx);
+
+/**
+ * Increments the ref-count for a SymbolStringPool entry.
+ */
+void LLVMOrcRetainSymbolStringPoolEntry(LLVMOrcSymbolStringPoolEntryRef S);
+
+/**
+ * Reduces the ref-count for of a SymbolStringPool entry.
+ */
+void LLVMOrcReleaseSymbolStringPoolEntry(LLVMOrcSymbolStringPoolEntryRef S);
+
+/**
+ * Return the c-string for the given symbol. This string will remain valid until
+ * the entry is freed (once all LLVMOrcSymbolStringPoolEntryRefs have been
+ * released).
+ */
+const char *LLVMOrcSymbolStringPoolEntryStr(LLVMOrcSymbolStringPoolEntryRef S);
+
+/**
+ * Reduces the ref-count of a ResourceTracker.
+ */
+void LLVMOrcReleaseResourceTracker(LLVMOrcResourceTrackerRef RT);
+
+/**
+ * Transfers tracking of all resources associated with resource tracker SrcRT
+ * to resource tracker DstRT.
+ */
+void LLVMOrcResourceTrackerTransferTo(LLVMOrcResourceTrackerRef SrcRT,
+                                      LLVMOrcResourceTrackerRef DstRT);
+
+/**
+ * Remove all resources associated with the given tracker. See
+ * ResourceTracker::remove().
+ */
+LLVMErrorRef LLVMOrcResourceTrackerRemove(LLVMOrcResourceTrackerRef RT);
+
+/**
+ * Dispose of a JITDylib::DefinitionGenerator. This should only be called if
+ * ownership has not been passed to a JITDylib (e.g. because some error
+ * prevented the client from calling LLVMOrcJITDylibAddGenerator).
+ */
+void LLVMOrcDisposeDefinitionGenerator(LLVMOrcDefinitionGeneratorRef DG);
+
+/**
+ * Dispose of a MaterializationUnit.
+ */
+void LLVMOrcDisposeMaterializationUnit(LLVMOrcMaterializationUnitRef MU);
+
+/**
+ * Create a custom MaterializationUnit.
+ *
+ * Name is a name for this MaterializationUnit to be used for identification
+ * and logging purposes (e.g. if this MaterializationUnit produces an
+ * object buffer then the name of that buffer will be derived from this name).
+ *
+ * The Syms list contains the names and linkages of the symbols provided by this
+ * unit. This function takes ownership of the elements of the Syms array. The
+ * Name fields of the array elements are taken to have been retained for this
+ * function. The client should *not* release the elements of the array, but is
+ * still responsible for destroying the array itself.
+ *
+ * The InitSym argument indicates whether or not this MaterializationUnit
+ * contains static initializers. If three are no static initializers (the common
+ * case) then this argument should be null. If there are static initializers
+ * then InitSym should be set to a unique name that also appears in the Syms
+ * list with the LLVMJITSymbolGenericFlagsMaterializationSideEffectsOnly flag
+ * set. This function takes ownership of the InitSym, which should have been
+ * retained twice on behalf of this function: once for the Syms entry and once
+ * for InitSym. If clients wish to use the InitSym value after this function
+ * returns they must retain it once more for themselves.
+ *
+ * If any of the symbols in the Syms list is looked up then the Materialize
+ * function will be called.
+ *
+ * If any of the symbols in the Syms list is overridden then the Discard
+ * function will be called.
+ *
+ * The caller owns the underling MaterializationUnit and is responsible for
+ * either passing it to a JITDylib (via LLVMOrcJITDylibDefine) or disposing
+ * of it by calling LLVMOrcDisposeMaterializationUnit.
+ */
+LLVMOrcMaterializationUnitRef LLVMOrcCreateCustomMaterializationUnit(
+    const char *Name, void *Ctx, LLVMOrcCSymbolFlagsMapPairs Syms,
+    size_t NumSyms, LLVMOrcSymbolStringPoolEntryRef InitSym,
+    LLVMOrcMaterializationUnitMaterializeFunction Materialize,
+    LLVMOrcMaterializationUnitDiscardFunction Discard,
+    LLVMOrcMaterializationUnitDestroyFunction Destroy);
+
+/**
+ * Create a MaterializationUnit to define the given symbols as pointing to
+ * the corresponding raw addresses.
+ *
+ * This function takes ownership of the elements of the Syms array. The Name
+ * fields of the array elements are taken to have been retained for this
+ * function. This allows the following pattern...
+ *
+ *   size_t NumPairs;
+ *   LLVMOrcCSymbolMapPairs Sym;
+ *   -- Build Syms array --
+ *   LLVMOrcMaterializationUnitRef MU =
+ *       LLVMOrcAbsoluteSymbols(Syms, NumPairs);
+ *
+ * ... without requiring cleanup of the elements of the Sym array afterwards.
+ *
+ * The client is still responsible for deleting the Sym array itself.
+ *
+ * If a client wishes to reuse elements of the Sym array after this call they
+ * must explicitly retain each of the elements for themselves.
+ */
+LLVMOrcMaterializationUnitRef
+LLVMOrcAbsoluteSymbols(LLVMOrcCSymbolMapPairs Syms, size_t NumPairs);
+
+/**
+ * Create a MaterializationUnit to define lazy re-expots. These are callable
+ * entry points that call through to the given symbols.
+ *
+ * This function takes ownership of the CallableAliases array. The Name
+ * fields of the array elements are taken to have been retained for this
+ * function. This allows the following pattern...
+ *
+ *   size_t NumPairs;
+ *   LLVMOrcCSymbolAliasMapPairs CallableAliases;
+ *   -- Build CallableAliases array --
+ *   LLVMOrcMaterializationUnitRef MU =
+ *      LLVMOrcLazyReexports(LCTM, ISM, JD, CallableAliases, NumPairs);
+ *
+ * ... without requiring cleanup of the elements of the CallableAliases array afterwards.
+ *
+ * The client is still responsible for deleting the CallableAliases array itself.
+ *
+ * If a client wishes to reuse elements of the CallableAliases array after this call they
+ * must explicitly retain each of the elements for themselves.
+ */
+LLVMOrcMaterializationUnitRef LLVMOrcLazyReexports(
+    LLVMOrcLazyCallThroughManagerRef LCTM, LLVMOrcIndirectStubsManagerRef ISM,
+    LLVMOrcJITDylibRef SourceRef, LLVMOrcCSymbolAliasMapPairs CallableAliases,
+    size_t NumPairs);
+// TODO: ImplSymbolMad SrcJDLoc
+
+/**
+ * Disposes of the passed MaterializationResponsibility object.
+ *
+ * This should only be done after the symbols covered by the object have either
+ * been resolved and emitted (via
+ * LLVMOrcMaterializationResponsibilityNotifyResolved and
+ * LLVMOrcMaterializationResponsibilityNotifyEmitted) or failed (via
+ * LLVMOrcMaterializationResponsibilityFailMaterialization).
+ */
+void LLVMOrcDisposeMaterializationResponsibility(
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * Returns the target JITDylib that these symbols are being materialized into.
+ */
+LLVMOrcJITDylibRef LLVMOrcMaterializationResponsibilityGetTargetDylib(
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * Returns the ExecutionSession for this MaterializationResponsibility.
+ */
+LLVMOrcExecutionSessionRef
+LLVMOrcMaterializationResponsibilityGetExecutionSession(
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * Returns the symbol flags map for this responsibility instance.
+ *
+ * The length of the array is returned in NumPairs and the caller is responsible
+ * for the returned memory and needs to call LLVMOrcDisposeCSymbolFlagsMap.
+ *
+ * To use the returned symbols beyond the livetime of the
+ * MaterializationResponsibility requires the caller to retain the symbols
+ * explicitly.
+ */
+LLVMOrcCSymbolFlagsMapPairs LLVMOrcMaterializationResponsibilityGetSymbols(
+    LLVMOrcMaterializationResponsibilityRef MR, size_t *NumPairs);
+
+/**
+ * Disposes of the passed LLVMOrcCSymbolFlagsMap.
+ *
+ * Does not release the entries themselves.
+ */
+void LLVMOrcDisposeCSymbolFlagsMap(LLVMOrcCSymbolFlagsMapPairs Pairs);
+
+/**
+ * Returns the initialization pseudo-symbol, if any. This symbol will also
+ * be present in the SymbolFlagsMap for this MaterializationResponsibility
+ * object.
+ *
+ * The returned symbol is not retained over any mutating operation of the
+ * MaterializationResponsbility or beyond the lifetime thereof.
+ */
+LLVMOrcSymbolStringPoolEntryRef
+LLVMOrcMaterializationResponsibilityGetInitializerSymbol(
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * Returns the names of any symbols covered by this
+ * MaterializationResponsibility object that have queries pending. This
+ * information can be used to return responsibility for unrequested symbols
+ * back to the JITDylib via the delegate method.
+ */
+LLVMOrcSymbolStringPoolEntryRef *
+LLVMOrcMaterializationResponsibilityGetRequestedSymbols(
+    LLVMOrcMaterializationResponsibilityRef MR, size_t *NumSymbols);
+
+/**
+ * Disposes of the passed LLVMOrcSymbolStringPoolEntryRef* .
+ *
+ * Does not release the symbols themselves.
+ */
+void LLVMOrcDisposeSymbols(LLVMOrcSymbolStringPoolEntryRef *Symbols);
+
+/**
+ * Notifies the target JITDylib that the given symbols have been resolved.
+ * This will update the given symbols' addresses in the JITDylib, and notify
+ * any pending queries on the given symbols of their resolution. The given
+ * symbols must be ones covered by this MaterializationResponsibility
+ * instance. Individual calls to this method may resolve a subset of the
+ * symbols, but all symbols must have been resolved prior to calling emit.
+ *
+ * This method will return an error if any symbols being resolved have been
+ * moved to the error state due to the failure of a dependency. If this
+ * method returns an error then clients should log it and call
+ * LLVMOrcMaterializationResponsibilityFailMaterialization. If no dependencies
+ * have been registered for the symbols covered by this
+ * MaterializationResponsibiility then this method is guaranteed to return
+ * LLVMErrorSuccess.
+ */
+LLVMErrorRef LLVMOrcMaterializationResponsibilityNotifyResolved(
+    LLVMOrcMaterializationResponsibilityRef MR, LLVMOrcCSymbolMapPairs Symbols,
+    size_t NumPairs);
+
+/**
+ * Notifies the target JITDylib (and any pending queries on that JITDylib)
+ * that all symbols covered by this MaterializationResponsibility instance
+ * have been emitted.
+ *
+ * This method will return an error if any symbols being resolved have been
+ * moved to the error state due to the failure of a dependency. If this
+ * method returns an error then clients should log it and call
+ * LLVMOrcMaterializationResponsibilityFailMaterialization.
+ * If no dependencies have been registered for the symbols covered by this
+ * MaterializationResponsibiility then this method is guaranteed to return
+ * LLVMErrorSuccess.
+ */
+LLVMErrorRef LLVMOrcMaterializationResponsibilityNotifyEmitted(
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * Attempt to claim responsibility for new definitions. This method can be
+ * used to claim responsibility for symbols that are added to a
+ * materialization unit during the compilation process (e.g. literal pool
+ * symbols). Symbol linkage rules are the same as for symbols that are
+ * defined up front: duplicate strong definitions will result in errors.
+ * Duplicate weak definitions will be discarded (in which case they will
+ * not be added to this responsibility instance).
+ *
+ * This method can be used by materialization units that want to add
+ * additional symbols at materialization time (e.g. stubs, compile
+ * callbacks, metadata)
+ */
+LLVMErrorRef LLVMOrcMaterializationResponsibilityDefineMaterializing(
+    LLVMOrcMaterializationResponsibilityRef MR,
+    LLVMOrcCSymbolFlagsMapPairs Pairs, size_t NumPairs);
+
+/**
+ * Notify all not-yet-emitted covered by this MaterializationResponsibility
+ * instance that an error has occurred.
+ * This will remove all symbols covered by this MaterializationResponsibilty
+ * from the target JITDylib, and send an error to any queries waiting on
+ * these symbols.
+ */
+void LLVMOrcMaterializationResponsibilityFailMaterialization(
+    LLVMOrcMaterializationResponsibilityRef MR);
+
+/**
+ * Transfers responsibility to the given MaterializationUnit for all
+ * symbols defined by that MaterializationUnit. This allows
+ * materializers to break up work based on run-time information (e.g.
+ * by introspecting which symbols have actually been looked up and
+ * materializing only those).
+ */
+LLVMErrorRef LLVMOrcMaterializationResponsibilityReplace(
+    LLVMOrcMaterializationResponsibilityRef MR,
+    LLVMOrcMaterializationUnitRef MU);
+
+/**
+ * Delegates responsibility for the given symbols to the returned
+ * materialization responsibility. Useful for breaking up work between
+ * threads, or different kinds of materialization processes.
+ *
+ * The caller retains responsibility of the the passed
+ * MaterializationResponsibility.
+ */
+LLVMErrorRef LLVMOrcMaterializationResponsibilityDelegate(
+    LLVMOrcMaterializationResponsibilityRef MR,
+    LLVMOrcSymbolStringPoolEntryRef *Symbols, size_t NumSymbols,
+    LLVMOrcMaterializationResponsibilityRef *Result);
+
+/**
+ * Adds dependencies to a symbol that the MaterializationResponsibility is
+ * responsible for.
+ *
+ * This function takes ownership of Dependencies struct. The Names
+ * array have been retained for this function. This allows the following
+ * pattern...
+ *
+ *   LLVMOrcSymbolStringPoolEntryRef Names[] = {...};
+ *   LLVMOrcCDependenceMapPair Dependence = {JD, {Names, sizeof(Names)}}
+ *   LLVMOrcMaterializationResponsibilityAddDependencies(JD, Name, &Dependence,
+ * 1);
+ *
+ * ... without requiring cleanup of the elements of the Names array afterwards.
+ *
+ * The client is still responsible for deleting the Dependencies.Names array
+ * itself.
+ */
+void LLVMOrcMaterializationResponsibilityAddDependencies(
+    LLVMOrcMaterializationResponsibilityRef MR,
+    LLVMOrcSymbolStringPoolEntryRef Name,
+    LLVMOrcCDependenceMapPairs Dependencies, size_t NumPairs);
+
+/**
+ * Adds dependencies to all symbols that the MaterializationResponsibility is
+ * responsible for. See LLVMOrcMaterializationResponsibilityAddDependencies for
+ * notes about memory responsibility.
+ */
+void LLVMOrcMaterializationResponsibilityAddDependenciesForAll(
+    LLVMOrcMaterializationResponsibilityRef MR,
+    LLVMOrcCDependenceMapPairs Dependencies, size_t NumPairs);
+
+/**
+ * Create a "bare" JITDylib.
+ *
+ * The client is responsible for ensuring that the JITDylib's name is unique,
+ * e.g. by calling LLVMOrcExecutionSessionGetJTIDylibByName first.
+ *
+ * This call does not install any library code or symbols into the newly
+ * created JITDylib. The client is responsible for all configuration.
+ */
+LLVMOrcJITDylibRef
+LLVMOrcExecutionSessionCreateBareJITDylib(LLVMOrcExecutionSessionRef ES,
+                                          const char *Name);
+
+/**
+ * Create a JITDylib.
+ *
+ * The client is responsible for ensuring that the JITDylib's name is unique,
+ * e.g. by calling LLVMOrcExecutionSessionGetJTIDylibByName first.
+ *
+ * If a Platform is attached to the ExecutionSession then
+ * Platform::setupJITDylib will be called to install standard platform symbols
+ * (e.g. standard library interposes). If no Platform is installed then this
+ * call is equivalent to LLVMExecutionSessionRefCreateBareJITDylib and will
+ * always return success.
+ */
+LLVMErrorRef
+LLVMOrcExecutionSessionCreateJITDylib(LLVMOrcExecutionSessionRef ES,
+                                      LLVMOrcJITDylibRef *Result,
+                                      const char *Name);
+
+/**
+ * Returns the JITDylib with the given name, or NULL if no such JITDylib
+ * exists.
+ */
+LLVMOrcJITDylibRef
+LLVMOrcExecutionSessionGetJITDylibByName(LLVMOrcExecutionSessionRef ES,
+                                         const char *Name);
+
+/**
+ * Return a reference to a newly created resource tracker associated with JD.
+ * The tracker is returned with an initial ref-count of 1, and must be released
+ * with LLVMOrcReleaseResourceTracker when no longer needed.
+ */
+LLVMOrcResourceTrackerRef
+LLVMOrcJITDylibCreateResourceTracker(LLVMOrcJITDylibRef JD);
+
+/**
+ * Return a reference to the default resource tracker for the given JITDylib.
+ * This operation will increase the retain count of the tracker: Clients should
+ * call LLVMOrcReleaseResourceTracker when the result is no longer needed.
+ */
+LLVMOrcResourceTrackerRef
+LLVMOrcJITDylibGetDefaultResourceTracker(LLVMOrcJITDylibRef JD);
+
+/**
+ * Add the given MaterializationUnit to the given JITDylib.
+ *
+ * If this operation succeeds then JITDylib JD will take ownership of MU.
+ * If the operation fails then ownership remains with the caller who should
+ * call LLVMOrcDisposeMaterializationUnit to destroy it.
+ */
+LLVMErrorRef LLVMOrcJITDylibDefine(LLVMOrcJITDylibRef JD,
+                                   LLVMOrcMaterializationUnitRef MU);
+
+/**
+ * Calls remove on all trackers associated with this JITDylib, see
+ * JITDylib::clear().
+ */
+LLVMErrorRef LLVMOrcJITDylibClear(LLVMOrcJITDylibRef JD);
+
+/**
+ * Add a DefinitionGenerator to the given JITDylib.
+ *
+ * The JITDylib will take ownership of the given generator: The client is no
+ * longer responsible for managing its memory.
+ */
+void LLVMOrcJITDylibAddGenerator(LLVMOrcJITDylibRef JD,
+                                 LLVMOrcDefinitionGeneratorRef DG);
+
+/**
+ * Create a custom generator.
+ *
+ * The F argument will be used to implement the DefinitionGenerator's
+ * tryToGenerate method (see
+ * LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction).
+ *
+ * Ctx is a context object that will be passed to F. This argument is
+ * permitted to be null.
+ *
+ * Dispose is the disposal function for Ctx. This argument is permitted to be
+ * null (in which case the client is responsible for the lifetime of Ctx).
+ */
+LLVMOrcDefinitionGeneratorRef LLVMOrcCreateCustomCAPIDefinitionGenerator(
+    LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction F, void *Ctx,
+    LLVMOrcDisposeCAPIDefinitionGeneratorFunction Dispose);
+
+/**
+ * Continue a lookup that was suspended in a generator (see
+ * LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction).
+ */
+void LLVMOrcLookupStateContinueLookup(LLVMOrcLookupStateRef S,
+                                      LLVMErrorRef Err);
+
+/**
+ * Get a DynamicLibrarySearchGenerator that will reflect process symbols into
+ * the JITDylib. On success the resulting generator is owned by the client.
+ * Ownership is typically transferred by adding the instance to a JITDylib
+ * using LLVMOrcJITDylibAddGenerator,
+ *
+ * The GlobalPrefix argument specifies the character that appears on the front
+ * of linker-mangled symbols for the target platform (e.g. '_' on MachO).
+ * If non-null, this character will be stripped from the start of all symbol
+ * strings before passing the remaining substring to dlsym.
+ *
+ * The optional Filter and Ctx arguments can be used to supply a symbol name
+ * filter: Only symbols for which the filter returns true will be visible to
+ * JIT'd code. If the Filter argument is null then all process symbols will
+ * be visible to JIT'd code. Note that the symbol name passed to the Filter
+ * function is the full mangled symbol: The client is responsible for stripping
+ * the global prefix if present.
+ */
+LLVMErrorRef LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess(
+    LLVMOrcDefinitionGeneratorRef *Result, char GlobalPrefx,
+    LLVMOrcSymbolPredicate Filter, void *FilterCtx);
+
+/**
+ * Get a LLVMOrcCreateDynamicLibararySearchGeneratorForPath that will reflect
+ * library symbols into the JITDylib. On success the resulting generator is
+ * owned by the client. Ownership is typically transferred by adding the
+ * instance to a JITDylib using LLVMOrcJITDylibAddGenerator,
+ *
+ * The GlobalPrefix argument specifies the character that appears on the front
+ * of linker-mangled symbols for the target platform (e.g. '_' on MachO).
+ * If non-null, this character will be stripped from the start of all symbol
+ * strings before passing the remaining substring to dlsym.
+ *
+ * The optional Filter and Ctx arguments can be used to supply a symbol name
+ * filter: Only symbols for which the filter returns true will be visible to
+ * JIT'd code. If the Filter argument is null then all library symbols will
+ * be visible to JIT'd code. Note that the symbol name passed to the Filter
+ * function is the full mangled symbol: The client is responsible for stripping
+ * the global prefix if present.
+ * 
+ * THIS API IS EXPERIMENTAL AND LIKELY TO CHANGE IN THE NEAR FUTURE!
+ * 
+ */
+LLVMErrorRef LLVMOrcCreateDynamicLibrarySearchGeneratorForPath(
+    LLVMOrcDefinitionGeneratorRef *Result, const char *FileName,
+    char GlobalPrefix, LLVMOrcSymbolPredicate Filter, void *FilterCtx);
+
+/**
+ * Get a LLVMOrcCreateStaticLibrarySearchGeneratorForPath that will reflect
+ * static library symbols into the JITDylib. On success the resulting
+ * generator is owned by the client. Ownership is typically transferred by
+ * adding the instance to a JITDylib using LLVMOrcJITDylibAddGenerator,
+ *
+ * Call with the optional TargetTriple argument will succeed if the file at
+ * the given path is a static library or a MachO universal binary containing a
+ * static library that is compatible with the given triple. Otherwise it will
+ * return an error.
+ *
+ * THIS API IS EXPERIMENTAL AND LIKELY TO CHANGE IN THE NEAR FUTURE!
+ * 
+ */
+LLVMErrorRef LLVMOrcCreateStaticLibrarySearchGeneratorForPath(
+    LLVMOrcDefinitionGeneratorRef *Result, LLVMOrcObjectLayerRef ObjLayer,
+    const char *FileName, const char *TargetTriple);
+
+/**
+ * Create a ThreadSafeContext containing a new LLVMContext.
+ *
+ * Ownership of the underlying ThreadSafeContext data is shared: Clients
+ * can and should dispose of their ThreadSafeContext as soon as they no longer
+ * need to refer to it directly. Other references (e.g. from ThreadSafeModules)
+ * will keep the data alive as long as it is needed.
+ */
+LLVMOrcThreadSafeContextRef LLVMOrcCreateNewThreadSafeContext(void);
+
+/**
+ * Get a reference to the wrapped LLVMContext.
+ */
+LLVMContextRef
+LLVMOrcThreadSafeContextGetContext(LLVMOrcThreadSafeContextRef TSCtx);
+
+/**
+ * Dispose of a ThreadSafeContext.
+ */
+void LLVMOrcDisposeThreadSafeContext(LLVMOrcThreadSafeContextRef TSCtx);
+
+/**
+ * Create a ThreadSafeModule wrapper around the given LLVM module. This takes
+ * ownership of the M argument which should not be disposed of or referenced
+ * after this function returns.
+ *
+ * Ownership of the ThreadSafeModule is unique: If it is transferred to the JIT
+ * (e.g. by LLVMOrcLLJITAddLLVMIRModule) then the client is no longer
+ * responsible for it. If it is not transferred to the JIT then the client
+ * should call LLVMOrcDisposeThreadSafeModule to dispose of it.
+ */
+LLVMOrcThreadSafeModuleRef
+LLVMOrcCreateNewThreadSafeModule(LLVMModuleRef M,
+                                 LLVMOrcThreadSafeContextRef TSCtx);
+
+/**
+ * Dispose of a ThreadSafeModule. This should only be called if ownership has
+ * not been passed to LLJIT (e.g. because some error prevented the client from
+ * adding this to the JIT).
+ */
+void LLVMOrcDisposeThreadSafeModule(LLVMOrcThreadSafeModuleRef TSM);
+
+/**
+ * Apply the given function to the module contained in this ThreadSafeModule.
+ */
+LLVMErrorRef
+LLVMOrcThreadSafeModuleWithModuleDo(LLVMOrcThreadSafeModuleRef TSM,
+                                    LLVMOrcGenericIRModuleOperationFunction F,
+                                    void *Ctx);
+
+/**
+ * Create a JITTargetMachineBuilder by detecting the host.
+ *
+ * On success the client owns the resulting JITTargetMachineBuilder. It must be
+ * passed to a consuming operation (e.g.
+ * LLVMOrcLLJITBuilderSetJITTargetMachineBuilder) or disposed of by calling
+ * LLVMOrcDisposeJITTargetMachineBuilder.
+ */
+LLVMErrorRef LLVMOrcJITTargetMachineBuilderDetectHost(
+    LLVMOrcJITTargetMachineBuilderRef *Result);
+
+/**
+ * Create a JITTargetMachineBuilder from the given TargetMachine template.
+ *
+ * This operation takes ownership of the given TargetMachine and destroys it
+ * before returing. The resulting JITTargetMachineBuilder is owned by the client
+ * and must be passed to a consuming operation (e.g.
+ * LLVMOrcLLJITBuilderSetJITTargetMachineBuilder) or disposed of by calling
+ * LLVMOrcDisposeJITTargetMachineBuilder.
+ */
+LLVMOrcJITTargetMachineBuilderRef
+LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(LLVMTargetMachineRef TM);
+
+/**
+ * Dispose of a JITTargetMachineBuilder.
+ */
+void LLVMOrcDisposeJITTargetMachineBuilder(
+    LLVMOrcJITTargetMachineBuilderRef JTMB);
+
+/**
+ * Returns the target triple for the given JITTargetMachineBuilder as a string.
+ *
+ * The caller owns the resulting string as must dispose of it by calling
+ * LLVMDisposeMessage
+ */
+char *LLVMOrcJITTargetMachineBuilderGetTargetTriple(
+    LLVMOrcJITTargetMachineBuilderRef JTMB);
+
+/**
+ * Sets the target triple for the given JITTargetMachineBuilder to the given
+ * string.
+ */
+void LLVMOrcJITTargetMachineBuilderSetTargetTriple(
+    LLVMOrcJITTargetMachineBuilderRef JTMB, const char *TargetTriple);
+
+/**
+ * Add an object to an ObjectLayer to the given JITDylib.
+ *
+ * Adds a buffer representing an object file to the given JITDylib using the
+ * given ObjectLayer instance. This operation transfers ownership of the buffer
+ * to the ObjectLayer instance. The buffer should not be disposed of or
+ * referenced once this function returns.
+ *
+ * Resources associated with the given object will be tracked by the given
+ * JITDylib's default ResourceTracker.
+ */
+LLVMErrorRef LLVMOrcObjectLayerAddObjectFile(LLVMOrcObjectLayerRef ObjLayer,
+                                             LLVMOrcJITDylibRef JD,
+                                             LLVMMemoryBufferRef ObjBuffer);
+
+/**
+ * Add an object to an ObjectLayer using the given ResourceTracker.
+ *
+ * Adds a buffer representing an object file to the given ResourceTracker's
+ * JITDylib using the given ObjectLayer instance. This operation transfers
+ * ownership of the buffer to the ObjectLayer instance. The buffer should not
+ * be disposed of or referenced once this function returns.
+ *
+ * Resources associated with the given object will be tracked by
+ * ResourceTracker RT.
+ */
+LLVMErrorRef
+LLVMOrcObjectLayerAddObjectFileWithRT(LLVMOrcObjectLayerRef ObjLayer,
+                                      LLVMOrcResourceTrackerRef RT,
+                                      LLVMMemoryBufferRef ObjBuffer);
+
+/**
+ * Emit an object buffer to an ObjectLayer.
+ *
+ * Ownership of the responsibility object and object buffer pass to this
+ * function. The client is not responsible for cleanup.
+ */
+void LLVMOrcObjectLayerEmit(LLVMOrcObjectLayerRef ObjLayer,
+                            LLVMOrcMaterializationResponsibilityRef R,
+                            LLVMMemoryBufferRef ObjBuffer);
+
+/**
+ * Dispose of an ObjectLayer.
+ */
+void LLVMOrcDisposeObjectLayer(LLVMOrcObjectLayerRef ObjLayer);
+
+void LLVMOrcIRTransformLayerEmit(LLVMOrcIRTransformLayerRef IRTransformLayer,
+                                 LLVMOrcMaterializationResponsibilityRef MR,
+                                 LLVMOrcThreadSafeModuleRef TSM);
+
+/**
+ * Set the transform function of the provided transform layer, passing through a
+ * pointer to user provided context.
+ */
+void LLVMOrcIRTransformLayerSetTransform(
+    LLVMOrcIRTransformLayerRef IRTransformLayer,
+    LLVMOrcIRTransformLayerTransformFunction TransformFunction, void *Ctx);
+
+/**
+ * Set the transform function on an LLVMOrcObjectTransformLayer.
+ */
+void LLVMOrcObjectTransformLayerSetTransform(
+    LLVMOrcObjectTransformLayerRef ObjTransformLayer,
+    LLVMOrcObjectTransformLayerTransformFunction TransformFunction, void *Ctx);
+
+/**
+ * Create a LocalIndirectStubsManager from the given target triple.
+ *
+ * The resulting IndirectStubsManager is owned by the client
+ * and must be disposed of by calling LLVMOrcDisposeDisposeIndirectStubsManager.
+ */
+LLVMOrcIndirectStubsManagerRef
+LLVMOrcCreateLocalIndirectStubsManager(const char *TargetTriple);
+
+/**
+ * Dispose of an IndirectStubsManager.
+ */
+void LLVMOrcDisposeIndirectStubsManager(LLVMOrcIndirectStubsManagerRef ISM);
+
+LLVMErrorRef LLVMOrcCreateLocalLazyCallThroughManager(
+    const char *TargetTriple, LLVMOrcExecutionSessionRef ES,
+    LLVMOrcJITTargetAddress ErrorHandlerAddr,
+    LLVMOrcLazyCallThroughManagerRef *LCTM);
+
+/**
+ * Dispose of an LazyCallThroughManager.
+ */
+void LLVMOrcDisposeLazyCallThroughManager(
+    LLVMOrcLazyCallThroughManagerRef LCTM);
+
+/**
+ * Create a DumpObjects instance.
+ *
+ * DumpDir specifies the path to write dumped objects to. DumpDir may be empty
+ * in which case files will be dumped to the working directory.
+ *
+ * IdentifierOverride specifies a file name stem to use when dumping objects.
+ * If empty then each MemoryBuffer's identifier will be used (with a .o suffix
+ * added if not already present). If an identifier override is supplied it will
+ * be used instead, along with an incrementing counter (since all buffers will
+ * use the same identifier, the resulting files will be named <ident>.o,
+ * <ident>.2.o, <ident>.3.o, and so on). IdentifierOverride should not contain
+ * an extension, as a .o suffix will be added by DumpObjects.
+ */
+LLVMOrcDumpObjectsRef LLVMOrcCreateDumpObjects(const char *DumpDir,
+                                               const char *IdentifierOverride);
+
+/**
+ * Dispose of a DumpObjects instance.
+ */
+void LLVMOrcDisposeDumpObjects(LLVMOrcDumpObjectsRef DumpObjects);
+
+/**
+ * Dump the contents of the given MemoryBuffer.
+ */
+LLVMErrorRef LLVMOrcDumpObjects_CallOperator(LLVMOrcDumpObjectsRef DumpObjects,
+                                             LLVMMemoryBufferRef *ObjBuffer);
+
+/**
+ * @}
+ */
+
+LLVM_C_EXTERN_C_END
+
+#endif /* LLVM_C_ORC_H */

+ 0 - 169
src/llvm-c/OrcBindings.h

@@ -1,169 +0,0 @@
-/*===----------- llvm-c/OrcBindings.h - Orc Lib C Iface ---------*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMOrcJIT.a, which implements  *|
-|* JIT compilation of LLVM IR.                                                *|
-|*                                                                            *|
-|* Many exotic languages can interoperate with C code but have a harder time  *|
-|* with C++ due to name mangling. So in addition to C, this interface enables *|
-|* tools written in such languages.                                           *|
-|*                                                                            *|
-|* Note: This interface is experimental. It is *NOT* stable, and may be       *|
-|*       changed without warning.                                             *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_ORCBINDINGS_H
-#define LLVM_C_ORCBINDINGS_H
-
-#include "Error.h"
-#include "ExternC.h"
-#include "Object.h"
-#include "TargetMachine.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-typedef struct LLVMOrcOpaqueJITStack *LLVMOrcJITStackRef;
-typedef uint64_t LLVMOrcModuleHandle;
-typedef uint64_t LLVMOrcTargetAddress;
-typedef uint64_t (*LLVMOrcSymbolResolverFn)(const char *Name, void *LookupCtx);
-typedef uint64_t (*LLVMOrcLazyCompileCallbackFn)(LLVMOrcJITStackRef JITStack,
-                                                 void *CallbackCtx);
-
-/**
- * Create an ORC JIT stack.
- *
- * The client owns the resulting stack, and must call OrcDisposeInstance(...)
- * to destroy it and free its memory. The JIT stack will take ownership of the
- * TargetMachine, which will be destroyed when the stack is destroyed. The
- * client should not attempt to dispose of the Target Machine, or it will result
- * in a double-free.
- */
-LLVMOrcJITStackRef LLVMOrcCreateInstance(LLVMTargetMachineRef TM);
-
-/**
- * Get the error message for the most recent error (if any).
- *
- * This message is owned by the ORC JIT Stack and will be freed when the stack
- * is disposed of by LLVMOrcDisposeInstance.
- */
-const char *LLVMOrcGetErrorMsg(LLVMOrcJITStackRef JITStack);
-
-/**
- * Mangle the given symbol.
- * Memory will be allocated for MangledSymbol to hold the result. The client
- */
-void LLVMOrcGetMangledSymbol(LLVMOrcJITStackRef JITStack, char **MangledSymbol,
-                             const char *Symbol);
-
-/**
- * Dispose of a mangled symbol.
- */
-void LLVMOrcDisposeMangledSymbol(char *MangledSymbol);
-
-/**
- * Create a lazy compile callback.
- */
-LLVMErrorRef LLVMOrcCreateLazyCompileCallback(
-    LLVMOrcJITStackRef JITStack, LLVMOrcTargetAddress *RetAddr,
-    LLVMOrcLazyCompileCallbackFn Callback, void *CallbackCtx);
-
-/**
- * Create a named indirect call stub.
- */
-LLVMErrorRef LLVMOrcCreateIndirectStub(LLVMOrcJITStackRef JITStack,
-                                       const char *StubName,
-                                       LLVMOrcTargetAddress InitAddr);
-
-/**
- * Set the pointer for the given indirect stub.
- */
-LLVMErrorRef LLVMOrcSetIndirectStubPointer(LLVMOrcJITStackRef JITStack,
-                                           const char *StubName,
-                                           LLVMOrcTargetAddress NewAddr);
-
-/**
- * Add module to be eagerly compiled.
- */
-LLVMErrorRef LLVMOrcAddEagerlyCompiledIR(LLVMOrcJITStackRef JITStack,
-                                         LLVMOrcModuleHandle *RetHandle,
-                                         LLVMModuleRef Mod,
-                                         LLVMOrcSymbolResolverFn SymbolResolver,
-                                         void *SymbolResolverCtx);
-
-/**
- * Add module to be lazily compiled one function at a time.
- */
-LLVMErrorRef LLVMOrcAddLazilyCompiledIR(LLVMOrcJITStackRef JITStack,
-                                        LLVMOrcModuleHandle *RetHandle,
-                                        LLVMModuleRef Mod,
-                                        LLVMOrcSymbolResolverFn SymbolResolver,
-                                        void *SymbolResolverCtx);
-
-/**
- * Add an object file.
- *
- * This method takes ownership of the given memory buffer and attempts to add
- * it to the JIT as an object file.
- * Clients should *not* dispose of the 'Obj' argument: the JIT will manage it
- * from this call onwards.
- */
-LLVMErrorRef LLVMOrcAddObjectFile(LLVMOrcJITStackRef JITStack,
-                                  LLVMOrcModuleHandle *RetHandle,
-                                  LLVMMemoryBufferRef Obj,
-                                  LLVMOrcSymbolResolverFn SymbolResolver,
-                                  void *SymbolResolverCtx);
-
-/**
- * Remove a module set from the JIT.
- *
- * This works for all modules that can be added via OrcAdd*, including object
- * files.
- */
-LLVMErrorRef LLVMOrcRemoveModule(LLVMOrcJITStackRef JITStack,
-                                 LLVMOrcModuleHandle H);
-
-/**
- * Get symbol address from JIT instance.
- */
-LLVMErrorRef LLVMOrcGetSymbolAddress(LLVMOrcJITStackRef JITStack,
-                                     LLVMOrcTargetAddress *RetAddr,
-                                     const char *SymbolName);
-
-/**
- * Get symbol address from JIT instance, searching only the specified
- * handle.
- */
-LLVMErrorRef LLVMOrcGetSymbolAddressIn(LLVMOrcJITStackRef JITStack,
-                                       LLVMOrcTargetAddress *RetAddr,
-                                       LLVMOrcModuleHandle H,
-                                       const char *SymbolName);
-
-/**
- * Dispose of an ORC JIT stack.
- */
-LLVMErrorRef LLVMOrcDisposeInstance(LLVMOrcJITStackRef JITStack);
-
-/**
- * Register a JIT Event Listener.
- *
- * A NULL listener is ignored.
- */
-void LLVMOrcRegisterJITEventListener(LLVMOrcJITStackRef JITStack, LLVMJITEventListenerRef L);
-
-/**
- * Unegister a JIT Event Listener.
- *
- * A NULL listener is ignored.
- */
-void LLVMOrcUnregisterJITEventListener(LLVMOrcJITStackRef JITStack, LLVMJITEventListenerRef L);
-
-LLVM_C_EXTERN_C_END
-
-#endif /* LLVM_C_ORCBINDINGS_H */

+ 103 - 0
src/llvm-c/OrcEE.h

@@ -0,0 +1,103 @@
+/*===-- llvm-c/OrcEE.h - OrcV2 C bindings ExecutionEngine utils -*- C++ -*-===*\
+|*                                                                            *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
+|* Exceptions.                                                                *|
+|* See https://llvm.org/LICENSE.txt for license information.                  *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
+|*                                                                            *|
+|*===----------------------------------------------------------------------===*|
+|*                                                                            *|
+|* This header declares the C interface to ExecutionEngine based utils, e.g.  *|
+|* RTDyldObjectLinkingLayer (based on RuntimeDyld) in Orc.                    *|
+|*                                                                            *|
+|* Many exotic languages can interoperate with C code but have a harder time  *|
+|* with C++ due to name mangling. So in addition to C, this interface enables *|
+|* tools written in such languages.                                           *|
+|*                                                                            *|
+|* Note: This interface is experimental. It is *NOT* stable, and may be       *|
+|*       changed without warning. Only C API usage documentation is           *|
+|*       provided. See the C++ documentation for all higher level ORC API     *|
+|*       details.                                                             *|
+|*                                                                            *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_ORCEE_H
+#define LLVM_C_ORCEE_H
+
+#include "llvm-c/Error.h"
+#include "llvm-c/ExecutionEngine.h"
+#include "llvm-c/Orc.h"
+#include "llvm-c/TargetMachine.h"
+#include "llvm-c/Types.h"
+
+LLVM_C_EXTERN_C_BEGIN
+
+typedef void *(*LLVMMemoryManagerCreateContextCallback)(void *CtxCtx);
+typedef void (*LLVMMemoryManagerNotifyTerminatingCallback)(void *CtxCtx);
+
+/**
+ * @defgroup LLVMCExecutionEngineORCEE ExecutionEngine-based ORC Utils
+ * @ingroup LLVMCExecutionEngine
+ *
+ * @{
+ */
+
+/**
+ * Create a RTDyldObjectLinkingLayer instance using the standard
+ * SectionMemoryManager for memory management.
+ */
+LLVMOrcObjectLayerRef
+LLVMOrcCreateRTDyldObjectLinkingLayerWithSectionMemoryManager(
+    LLVMOrcExecutionSessionRef ES);
+
+/**
+ * Create a RTDyldObjectLinkingLayer instance using MCJIT-memory-manager-like
+ * callbacks.
+ *
+ * This is intended to simplify transitions for existing MCJIT clients. The
+ * callbacks used are similar (but not identical) to the callbacks for
+ * LLVMCreateSimpleMCJITMemoryManager: Unlike MCJIT, RTDyldObjectLinkingLayer
+ * will create a new memory manager for each object linked by calling the given
+ * CreateContext callback. This allows for code removal by destroying each
+ * allocator individually. Every allocator will be destroyed (if it has not been
+ * already) at RTDyldObjectLinkingLayer destruction time, and the
+ * NotifyTerminating callback will be called to indicate that no further
+ * allocation contexts will be created.
+ *
+ * To implement MCJIT-like behavior clients can implement CreateContext,
+ * NotifyTerminating, and Destroy as:
+ *
+ *   void *CreateContext(void *CtxCtx) { return CtxCtx; }
+ *   void NotifyTerminating(void *CtxCtx) { MyOriginalDestroy(CtxCtx); }
+ *   void Destroy(void *Ctx) { }
+ *
+ * This scheme simply reuses the CreateContextCtx pointer as the one-and-only
+ * allocation context.
+ */
+LLVMOrcObjectLayerRef
+LLVMOrcCreateRTDyldObjectLinkingLayerWithMCJITMemoryManagerLikeCallbacks(
+    LLVMOrcExecutionSessionRef ES, void *CreateContextCtx,
+    LLVMMemoryManagerCreateContextCallback CreateContext,
+    LLVMMemoryManagerNotifyTerminatingCallback NotifyTerminating,
+    LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
+    LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
+    LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
+    LLVMMemoryManagerDestroyCallback Destroy);
+
+/**
+ * Add the given listener to the given RTDyldObjectLinkingLayer.
+ *
+ * Note: Layer must be an RTDyldObjectLinkingLayer instance or
+ * behavior is undefined.
+ */
+void LLVMOrcRTDyldObjectLinkingLayerRegisterJITEventListener(
+    LLVMOrcObjectLayerRef RTDyldObjLinkingLayer,
+    LLVMJITEventListenerRef Listener);
+
+/**
+ * @}
+ */
+
+LLVM_C_EXTERN_C_END
+
+#endif /* LLVM_C_ORCEE_H */

+ 10 - 0
src/llvm-c/Support.h

@@ -20,6 +20,12 @@
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @addtogroup LLVMCCore
+ *
+ * @{
+ */
+
 /**
 /**
  * This function permanently loads the dynamic library at the given path.
  * This function permanently loads the dynamic library at the given path.
  * It is safe to call this function multiple times for the same library.
  * It is safe to call this function multiple times for the same library.
@@ -57,6 +63,10 @@ void *LLVMSearchForAddressOfSymbol(const char *symbolName);
  */
  */
 void LLVMAddSymbol(const char *symbolName, void *symbolValue);
 void LLVMAddSymbol(const char *symbolName, void *symbolValue);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 13 - 13
src/llvm-c/Target.h

@@ -21,7 +21,7 @@
 
 
 #include "llvm-c/ExternC.h"
 #include "llvm-c/ExternC.h"
 #include "llvm-c/Types.h"
 #include "llvm-c/Types.h"
-#include "llvm-c/Config/llvm-config.h"
+#include "llvm-c/Config//llvm-config.h"
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
@@ -40,34 +40,34 @@ typedef struct LLVMOpaqueTargetLibraryInfotData *LLVMTargetLibraryInfoRef;
 /* Declare all of the target-initialization functions that are available. */
 /* Declare all of the target-initialization functions that are available. */
 #define LLVM_TARGET(TargetName) \
 #define LLVM_TARGET(TargetName) \
   void LLVMInitialize##TargetName##TargetInfo(void);
   void LLVMInitialize##TargetName##TargetInfo(void);
-#include "llvm-c/Config/Targets.def"
+#include "llvm-c/Config//Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 
 
 #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(void);
 #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(void);
-#include "llvm-c/Config/Targets.def"
+#include "llvm-c/Config//Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 
 
 #define LLVM_TARGET(TargetName) \
 #define LLVM_TARGET(TargetName) \
   void LLVMInitialize##TargetName##TargetMC(void);
   void LLVMInitialize##TargetName##TargetMC(void);
-#include "llvm-c/Config/Targets.def"
+#include "llvm-c/Config//Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 
 
 /* Declare all of the available assembly printer initialization functions. */
 /* Declare all of the available assembly printer initialization functions. */
 #define LLVM_ASM_PRINTER(TargetName) \
 #define LLVM_ASM_PRINTER(TargetName) \
   void LLVMInitialize##TargetName##AsmPrinter(void);
   void LLVMInitialize##TargetName##AsmPrinter(void);
-#include "llvm-c/Config/AsmPrinters.def"
+#include "llvm-c/Config//AsmPrinters.def"
 #undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
 #undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
 
 
 /* Declare all of the available assembly parser initialization functions. */
 /* Declare all of the available assembly parser initialization functions. */
 #define LLVM_ASM_PARSER(TargetName) \
 #define LLVM_ASM_PARSER(TargetName) \
   void LLVMInitialize##TargetName##AsmParser(void);
   void LLVMInitialize##TargetName##AsmParser(void);
-#include "llvm-c/Config/AsmParsers.def"
+#include "llvm-c/Config//AsmParsers.def"
 #undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
 #undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
 
 
 /* Declare all of the available disassembler initialization functions. */
 /* Declare all of the available disassembler initialization functions. */
 #define LLVM_DISASSEMBLER(TargetName) \
 #define LLVM_DISASSEMBLER(TargetName) \
   void LLVMInitialize##TargetName##Disassembler(void);
   void LLVMInitialize##TargetName##Disassembler(void);
-#include "llvm-c/Config/Disassemblers.def"
+#include "llvm-c/Config//Disassemblers.def"
 #undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
 #undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
 
 
 /** LLVMInitializeAllTargetInfos - The main program should call this function if
 /** LLVMInitializeAllTargetInfos - The main program should call this function if
@@ -75,7 +75,7 @@ typedef struct LLVMOpaqueTargetLibraryInfotData *LLVMTargetLibraryInfoRef;
     support. */
     support. */
 static inline void LLVMInitializeAllTargetInfos(void) {
 static inline void LLVMInitializeAllTargetInfos(void) {
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
-#include "llvm-c/Config/Targets.def"
+#include "llvm-c/Config//Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 }
 }
 
 
@@ -84,7 +84,7 @@ static inline void LLVMInitializeAllTargetInfos(void) {
     support. */
     support. */
 static inline void LLVMInitializeAllTargets(void) {
 static inline void LLVMInitializeAllTargets(void) {
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
-#include "llvm-c/Config/Targets.def"
+#include "llvm-c/Config//Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 }
 }
 
 
@@ -93,7 +93,7 @@ static inline void LLVMInitializeAllTargets(void) {
     support. */
     support. */
 static inline void LLVMInitializeAllTargetMCs(void) {
 static inline void LLVMInitializeAllTargetMCs(void) {
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
 #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
-#include "llvm-c/Config/Targets.def"
+#include "llvm-c/Config//Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 }
 }
 
 
@@ -102,7 +102,7 @@ static inline void LLVMInitializeAllTargetMCs(void) {
     available via the TargetRegistry. */
     available via the TargetRegistry. */
 static inline void LLVMInitializeAllAsmPrinters(void) {
 static inline void LLVMInitializeAllAsmPrinters(void) {
 #define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter();
 #define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter();
-#include "llvm-c/Config/AsmPrinters.def"
+#include "llvm-c/Config//AsmPrinters.def"
 #undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
 #undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
 }
 }
 
 
@@ -111,7 +111,7 @@ static inline void LLVMInitializeAllAsmPrinters(void) {
     available via the TargetRegistry. */
     available via the TargetRegistry. */
 static inline void LLVMInitializeAllAsmParsers(void) {
 static inline void LLVMInitializeAllAsmParsers(void) {
 #define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser();
 #define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser();
-#include "llvm-c/Config/AsmParsers.def"
+#include "llvm-c/Config//AsmParsers.def"
 #undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
 #undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
 }
 }
 
 
@@ -121,7 +121,7 @@ static inline void LLVMInitializeAllAsmParsers(void) {
 static inline void LLVMInitializeAllDisassemblers(void) {
 static inline void LLVMInitializeAllDisassemblers(void) {
 #define LLVM_DISASSEMBLER(TargetName) \
 #define LLVM_DISASSEMBLER(TargetName) \
   LLVMInitialize##TargetName##Disassembler();
   LLVMInitialize##TargetName##Disassembler();
-#include "llvm-c/Config/Disassemblers.def"
+#include "llvm-c/Config//Disassemblers.def"
 #undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
 #undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
 }
 }
 
 

+ 13 - 1
src/llvm-c/TargetMachine.h

@@ -25,6 +25,12 @@
 
 
 LLVM_C_EXTERN_C_BEGIN
 LLVM_C_EXTERN_C_BEGIN
 
 
+/**
+ * @addtogroup LLVMCTarget
+ *
+ * @{
+ */
+
 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
 typedef struct LLVMTarget *LLVMTargetRef;
 typedef struct LLVMTarget *LLVMTargetRef;
 
 
@@ -130,7 +136,9 @@ void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T,
   wraps several c++ only classes (among them a file stream). Returns any
   wraps several c++ only classes (among them a file stream). Returns any
   error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */
   error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */
 LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
 LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
-  char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage);
+                                     const char *Filename,
+                                     LLVMCodeGenFileType codegen,
+                                     char **ErrorMessage);
 
 
 /** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */
 /** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */
 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M,
 LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M,
@@ -156,6 +164,10 @@ char* LLVMGetHostCPUFeatures(void);
 /** Adds the target-specific analysis passes to the pass manager. */
 /** Adds the target-specific analysis passes to the pass manager. */
 void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM);
 void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM);
 
 
+/**
+ * @}
+ */
+
 LLVM_C_EXTERN_C_END
 LLVM_C_EXTERN_C_END
 
 
 #endif
 #endif

+ 0 - 40
src/llvm-c/Transforms/AggressiveInstCombine.h

@@ -1,40 +0,0 @@
-/*===-- AggressiveInstCombine.h ---------------------------------*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMAggressiveInstCombine.a,    *|
-|* which combines instructions to form fewer, simple IR instructions.         *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_AGGRESSIVEINSTCOMBINE_H
-#define LLVM_C_TRANSFORMS_AGGRESSIVEINSTCOMBINE_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsAggressiveInstCombine Aggressive Instruction Combining transformations
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createAggressiveInstCombinerPass function. */
-void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif
-

+ 0 - 56
src/llvm-c/Transforms/Coroutines.h

@@ -1,56 +0,0 @@
-/*===-- Coroutines.h - Coroutines Library C Interface -----------*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMCoroutines.a, which         *|
-|* implements various scalar transformations of the LLVM IR.                  *|
-|*                                                                            *|
-|* Many exotic languages can interoperate with C code but have a harder time  *|
-|* with C++ due to name mangling. So in addition to C, this interface enables *|
-|* tools written in such languages.                                           *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_COROUTINES_H
-#define LLVM_C_TRANSFORMS_COROUTINES_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-#include "llvm-c/Transforms/PassManagerBuilder.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsCoroutines Coroutine transformations
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createCoroEarlyLegacyPass function. */
-void LLVMAddCoroEarlyPass(LLVMPassManagerRef PM);
-
-/** See llvm::createCoroSplitLegacyPass function. */
-void LLVMAddCoroSplitPass(LLVMPassManagerRef PM);
-
-/** See llvm::createCoroElideLegacyPass function. */
-void LLVMAddCoroElidePass(LLVMPassManagerRef PM);
-
-/** See llvm::createCoroCleanupLegacyPass function. */
-void LLVMAddCoroCleanupPass(LLVMPassManagerRef PM);
-
-/** See llvm::addCoroutinePassesToExtensionPoints. */
-void LLVMPassManagerBuilderAddCoroutinePassesToExtensionPoints(LLVMPassManagerBuilderRef PMB);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif

+ 0 - 96
src/llvm-c/Transforms/IPO.h

@@ -1,96 +0,0 @@
-/*===-- IPO.h - Interprocedural Transformations C Interface -----*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMIPO.a, which implements     *|
-|* various interprocedural transformations of the LLVM IR.                    *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_IPO_H
-#define LLVM_C_TRANSFORMS_IPO_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsIPO Interprocedural transformations
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createArgumentPromotionPass function. */
-void LLVMAddArgumentPromotionPass(LLVMPassManagerRef PM);
-
-/** See llvm::createConstantMergePass function. */
-void LLVMAddConstantMergePass(LLVMPassManagerRef PM);
-
-/** See llvm::createMergeFunctionsPass function. */
-void LLVMAddMergeFunctionsPass(LLVMPassManagerRef PM);
-
-/** See llvm::createCalledValuePropagationPass function. */
-void LLVMAddCalledValuePropagationPass(LLVMPassManagerRef PM);
-
-/** See llvm::createDeadArgEliminationPass function. */
-void LLVMAddDeadArgEliminationPass(LLVMPassManagerRef PM);
-
-/** See llvm::createFunctionAttrsPass function. */
-void LLVMAddFunctionAttrsPass(LLVMPassManagerRef PM);
-
-/** See llvm::createFunctionInliningPass function. */
-void LLVMAddFunctionInliningPass(LLVMPassManagerRef PM);
-
-/** See llvm::createAlwaysInlinerPass function. */
-void LLVMAddAlwaysInlinerPass(LLVMPassManagerRef PM);
-
-/** See llvm::createGlobalDCEPass function. */
-void LLVMAddGlobalDCEPass(LLVMPassManagerRef PM);
-
-/** See llvm::createGlobalOptimizerPass function. */
-void LLVMAddGlobalOptimizerPass(LLVMPassManagerRef PM);
-
-/** See llvm::createPruneEHPass function. */
-void LLVMAddPruneEHPass(LLVMPassManagerRef PM);
-
-/** See llvm::createIPSCCPPass function. */
-void LLVMAddIPSCCPPass(LLVMPassManagerRef PM);
-
-/** See llvm::createInternalizePass function. */
-void LLVMAddInternalizePass(LLVMPassManagerRef, unsigned AllButMain);
-
-/**
- * Create and add the internalize pass to the given pass manager with the
- * provided preservation callback.
- *
- * The context parameter is forwarded to the callback on each invocation.
- * As such, it is the responsibility of the caller to extend its lifetime
- * until execution of this pass has finished.
- *
- * @see llvm::createInternalizePass function.
- */
-void LLVMAddInternalizePassWithMustPreservePredicate(
-    LLVMPassManagerRef PM,
-    void *Context,
-    LLVMBool (*MustPreserve)(LLVMValueRef, void *));
-
-/** See llvm::createStripDeadPrototypesPass function. */
-void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM);
-
-/** See llvm::createStripSymbolsPass function. */
-void LLVMAddStripSymbolsPass(LLVMPassManagerRef PM);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif

+ 0 - 40
src/llvm-c/Transforms/InstCombine.h

@@ -1,40 +0,0 @@
-/*===-- Scalar.h - Scalar Transformation Library C Interface ----*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMInstCombine.a, which        *|
-|* combines instructions to form fewer, simple IR instructions.               *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_INSTCOMBINE_H
-#define LLVM_C_TRANSFORMS_INSTCOMBINE_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsInstCombine Instruction Combining transformations
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createInstructionCombiningPass function. */
-void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif
-

+ 116 - 0
src/llvm-c/Transforms/PassBuilder.h

@@ -0,0 +1,116 @@
+/*===-- llvm-c/Transform/PassBuilder.h - PassBuilder for LLVM C ---*- C -*-===*\
+|*                                                                            *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
+|* Exceptions.                                                                *|
+|* See https://llvm.org/LICENSE.txt for license information.                  *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
+|*                                                                            *|
+|*===----------------------------------------------------------------------===*|
+|*                                                                            *|
+|* This header contains the LLVM-C interface into the new pass manager        *|
+|*                                                                            *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_TRANSFORMS_PASSBUILDER_H
+#define LLVM_C_TRANSFORMS_PASSBUILDER_H
+
+#include "llvm-c/Error.h"
+#include "llvm-c/TargetMachine.h"
+#include "llvm-c/Types.h"
+
+/**
+ * @defgroup LLVMCCoreNewPM New Pass Manager
+ * @ingroup LLVMCCore
+ *
+ * @{
+ */
+
+LLVM_C_EXTERN_C_BEGIN
+
+/**
+ * A set of options passed which are attached to the Pass Manager upon run.
+ *
+ * This corresponds to an llvm::LLVMPassBuilderOptions instance
+ *
+ * The details for how the different properties of this structure are used can
+ * be found in the source for LLVMRunPasses
+ */
+typedef struct LLVMOpaquePassBuilderOptions *LLVMPassBuilderOptionsRef;
+
+/**
+ * Construct and run a set of passes over a module
+ *
+ * This function takes a string with the passes that should be used. The format
+ * of this string is the same as opt's -passes argument for the new pass
+ * manager. Individual passes may be specified, separated by commas. Full
+ * pipelines may also be invoked using `default<O3>` and friends. See opt for
+ * full reference of the Passes format.
+ */
+LLVMErrorRef LLVMRunPasses(LLVMModuleRef M, const char *Passes,
+                           LLVMTargetMachineRef TM,
+                           LLVMPassBuilderOptionsRef Options);
+
+/**
+ * Create a new set of options for a PassBuilder
+ *
+ * Ownership of the returned instance is given to the client, and they are
+ * responsible for it. The client should call LLVMDisposePassBuilderOptions
+ * to free the pass builder options.
+ */
+LLVMPassBuilderOptionsRef LLVMCreatePassBuilderOptions(void);
+
+/**
+ * Toggle adding the VerifierPass for the PassBuilder, ensuring all functions
+ * inside the module is valid.
+ */
+void LLVMPassBuilderOptionsSetVerifyEach(LLVMPassBuilderOptionsRef Options,
+                                         LLVMBool VerifyEach);
+
+/**
+ * Toggle debug logging when running the PassBuilder
+ */
+void LLVMPassBuilderOptionsSetDebugLogging(LLVMPassBuilderOptionsRef Options,
+                                           LLVMBool DebugLogging);
+
+void LLVMPassBuilderOptionsSetLoopInterleaving(
+    LLVMPassBuilderOptionsRef Options, LLVMBool LoopInterleaving);
+
+void LLVMPassBuilderOptionsSetLoopVectorization(
+    LLVMPassBuilderOptionsRef Options, LLVMBool LoopVectorization);
+
+void LLVMPassBuilderOptionsSetSLPVectorization(
+    LLVMPassBuilderOptionsRef Options, LLVMBool SLPVectorization);
+
+void LLVMPassBuilderOptionsSetLoopUnrolling(LLVMPassBuilderOptionsRef Options,
+                                            LLVMBool LoopUnrolling);
+
+void LLVMPassBuilderOptionsSetForgetAllSCEVInLoopUnroll(
+    LLVMPassBuilderOptionsRef Options, LLVMBool ForgetAllSCEVInLoopUnroll);
+
+void LLVMPassBuilderOptionsSetLicmMssaOptCap(LLVMPassBuilderOptionsRef Options,
+                                             unsigned LicmMssaOptCap);
+
+void LLVMPassBuilderOptionsSetLicmMssaNoAccForPromotionCap(
+    LLVMPassBuilderOptionsRef Options, unsigned LicmMssaNoAccForPromotionCap);
+
+void LLVMPassBuilderOptionsSetCallGraphProfile(
+    LLVMPassBuilderOptionsRef Options, LLVMBool CallGraphProfile);
+
+void LLVMPassBuilderOptionsSetMergeFunctions(LLVMPassBuilderOptionsRef Options,
+                                             LLVMBool MergeFunctions);
+
+void LLVMPassBuilderOptionsSetInlinerThreshold(
+    LLVMPassBuilderOptionsRef Options, int Threshold);
+
+/**
+ * Dispose of a heap-allocated PassBuilderOptions instance
+ */
+void LLVMDisposePassBuilderOptions(LLVMPassBuilderOptionsRef Options);
+
+/**
+ * @}
+ */
+
+LLVM_C_EXTERN_C_END
+
+#endif // LLVM_C_TRANSFORMS_PASSBUILDER_H

+ 0 - 87
src/llvm-c/Transforms/PassManagerBuilder.h

@@ -1,87 +0,0 @@
-/*===-- llvm-c/Transform/PassManagerBuilder.h - PMB C Interface ---*- C -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to the PassManagerBuilder class.      *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_PASSMANAGERBUILDER_H
-#define LLVM_C_TRANSFORMS_PASSMANAGERBUILDER_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-typedef struct LLVMOpaquePassManagerBuilder *LLVMPassManagerBuilderRef;
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsPassManagerBuilder Pass manager builder
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::PassManagerBuilder. */
-LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void);
-void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB);
-
-/** See llvm::PassManagerBuilder::OptLevel. */
-void
-LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
-                                  unsigned OptLevel);
-
-/** See llvm::PassManagerBuilder::SizeLevel. */
-void
-LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
-                                   unsigned SizeLevel);
-
-/** See llvm::PassManagerBuilder::DisableUnitAtATime. */
-void
-LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
-                                            LLVMBool Value);
-
-/** See llvm::PassManagerBuilder::DisableUnrollLoops. */
-void
-LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
-                                            LLVMBool Value);
-
-/** See llvm::PassManagerBuilder::DisableSimplifyLibCalls */
-void
-LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
-                                                 LLVMBool Value);
-
-/** See llvm::PassManagerBuilder::Inliner. */
-void
-LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
-                                              unsigned Threshold);
-
-/** See llvm::PassManagerBuilder::populateFunctionPassManager. */
-void
-LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
-                                                  LLVMPassManagerRef PM);
-
-/** See llvm::PassManagerBuilder::populateModulePassManager. */
-void
-LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
-                                                LLVMPassManagerRef PM);
-
-/** See llvm::PassManagerBuilder::populateLTOPassManager. */
-void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
-                                                  LLVMPassManagerRef PM,
-                                                  LLVMBool Internalize,
-                                                  LLVMBool RunInliner);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif

+ 0 - 170
src/llvm-c/Transforms/Scalar.h

@@ -1,170 +0,0 @@
-/*===-- Scalar.h - Scalar Transformation Library C Interface ----*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMScalarOpts.a, which         *|
-|* implements various scalar transformations of the LLVM IR.                  *|
-|*                                                                            *|
-|* Many exotic languages can interoperate with C code but have a harder time  *|
-|* with C++ due to name mangling. So in addition to C, this interface enables *|
-|* tools written in such languages.                                           *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_SCALAR_H
-#define LLVM_C_TRANSFORMS_SCALAR_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsScalar Scalar transformations
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createAggressiveDCEPass function. */
-void LLVMAddAggressiveDCEPass(LLVMPassManagerRef PM);
-
-/** See llvm::createDeadCodeEliminationPass function. */
-void LLVMAddDCEPass(LLVMPassManagerRef PM);
-
-/** See llvm::createBitTrackingDCEPass function. */
-void LLVMAddBitTrackingDCEPass(LLVMPassManagerRef PM);
-
-/** See llvm::createAlignmentFromAssumptionsPass function. */
-void LLVMAddAlignmentFromAssumptionsPass(LLVMPassManagerRef PM);
-
-/** See llvm::createCFGSimplificationPass function. */
-void LLVMAddCFGSimplificationPass(LLVMPassManagerRef PM);
-
-/** See llvm::createDeadStoreEliminationPass function. */
-void LLVMAddDeadStoreEliminationPass(LLVMPassManagerRef PM);
-
-/** See llvm::createScalarizerPass function. */
-void LLVMAddScalarizerPass(LLVMPassManagerRef PM);
-
-/** See llvm::createMergedLoadStoreMotionPass function. */
-void LLVMAddMergedLoadStoreMotionPass(LLVMPassManagerRef PM);
-
-/** See llvm::createGVNPass function. */
-void LLVMAddGVNPass(LLVMPassManagerRef PM);
-
-/** See llvm::createGVNPass function. */
-void LLVMAddNewGVNPass(LLVMPassManagerRef PM);
-
-/** See llvm::createIndVarSimplifyPass function. */
-void LLVMAddIndVarSimplifyPass(LLVMPassManagerRef PM);
-
-/** See llvm::createInstructionCombiningPass function. */
-void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM);
-
-/** See llvm::createInstSimplifyLegacyPass function. */
-void LLVMAddInstructionSimplifyPass(LLVMPassManagerRef PM);
-
-/** See llvm::createJumpThreadingPass function. */
-void LLVMAddJumpThreadingPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLICMPass function. */
-void LLVMAddLICMPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopDeletionPass function. */
-void LLVMAddLoopDeletionPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopIdiomPass function */
-void LLVMAddLoopIdiomPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopRotatePass function. */
-void LLVMAddLoopRotatePass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopRerollPass function. */
-void LLVMAddLoopRerollPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopUnrollPass function. */
-void LLVMAddLoopUnrollPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopUnrollAndJamPass function. */
-void LLVMAddLoopUnrollAndJamPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLoopUnswitchPass function. */
-void LLVMAddLoopUnswitchPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLowerAtomicPass function. */
-void LLVMAddLowerAtomicPass(LLVMPassManagerRef PM);
-
-/** See llvm::createMemCpyOptPass function. */
-void LLVMAddMemCpyOptPass(LLVMPassManagerRef PM);
-
-/** See llvm::createPartiallyInlineLibCallsPass function. */
-void LLVMAddPartiallyInlineLibCallsPass(LLVMPassManagerRef PM);
-
-/** See llvm::createReassociatePass function. */
-void LLVMAddReassociatePass(LLVMPassManagerRef PM);
-
-/** See llvm::createSCCPPass function. */
-void LLVMAddSCCPPass(LLVMPassManagerRef PM);
-
-/** See llvm::createSROAPass function. */
-void LLVMAddScalarReplAggregatesPass(LLVMPassManagerRef PM);
-
-/** See llvm::createSROAPass function. */
-void LLVMAddScalarReplAggregatesPassSSA(LLVMPassManagerRef PM);
-
-/** See llvm::createSROAPass function. */
-void LLVMAddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef PM,
-                                                  int Threshold);
-
-/** See llvm::createSimplifyLibCallsPass function. */
-void LLVMAddSimplifyLibCallsPass(LLVMPassManagerRef PM);
-
-/** See llvm::createTailCallEliminationPass function. */
-void LLVMAddTailCallEliminationPass(LLVMPassManagerRef PM);
-
-/** See llvm::demotePromoteMemoryToRegisterPass function. */
-void LLVMAddDemoteMemoryToRegisterPass(LLVMPassManagerRef PM);
-
-/** See llvm::createVerifierPass function. */
-void LLVMAddVerifierPass(LLVMPassManagerRef PM);
-
-/** See llvm::createCorrelatedValuePropagationPass function */
-void LLVMAddCorrelatedValuePropagationPass(LLVMPassManagerRef PM);
-
-/** See llvm::createEarlyCSEPass function */
-void LLVMAddEarlyCSEPass(LLVMPassManagerRef PM);
-
-/** See llvm::createEarlyCSEPass function */
-void LLVMAddEarlyCSEMemSSAPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLowerExpectIntrinsicPass function */
-void LLVMAddLowerExpectIntrinsicPass(LLVMPassManagerRef PM);
-
-/** See llvm::createLowerConstantIntrinsicsPass function */
-void LLVMAddLowerConstantIntrinsicsPass(LLVMPassManagerRef PM);
-
-/** See llvm::createTypeBasedAliasAnalysisPass function */
-void LLVMAddTypeBasedAliasAnalysisPass(LLVMPassManagerRef PM);
-
-/** See llvm::createScopedNoAliasAAPass function */
-void LLVMAddScopedNoAliasAAPass(LLVMPassManagerRef PM);
-
-/** See llvm::createBasicAliasAnalysisPass function */
-void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM);
-
-/** See llvm::createUnifyFunctionExitNodesPass function */
-void LLVMAddUnifyFunctionExitNodesPass(LLVMPassManagerRef PM);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif

+ 0 - 50
src/llvm-c/Transforms/Utils.h

@@ -1,50 +0,0 @@
-/*===-- Utils.h - Transformation Utils Library C Interface ------*- C++ -*-===*\
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMTransformUtils.a, which     *|
-|* implements various transformation utilities of the LLVM IR.                *|
-|*                                                                            *|
-|* Many exotic languages can interoperate with C code but have a harder time  *|
-|* with C++ due to name mangling. So in addition to C, this interface enables *|
-|* tools written in such languages.                                           *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_UTILS_H
-#define LLVM_C_TRANSFORMS_UTILS_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsUtils Transformation Utilities
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createLowerSwitchPass function. */
-void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM);
-
-/** See llvm::createPromoteMemoryToRegisterPass function. */
-void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM);
-
-/** See llvm::createAddDiscriminatorsPass function. */
-void LLVMAddAddDiscriminatorsPass(LLVMPassManagerRef PM);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif
-

+ 0 - 47
src/llvm-c/Transforms/Vectorize.h

@@ -1,47 +0,0 @@
-/*===---------------------------Vectorize.h --------------------- -*- C -*-===*\
-|*===----------- Vectorization Transformation Library C Interface ---------===*|
-|*                                                                            *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM          *|
-|* Exceptions.                                                                *|
-|* See https://llvm.org/LICENSE.txt for license information.                  *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception                    *|
-|*                                                                            *|
-|*===----------------------------------------------------------------------===*|
-|*                                                                            *|
-|* This header declares the C interface to libLLVMVectorize.a, which          *|
-|* implements various vectorization transformations of the LLVM IR.           *|
-|*                                                                            *|
-|* Many exotic languages can interoperate with C code but have a harder time  *|
-|* with C++ due to name mangling. So in addition to C, this interface enables *|
-|* tools written in such languages.                                           *|
-|*                                                                            *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef LLVM_C_TRANSFORMS_VECTORIZE_H
-#define LLVM_C_TRANSFORMS_VECTORIZE_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsVectorize Vectorization transformations
- * @ingroup LLVMCTransforms
- *
- * @{
- */
-
-/** See llvm::createLoopVectorizePass function. */
-void LLVMAddLoopVectorizePass(LLVMPassManagerRef PM);
-
-/** See llvm::createSLPVectorizerPass function. */
-void LLVMAddSLPVectorizePass(LLVMPassManagerRef PM);
-
-/**
- * @}
- */
-
-LLVM_C_EXTERN_C_END
-
-#endif

+ 0 - 3
src/llvm-c/Types.h

@@ -126,9 +126,6 @@ typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef;
 /** @see llvm::PassManagerBase */
 /** @see llvm::PassManagerBase */
 typedef struct LLVMOpaquePassManager *LLVMPassManagerRef;
 typedef struct LLVMOpaquePassManager *LLVMPassManagerRef;
 
 
-/** @see llvm::PassRegistry */
-typedef struct LLVMOpaquePassRegistry *LLVMPassRegistryRef;
-
 /**
 /**
  * Used to get the users and usees of a Value.
  * Used to get the users and usees of a Value.
  *
  *

+ 79 - 0
src/llvm-c/blake3.h

@@ -0,0 +1,79 @@
+/*===-- llvm-c/blake3.h - BLAKE3 C Interface ----------------------*- C -*-===*\
+|*                                                                            *|
+|* Released into the public domain with CC0 1.0                               *|
+|* See 'llvm/lib/Support/BLAKE3/LICENSE' for info.                            *|
+|* SPDX-License-Identifier: CC0-1.0                                           *|
+|*                                                                            *|
+|*===----------------------------------------------------------------------===*|
+|*                                                                            *|
+|* This header declares the C interface to LLVM's BLAKE3 implementation.      *|
+|* Original BLAKE3 C API: https://github.com/BLAKE3-team/BLAKE3/tree/1.3.1/c  *|
+|*                                                                            *|
+|* Symbols are prefixed with 'llvm' to avoid a potential conflict with        *|
+|* another BLAKE3 version within the same program.                            *|
+|*                                                                            *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_C_BLAKE3_H
+#define LLVM_C_BLAKE3_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define LLVM_BLAKE3_VERSION_STRING "1.3.1"
+#define LLVM_BLAKE3_KEY_LEN 32
+#define LLVM_BLAKE3_OUT_LEN 32
+#define LLVM_BLAKE3_BLOCK_LEN 64
+#define LLVM_BLAKE3_CHUNK_LEN 1024
+#define LLVM_BLAKE3_MAX_DEPTH 54
+
+// This struct is a private implementation detail. It has to be here because
+// it's part of llvm_blake3_hasher below.
+typedef struct {
+  uint32_t cv[8];
+  uint64_t chunk_counter;
+  uint8_t buf[LLVM_BLAKE3_BLOCK_LEN];
+  uint8_t buf_len;
+  uint8_t blocks_compressed;
+  uint8_t flags;
+} llvm_blake3_chunk_state;
+
+typedef struct {
+  uint32_t key[8];
+  llvm_blake3_chunk_state chunk;
+  uint8_t cv_stack_len;
+  // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example,
+  // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk
+  // requires a 4th entry, rather than merging everything down to 1, because we
+  // don't know whether more input is coming. This is different from how the
+  // reference implementation does things.
+  uint8_t cv_stack[(LLVM_BLAKE3_MAX_DEPTH + 1) * LLVM_BLAKE3_OUT_LEN];
+} llvm_blake3_hasher;
+
+const char *llvm_blake3_version(void);
+void llvm_blake3_hasher_init(llvm_blake3_hasher *self);
+void llvm_blake3_hasher_init_keyed(llvm_blake3_hasher *self,
+                                   const uint8_t key[LLVM_BLAKE3_KEY_LEN]);
+void llvm_blake3_hasher_init_derive_key(llvm_blake3_hasher *self,
+                                        const char *context);
+void llvm_blake3_hasher_init_derive_key_raw(llvm_blake3_hasher *self,
+                                            const void *context,
+                                            size_t context_len);
+void llvm_blake3_hasher_update(llvm_blake3_hasher *self, const void *input,
+                               size_t input_len);
+void llvm_blake3_hasher_finalize(const llvm_blake3_hasher *self, uint8_t *out,
+                                 size_t out_len);
+void llvm_blake3_hasher_finalize_seek(const llvm_blake3_hasher *self,
+                                      uint64_t seek, uint8_t *out,
+                                      size_t out_len);
+void llvm_blake3_hasher_reset(llvm_blake3_hasher *self);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LLVM_C_BLAKE3_H */

+ 28 - 2
src/llvm-c/lto.h

@@ -46,7 +46,7 @@ typedef bool lto_bool_t;
  * @{
  * @{
  */
  */
 
 
-#define LTO_API_VERSION 27
+#define LTO_API_VERSION 29
 
 
 /**
 /**
  * \since prior to LTO_API_VERSION=3
  * \since prior to LTO_API_VERSION=3
@@ -312,6 +312,16 @@ extern lto_bool_t lto_module_get_macho_cputype(lto_module_t mod,
                                                unsigned int *out_cputype,
                                                unsigned int *out_cputype,
                                                unsigned int *out_cpusubtype);
                                                unsigned int *out_cpusubtype);
 
 
+/**
+ * This function can be used by the linker to check if a given module has
+ * any constructor or destructor functions.
+ *
+ * Returns true if the module has either the @llvm.global_ctors or the
+ * @llvm.global_dtors symbol. Otherwise returns false.
+ *
+ * \since LTO_API_VERSION=29
+ */
+extern lto_bool_t lto_module_has_ctor_dtor(lto_module_t mod);
 /**
 /**
  * Diagnostic severity.
  * Diagnostic severity.
  *
  *
@@ -527,7 +537,23 @@ extern unsigned int
 lto_api_version(void);
 lto_api_version(void);
 
 
 /**
 /**
- * Sets options to help debug codegen bugs.
+ * Parses options immediately, making them available as early as possible. For
+ * example during executing codegen::InitTargetOptionsFromCodeGenFlags. Since
+ * parsing shud only happen once, only one of lto_codegen_debug_options or
+ * lto_set_debug_options should be called.
+ *
+ * This function takes one or more options separated by spaces.
+ * Warning: passing file paths through this function may confuse the argument
+ * parser if the paths contain spaces.
+ *
+ * \since LTO_API_VERSION=28
+ */
+extern void lto_set_debug_options(const char *const *options, int number);
+
+/**
+ * Sets options to help debug codegen bugs. Since parsing shud only happen once,
+ * only one of lto_codegen_debug_options or lto_set_debug_options
+ * should be called.
  *
  *
  * This function takes one or more options separated by spaces.
  * This function takes one or more options separated by spaces.
  * Warning: passing file paths through this function may confuse the argument
  * Warning: passing file paths through this function may confuse the argument

+ 7 - 7
src/llvm_abi.cpp

@@ -1130,14 +1130,14 @@ namespace lbAbiArm64 {
 			return non_struct(c, return_type);
 			return non_struct(c, return_type);
 		} else if (is_homogenous_aggregate(c, return_type, &homo_base_type, &homo_member_count)) {
 		} else if (is_homogenous_aggregate(c, return_type, &homo_base_type, &homo_member_count)) {
 			if (is_homogenous_aggregate_small_enough(homo_base_type, homo_member_count)) {
 			if (is_homogenous_aggregate_small_enough(homo_base_type, homo_member_count)) {
-				return lb_arg_type_direct(return_type, LLVMArrayType(homo_base_type, homo_member_count), nullptr, nullptr);
+				return lb_arg_type_direct(return_type, llvm_array_type(homo_base_type, homo_member_count), nullptr, nullptr);
 			} else {
 			} else {
 				//TODO(Platin): do i need to create stuff that can handle the diffrent return type?
 				//TODO(Platin): do i need to create stuff that can handle the diffrent return type?
 				//              else this needs a fix in llvm_backend_proc as we would need to cast it to the correct array type
 				//              else this needs a fix in llvm_backend_proc as we would need to cast it to the correct array type
 
 
 				LB_ABI_MODIFY_RETURN_IF_TUPLE_MACRO();
 				LB_ABI_MODIFY_RETURN_IF_TUPLE_MACRO();
 
 
-				//LLVMTypeRef array_type = LLVMArrayType(homo_base_type, homo_member_count);
+				//LLVMTypeRef array_type = llvm_array_type(homo_base_type, homo_member_count);
 				LLVMAttributeRef attr = lb_create_enum_attribute_with_type(c, "sret", return_type);
 				LLVMAttributeRef attr = lb_create_enum_attribute_with_type(c, "sret", return_type);
 				return lb_arg_type_indirect(return_type, attr);
 				return lb_arg_type_indirect(return_type, attr);
 			}
 			}
@@ -1155,7 +1155,7 @@ namespace lbAbiArm64 {
 					cast_type = LLVMInt64TypeInContext(c);
 					cast_type = LLVMInt64TypeInContext(c);
 				} else {
 				} else {
 					unsigned count = cast(unsigned)((size+7)/8);
 					unsigned count = cast(unsigned)((size+7)/8);
-					cast_type = LLVMArrayType(LLVMInt64TypeInContext(c), count);
+					cast_type = llvm_array_type(LLVMInt64TypeInContext(c), count);
 				}
 				}
 				return lb_arg_type_direct(return_type, cast_type, nullptr, nullptr);
 				return lb_arg_type_direct(return_type, cast_type, nullptr, nullptr);
 			} else {
 			} else {
@@ -1180,7 +1180,7 @@ namespace lbAbiArm64 {
 				args[i] = non_struct(c, type);
 				args[i] = non_struct(c, type);
 			} else if (is_homogenous_aggregate(c, type, &homo_base_type, &homo_member_count)) {
 			} else if (is_homogenous_aggregate(c, type, &homo_base_type, &homo_member_count)) {
 				if (is_homogenous_aggregate_small_enough(homo_base_type, homo_member_count)) {
 				if (is_homogenous_aggregate_small_enough(homo_base_type, homo_member_count)) {
-					args[i] = lb_arg_type_direct(type, LLVMArrayType(homo_base_type, homo_member_count), nullptr, nullptr);
+					args[i] = lb_arg_type_direct(type, llvm_array_type(homo_base_type, homo_member_count), nullptr, nullptr);
 				} else {
 				} else {
 					args[i] = lb_arg_type_indirect(type, nullptr);;
 					args[i] = lb_arg_type_indirect(type, nullptr);;
 				}
 				}
@@ -1198,7 +1198,7 @@ namespace lbAbiArm64 {
 						cast_type = LLVMIntTypeInContext(c, 64);
 						cast_type = LLVMIntTypeInContext(c, 64);
 					} else {
 					} else {
 						unsigned count = cast(unsigned)((size+7)/8);
 						unsigned count = cast(unsigned)((size+7)/8);
-						cast_type = LLVMArrayType(LLVMIntTypeInContext(c, 64), count);
+						cast_type = llvm_array_type(LLVMIntTypeInContext(c, 64), count);
 					}
 					}
 					args[i] = lb_arg_type_direct(type, cast_type, nullptr, nullptr);
 					args[i] = lb_arg_type_direct(type, cast_type, nullptr, nullptr);
 				} else {
 				} else {
@@ -1439,10 +1439,10 @@ namespace lbAbiArm32 {
 					args[i] = lb_arg_type_indirect(t, nullptr);
 					args[i] = lb_arg_type_indirect(t, nullptr);
 				} else if (a <= 4) {
 				} else if (a <= 4) {
 					unsigned n = cast(unsigned)((sz + 3) / 4);
 					unsigned n = cast(unsigned)((sz + 3) / 4);
-					args[i] = lb_arg_type_direct(LLVMArrayType(LLVMIntTypeInContext(c, 32), n));
+					args[i] = lb_arg_type_direct(llvm_array_type(LLVMIntTypeInContext(c, 32), n));
 				} else {
 				} else {
 					unsigned n = cast(unsigned)((sz + 7) / 8);
 					unsigned n = cast(unsigned)((sz + 7) / 8);
-					args[i] = lb_arg_type_direct(LLVMArrayType(LLVMIntTypeInContext(c, 64), n));
+					args[i] = lb_arg_type_direct(llvm_array_type(LLVMIntTypeInContext(c, 64), n));
 				}
 				}
 			}
 			}
 		}
 		}

+ 191 - 74
src/llvm_backend.cpp

@@ -168,7 +168,7 @@ gb_internal lbValue lb_equal_proc_for_type(lbModule *m, Type *type) {
 	map_set(&m->equal_procs, type, p);
 	map_set(&m->equal_procs, type, p);
 	lb_begin_procedure_body(p);
 	lb_begin_procedure_body(p);
 
 
-	lb_add_attribute_to_proc(m, p->value, "readonly");
+	// lb_add_attribute_to_proc(m, p->value, "readonly");
 	lb_add_attribute_to_proc(m, p->value, "nounwind");
 	lb_add_attribute_to_proc(m, p->value, "nounwind");
 
 
 	LLVMValueRef x = LLVMGetParam(p->value, 0);
 	LLVMValueRef x = LLVMGetParam(p->value, 0);
@@ -337,7 +337,7 @@ gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
 	lb_begin_procedure_body(p);
 	lb_begin_procedure_body(p);
 	defer (lb_end_procedure_body(p));
 	defer (lb_end_procedure_body(p));
 
 
-	lb_add_attribute_to_proc(m, p->value, "readonly");
+	// lb_add_attribute_to_proc(m, p->value, "readonly");
 	lb_add_attribute_to_proc(m, p->value, "nounwind");
 	lb_add_attribute_to_proc(m, p->value, "nounwind");
 
 
 	LLVMValueRef x = LLVMGetParam(p->value, 0);
 	LLVMValueRef x = LLVMGetParam(p->value, 0);
@@ -346,7 +346,7 @@ gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
 	lbValue seed = {y, t_uintptr};
 	lbValue seed = {y, t_uintptr};
 
 
 	lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
 	lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
-	lb_add_proc_attribute_at_index(p, 1+0, "readonly");
+	// lb_add_proc_attribute_at_index(p, 1+0, "readonly");
 
 
 	if (is_type_simple_compare(type)) {
 	if (is_type_simple_compare(type)) {
 		lbValue res = lb_simple_compare_hash(p, type, data, seed);
 		lbValue res = lb_simple_compare_hash(p, type, data, seed);
@@ -1025,6 +1025,10 @@ gb_internal lbProcedure *lb_create_startup_type_info(lbModule *m) {
 	LLVMSetLinkage(p->value, LLVMInternalLinkage);
 	LLVMSetLinkage(p->value, LLVMInternalLinkage);
 
 
 	lb_add_attribute_to_proc(m, p->value, "nounwind");
 	lb_add_attribute_to_proc(m, p->value, "nounwind");
+	if (!LB_USE_GIANT_PACKED_STRUCT) {
+		lb_add_attribute_to_proc(m, p->value, "optnone");
+		lb_add_attribute_to_proc(m, p->value, "noinline");
+	}
 
 
 	lb_begin_procedure_body(p);
 	lb_begin_procedure_body(p);
 
 
@@ -1086,6 +1090,8 @@ gb_internal lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProc
 
 
 	lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
 	lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
 	p->is_startup = true;
 	p->is_startup = true;
+	lb_add_attribute_to_proc(p->module, p->value, "optnone");
+	lb_add_attribute_to_proc(p->module, p->value, "noinline");
 
 
 	lb_begin_procedure_body(p);
 	lb_begin_procedure_body(p);
 
 
@@ -1189,6 +1195,8 @@ gb_internal lbProcedure *lb_create_cleanup_runtime(lbModule *main_module) { // C
 
 
 	lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
 	lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
 	p->is_startup = true;
 	p->is_startup = true;
+	lb_add_attribute_to_proc(p->module, p->value, "optnone");
+	lb_add_attribute_to_proc(p->module, p->value, "noinline");
 
 
 	lb_begin_procedure_body(p);
 	lb_begin_procedure_body(p);
 
 
@@ -1352,33 +1360,25 @@ gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
 	{
 	{
 		GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
 		GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
 
 
-		m->function_pass_managers[lbFunctionPassManager_default]                = LLVMCreateFunctionPassManagerForModule(m->mod);
-		m->function_pass_managers[lbFunctionPassManager_default_without_memcpy] = LLVMCreateFunctionPassManagerForModule(m->mod);
-		m->function_pass_managers[lbFunctionPassManager_none]                   = LLVMCreateFunctionPassManagerForModule(m->mod);
-		m->function_pass_managers[lbFunctionPassManager_minimal]                = LLVMCreateFunctionPassManagerForModule(m->mod);
-		m->function_pass_managers[lbFunctionPassManager_size]                   = LLVMCreateFunctionPassManagerForModule(m->mod);
-		m->function_pass_managers[lbFunctionPassManager_speed]                  = LLVMCreateFunctionPassManagerForModule(m->mod);
+		for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
+			m->function_pass_managers[i] = LLVMCreateFunctionPassManagerForModule(m->mod);
+		}
 
 
-		LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default]);
-		LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default_without_memcpy]);
-		LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_none]);
-		LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_minimal]);
-		LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_size]);
-		LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_speed]);
+		for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
+			LLVMInitializeFunctionPassManager(m->function_pass_managers[i]);
+		}
 
 
 		lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default],                false, build_context.optimization_level);
 		lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default],                false, build_context.optimization_level);
 		lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true,  build_context.optimization_level);
 		lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true,  build_context.optimization_level);
-		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none],   -1);
-		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_minimal], 0);
-		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_size],    1);
-		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_speed],   2);
+		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none],      -1);
+		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_minimal],    0);
+		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_size],       1);
+		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_speed],      2);
+		lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_aggressive], 3);
 
 
-		LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default]);
-		LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default_without_memcpy]);
-		LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_none]);
-		LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_minimal]);
-		LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_size]);
-		LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_speed]);
+		for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
+			LLVMFinalizeFunctionPassManager(m->function_pass_managers[i]);
+		}
 	}
 	}
 
 
 	if (m == &m->gen->default_module) {
 	if (m == &m->gen->default_module) {
@@ -1393,6 +1393,8 @@ gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
 			lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
 			lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
 			if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
 			if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
 				pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
 				pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
+				lb_add_attribute_to_proc(p->module, p->value, "optnone");
+				lb_add_attribute_to_proc(p->module, p->value, "noinline");
 			} else {
 			} else {
 				if (p->entity && p->entity->kind == Entity_Procedure) {
 				if (p->entity && p->entity->kind == Entity_Procedure) {
 					switch (p->entity->Procedure.optimization_mode) {
 					switch (p->entity->Procedure.optimization_mode) {
@@ -1402,6 +1404,7 @@ gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
 						break;
 						break;
 					case ProcedureOptimizationMode_Size:
 					case ProcedureOptimizationMode_Size:
 						pass_manager_kind = lbFunctionPassManager_size;
 						pass_manager_kind = lbFunctionPassManager_size;
+						lb_add_attribute_to_proc(p->module, p->value, "optsize");
 						break;
 						break;
 					case ProcedureOptimizationMode_Speed:
 					case ProcedureOptimizationMode_Speed:
 						pass_manager_kind = lbFunctionPassManager_speed;
 						pass_manager_kind = lbFunctionPassManager_speed;
@@ -1449,6 +1452,83 @@ gb_internal WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
 	LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
 	LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
 	lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
 	lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
 	LLVMRunPassManager(module_pass_manager, wd->m->mod);
 	LLVMRunPassManager(module_pass_manager, wd->m->mod);
+
+
+#if LB_USE_NEW_PASS_SYSTEM
+	auto passes = array_make<char const *>(heap_allocator(), 0, 64);
+	defer (array_free(&passes));
+
+
+
+	LLVMPassBuilderOptionsRef pb_options = LLVMCreatePassBuilderOptions();
+	defer (LLVMDisposePassBuilderOptions(pb_options));
+
+	switch (build_context.optimization_level) {
+	case -1:
+		break;
+	case 0:
+		array_add(&passes, "always-inline");
+		array_add(&passes, "function(annotation-remarks)");
+		break;
+	case 1:
+		array_add(&passes, "default<Os>");
+		break;
+	case 2:
+		array_add(&passes, "default<O2>");
+		break;
+	case 3:
+		array_add(&passes, "default<O3>");
+		break;
+	}
+
+	// asan - Linux, Darwin, Windows
+	// msan - linux
+	// tsan - Linux, Darwin
+	// ubsan - Linux, Darwin, Windows (NOT SUPPORTED WITH LLVM C-API)
+
+	if (build_context.sanitizer_flags & SanitizerFlag_Address) {
+		array_add(&passes, "asan");
+	}
+	if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
+		array_add(&passes, "msan");
+	}
+	if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
+		array_add(&passes, "tsan");
+	}
+
+	if (passes.count == 0) {
+		array_add(&passes, "verify");
+	}
+
+	gbString passes_str = gb_string_make_reserve(heap_allocator(), 1024);
+	defer (gb_string_free(passes_str));
+	for_array(i, passes) {
+		if (i != 0) {
+			passes_str = gb_string_appendc(passes_str, ",");
+		}
+		passes_str = gb_string_appendc(passes_str, passes[i]);
+	}
+
+	LLVMErrorRef llvm_err = LLVMRunPasses(wd->m->mod, passes_str, wd->target_machine, pb_options);
+
+	defer (LLVMConsumeError(llvm_err));
+	if (llvm_err != nullptr) {
+		char *llvm_error = LLVMGetErrorMessage(llvm_err);
+		gb_printf_err("LLVM Error:\n%s\n", llvm_error);
+		LLVMDisposeErrorMessage(llvm_error);
+		llvm_error = nullptr;
+
+		if (build_context.keep_temp_files) {
+			TIME_SECTION("LLVM Print Module to File");
+			String filepath_ll = lb_filepath_ll_for_module(wd->m);
+			if (LLVMPrintModuleToFile(wd->m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
+				gb_printf_err("LLVM Error: %s\n", llvm_error);
+			}
+		}
+		gb_exit(1);
+		return 1;
+	}
+#endif
 	return 0;
 	return 0;
 }
 }
 
 
@@ -2035,12 +2115,15 @@ gb_internal bool lb_generate_code(lbGenerator *gen) {
 	// GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
 	// GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
 
 
 	LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
 	LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
+	if (!LB_USE_NEW_PASS_SYSTEM) {
+		build_context.optimization_level = gb_clamp(build_context.optimization_level, -1, 2);
+	}
 	switch (build_context.optimization_level) {
 	switch (build_context.optimization_level) {
-	case 0: code_gen_level = LLVMCodeGenLevelNone;    break;
-	case 1: code_gen_level = LLVMCodeGenLevelLess;    break;
-	case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
-	case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
-	// case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
+	default:/*fallthrough*/
+	case 0: code_gen_level = LLVMCodeGenLevelNone;       break;
+	case 1: code_gen_level = LLVMCodeGenLevelLess;       break;
+	case 2: code_gen_level = LLVMCodeGenLevelDefault;    break;
+	case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
 	}
 	}
 
 
 	// NOTE(bill): Target Machine Creation
 	// NOTE(bill): Target Machine Creation
@@ -2144,10 +2227,16 @@ gb_internal bool lb_generate_code(lbGenerator *gen) {
 
 
 		{ // Add type info data
 		{ // Add type info data
 			isize max_type_info_count = info->minimum_dependency_type_info_set.count+1;
 			isize max_type_info_count = info->minimum_dependency_type_info_set.count+1;
-			// gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
 			Type *t = alloc_type_array(t_type_info, max_type_info_count);
 			Type *t = alloc_type_array(t_type_info, max_type_info_count);
-			LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
-			LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
+
+			// IMPORTANT NOTE(bill): As LLVM does not have a union type, an array of unions cannot be initialized
+			// at compile time without cheating in some way. This means to emulate an array of unions is to use
+			// a giant packed struct of "corrected" data types.
+
+			LLVMTypeRef internal_llvm_type = lb_setup_type_info_data_internal_type(m, max_type_info_count);
+
+			LLVMValueRef g = LLVMAddGlobal(m->mod, internal_llvm_type, LB_TYPE_INFO_DATA_NAME);
+			LLVMSetInitializer(g, LLVMConstNull(internal_llvm_type));
 			LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
 			LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
 
 
 			lbValue value = {};
 			lbValue value = {};
@@ -2156,6 +2245,10 @@ gb_internal bool lb_generate_code(lbGenerator *gen) {
 
 
 			lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
 			lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
 			lb_add_entity(m, lb_global_type_info_data_entity, value);
 			lb_add_entity(m, lb_global_type_info_data_entity, value);
+
+			if (LB_USE_GIANT_PACKED_STRUCT) {
+				lb_make_global_private_const(g);
+			}
 		}
 		}
 		{ // Type info member buffer
 		{ // Type info member buffer
 			// NOTE(bill): Removes need for heap allocation by making it global memory
 			// NOTE(bill): Removes need for heap allocation by making it global memory
@@ -2180,50 +2273,63 @@ gb_internal bool lb_generate_code(lbGenerator *gen) {
 				}
 				}
 			}
 			}
 
 
-			if (count > 0) {
-				{
-					char const *name = LB_TYPE_INFO_TYPES_NAME;
-					Type *t = alloc_type_array(t_type_info_ptr, count);
-					LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
-					LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
-					LLVMSetLinkage(g, LLVMInternalLinkage);
-					lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
-
+			{
+				char const *name = LB_TYPE_INFO_TYPES_NAME;
+				Type *t = alloc_type_array(t_type_info_ptr, count);
+				LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
+				LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
+				LLVMSetLinkage(g, LLVMInternalLinkage);
+				if (LB_USE_GIANT_PACKED_STRUCT) {
+					lb_make_global_private_const(g);
 				}
 				}
-				{
-					char const *name = LB_TYPE_INFO_NAMES_NAME;
-					Type *t = alloc_type_array(t_string, count);
-					LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
-					LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
-					LLVMSetLinkage(g, LLVMInternalLinkage);
-					lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
+				lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
+
+			}
+			{
+				char const *name = LB_TYPE_INFO_NAMES_NAME;
+				Type *t = alloc_type_array(t_string, count);
+				LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
+				LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
+				LLVMSetLinkage(g, LLVMInternalLinkage);
+				if (LB_USE_GIANT_PACKED_STRUCT) {
+					lb_make_global_private_const(g);
 				}
 				}
-				{
-					char const *name = LB_TYPE_INFO_OFFSETS_NAME;
-					Type *t = alloc_type_array(t_uintptr, count);
-					LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
-					LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
-					LLVMSetLinkage(g, LLVMInternalLinkage);
-					lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
+				lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
+			}
+			{
+				char const *name = LB_TYPE_INFO_OFFSETS_NAME;
+				Type *t = alloc_type_array(t_uintptr, count);
+				LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
+				LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
+				LLVMSetLinkage(g, LLVMInternalLinkage);
+				if (LB_USE_GIANT_PACKED_STRUCT) {
+					lb_make_global_private_const(g);
 				}
 				}
+				lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
+			}
 
 
-				{
-					char const *name = LB_TYPE_INFO_USINGS_NAME;
-					Type *t = alloc_type_array(t_bool, count);
-					LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
-					LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
-					LLVMSetLinkage(g, LLVMInternalLinkage);
-					lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
+			{
+				char const *name = LB_TYPE_INFO_USINGS_NAME;
+				Type *t = alloc_type_array(t_bool, count);
+				LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
+				LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
+				LLVMSetLinkage(g, LLVMInternalLinkage);
+				if (LB_USE_GIANT_PACKED_STRUCT) {
+					lb_make_global_private_const(g);
 				}
 				}
+				lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
+			}
 
 
-				{
-					char const *name = LB_TYPE_INFO_TAGS_NAME;
-					Type *t = alloc_type_array(t_string, count);
-					LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
-					LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
-					LLVMSetLinkage(g, LLVMInternalLinkage);
-					lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
+			{
+				char const *name = LB_TYPE_INFO_TAGS_NAME;
+				Type *t = alloc_type_array(t_string, count);
+				LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
+				LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
+				LLVMSetLinkage(g, LLVMInternalLinkage);
+				if (LB_USE_GIANT_PACKED_STRUCT) {
+					lb_make_global_private_const(g);
 				}
 				}
+				lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
 			}
 			}
 		}
 		}
 	}
 	}
@@ -2444,17 +2550,13 @@ gb_internal bool lb_generate_code(lbGenerator *gen) {
 		}
 		}
 	}
 	}
 
 
-
 	TIME_SECTION("LLVM Function Pass");
 	TIME_SECTION("LLVM Function Pass");
 	lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
 	lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
 
 
 	TIME_SECTION("LLVM Module Pass");
 	TIME_SECTION("LLVM Module Pass");
 	lb_llvm_module_passes(gen, do_threading);
 	lb_llvm_module_passes(gen, do_threading);
 
 
-
 	TIME_SECTION("LLVM Module Verification");
 	TIME_SECTION("LLVM Module Verification");
-
-
 	if (!lb_llvm_module_verification(gen, do_threading)) {
 	if (!lb_llvm_module_verification(gen, do_threading)) {
 		return false;
 		return false;
 	}
 	}
@@ -2498,6 +2600,21 @@ gb_internal bool lb_generate_code(lbGenerator *gen) {
 		return false;
 		return false;
 	}
 	}
 
 
+
+	if (build_context.sanitizer_flags & SanitizerFlag_Address) {
+		auto paths = array_make<String>(heap_allocator(), 0, 1);
+		if (build_context.metrics.os == TargetOs_windows) {
+			String path = concatenate_strings(permanent_allocator(), build_context.ODIN_ROOT, str_lit("\\bin\\llvm\\windows\\clang_rt.asan-x86_64.lib"));
+			array_add(&paths, path);
+		}
+		Entity *lib = alloc_entity_library_name(nullptr, make_token_ident("asan_lib"), nullptr, slice_from_array(paths), str_lit("asan_lib"));
+		array_add(&gen->foreign_libraries, lib);
+	}
+	if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
+	}
+	if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
+	}
+
 	gb_sort_array(gen->foreign_libraries.data, gen->foreign_libraries.count, foreign_library_cmp);
 	gb_sort_array(gen->foreign_libraries.data, gen->foreign_libraries.count, foreign_library_cmp);
 
 
 	return true;
 	return true;

+ 29 - 7
src/llvm_backend.hpp

@@ -6,13 +6,7 @@
 #include "llvm-c/Object.h"
 #include "llvm-c/Object.h"
 #include "llvm-c/BitWriter.h"
 #include "llvm-c/BitWriter.h"
 #include "llvm-c/DebugInfo.h"
 #include "llvm-c/DebugInfo.h"
-#include "llvm-c/Transforms/AggressiveInstCombine.h"
-#include "llvm-c/Transforms/InstCombine.h"
-#include "llvm-c/Transforms/IPO.h"
-#include "llvm-c/Transforms/PassManagerBuilder.h"
-#include "llvm-c/Transforms/Scalar.h"
-#include "llvm-c/Transforms/Utils.h"
-#include "llvm-c/Transforms/Vectorize.h"
+#include "llvm-c/Transforms/PassBuilder.h"
 #else
 #else
 #include <llvm-c/Core.h>
 #include <llvm-c/Core.h>
 #include <llvm-c/ExecutionEngine.h>
 #include <llvm-c/ExecutionEngine.h>
@@ -54,6 +48,20 @@
 #define ODIN_LLVM_MINIMUM_VERSION_14 0
 #define ODIN_LLVM_MINIMUM_VERSION_14 0
 #endif
 #endif
 
 
+#if LLVM_VERSION_MAJOR == 15 || LLVM_VERSION_MAJOR == 16
+#error "LLVM versions 15 and 16 are not supported"
+#endif
+
+#if LLVM_VERSION_MAJOR >= 17
+#define LB_USE_NEW_PASS_SYSTEM 1
+#else
+#define LB_USE_NEW_PASS_SYSTEM 0
+#endif
+
+gb_internal bool lb_use_new_pass_system(void) {
+	return LB_USE_NEW_PASS_SYSTEM;
+}
+
 struct lbProcedure;
 struct lbProcedure;
 
 
 struct lbValue {
 struct lbValue {
@@ -123,6 +131,7 @@ enum lbFunctionPassManagerKind {
 	lbFunctionPassManager_minimal,
 	lbFunctionPassManager_minimal,
 	lbFunctionPassManager_size,
 	lbFunctionPassManager_size,
 	lbFunctionPassManager_speed,
 	lbFunctionPassManager_speed,
+	lbFunctionPassManager_aggressive,
 
 
 	lbFunctionPassManager_COUNT
 	lbFunctionPassManager_COUNT
 };
 };
@@ -170,6 +179,8 @@ struct lbModule {
 
 
 	lbProcedure *curr_procedure;
 	lbProcedure *curr_procedure;
 
 
+	LLVMBuilderRef const_dummy_builder;
+
 	LLVMDIBuilderRef debug_builder;
 	LLVMDIBuilderRef debug_builder;
 	LLVMMetadataRef debug_compile_unit;
 	LLVMMetadataRef debug_compile_unit;
 
 
@@ -440,6 +451,7 @@ gb_internal lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Arr
 
 
 
 
 gb_internal lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index);
 gb_internal lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index);
+gb_internal lbValue lb_const_ptr_offset(lbModule *m, lbValue ptr, lbValue index);
 gb_internal lbValue lb_string_elem(lbProcedure *p, lbValue string);
 gb_internal lbValue lb_string_elem(lbProcedure *p, lbValue string);
 gb_internal lbValue lb_string_len(lbProcedure *p, lbValue string);
 gb_internal lbValue lb_string_len(lbProcedure *p, lbValue string);
 gb_internal lbValue lb_cstring_len(lbProcedure *p, lbValue value);
 gb_internal lbValue lb_cstring_len(lbProcedure *p, lbValue value);
@@ -486,6 +498,7 @@ gb_internal lbValue lb_find_value_from_entity(lbModule *m, Entity *e);
 gb_internal void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value);
 gb_internal void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value);
 gb_internal lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value);
 gb_internal lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value);
 gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, String const &procedure, TokenPos const &pos);
 gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, String const &procedure, TokenPos const &pos);
+gb_internal lbValue lb_const_source_code_location_const(lbModule *m, String const &procedure, TokenPos const &pos);
 
 
 gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos);
 gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos);
 
 
@@ -542,6 +555,15 @@ gb_internal LLVMTypeRef OdinLLVMGetVectorElementType(LLVMTypeRef type);
 
 
 gb_internal String lb_filepath_ll_for_module(lbModule *m);
 gb_internal String lb_filepath_ll_for_module(lbModule *m);
 
 
+
+gb_internal LLVMTypeRef llvm_array_type(LLVMTypeRef ElementType, uint64_t ElementCount) {
+#if LB_USE_NEW_PASS_SYSTEM
+	return LLVMArrayType2(ElementType, ElementCount);
+#else
+	return LLVMArrayType(ElementType, cast(unsigned)ElementCount);
+#endif
+}
+
 #define LB_STARTUP_RUNTIME_PROC_NAME   "__$startup_runtime"
 #define LB_STARTUP_RUNTIME_PROC_NAME   "__$startup_runtime"
 #define LB_CLEANUP_RUNTIME_PROC_NAME   "__$cleanup_runtime"
 #define LB_CLEANUP_RUNTIME_PROC_NAME   "__$cleanup_runtime"
 #define LB_STARTUP_TYPE_INFO_PROC_NAME "__$startup_type_info"
 #define LB_STARTUP_TYPE_INFO_PROC_NAME "__$startup_type_info"

+ 12 - 19
src/llvm_backend_const.cpp

@@ -14,17 +14,6 @@ gb_internal bool lb_is_const_or_global(lbValue value) {
 	if (lb_is_const(value)) {
 	if (lb_is_const(value)) {
 		return true;
 		return true;
 	}
 	}
-	// TODO remove use of LLVMGetElementType
-	#if 0
-	if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
-		LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
-		if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
-			return false;
-		}
-		LLVMTypeRef elem = LLVMGetElementType(t);
-		return lb_is_type_kind(elem, LLVMFunctionTypeKind);
-	}
-	#endif
 	return false;
 	return false;
 }
 }
 
 
@@ -75,8 +64,8 @@ gb_internal String lb_get_const_string(lbModule *m, lbValue value) {
 
 
 	unsigned     ptr_indices[1] = {0};
 	unsigned     ptr_indices[1] = {0};
 	unsigned     len_indices[1] = {1};
 	unsigned     len_indices[1] = {1};
-	LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
-	LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
+	LLVMValueRef underlying_ptr = llvm_const_extract_value(m, value.value, ptr_indices, gb_count_of(ptr_indices));
+	LLVMValueRef underlying_len = llvm_const_extract_value(m, value.value, len_indices, gb_count_of(len_indices));
 
 
 	GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
 	GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
 	underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
 	underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
@@ -295,14 +284,12 @@ gb_internal lbValue lb_expr_untyped_const_to_typed(lbModule *m, Ast *expr, Type
 	return lb_const_value(m, t, tv.value);
 	return lb_const_value(m, t, tv.value);
 }
 }
 
 
-gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, String const &procedure, TokenPos const &pos) {
-	lbModule *m = p->module;
-
+gb_internal lbValue lb_const_source_code_location_const(lbModule *m, String const &procedure, TokenPos const &pos) {
 	LLVMValueRef fields[4] = {};
 	LLVMValueRef fields[4] = {};
-	fields[0]/*file*/      = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
+	fields[0]/*file*/      = lb_find_or_add_entity_string(m, get_file_path_string(pos.file_id)).value;
 	fields[1]/*line*/      = lb_const_int(m, t_i32, pos.line).value;
 	fields[1]/*line*/      = lb_const_int(m, t_i32, pos.line).value;
 	fields[2]/*column*/    = lb_const_int(m, t_i32, pos.column).value;
 	fields[2]/*column*/    = lb_const_int(m, t_i32, pos.column).value;
-	fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
+	fields[3]/*procedure*/ = lb_find_or_add_entity_string(m, procedure).value;
 
 
 	lbValue res = {};
 	lbValue res = {};
 	res.value = llvm_const_named_struct(m, t_source_code_location, fields, gb_count_of(fields));
 	res.value = llvm_const_named_struct(m, t_source_code_location, fields, gb_count_of(fields));
@@ -310,6 +297,12 @@ gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, String co
 	return res;
 	return res;
 }
 }
 
 
+
+gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, String const &procedure, TokenPos const &pos) {
+	lbModule *m = p->module;
+	return lb_const_source_code_location_const(m, procedure, pos);
+}
+
 gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, Ast *node) {
 gb_internal lbValue lb_emit_source_code_location_const(lbProcedure *p, Ast *node) {
 	String proc_name = {};
 	String proc_name = {};
 	if (p->entity) {
 	if (p->entity) {
@@ -1096,7 +1089,7 @@ gb_internal lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bo
 								if (is_constant) {
 								if (is_constant) {
 									LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value;
 									LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value;
 									if (LLVMIsConstant(elem_value)) {
 									if (LLVMIsConstant(elem_value)) {
-										values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len);
+										values[index] = llvm_const_insert_value(m, values[index], elem_value, idx_list, idx_list_len);
 									} else {
 									} else {
 										is_constant = false;
 										is_constant = false;
 									}
 									}

+ 1 - 1
src/llvm_backend_expr.cpp

@@ -4292,7 +4292,7 @@ gb_internal lbAddr lb_build_addr_compound_lit(lbProcedure *p, Ast *expr) {
 				unsigned len_index = lb_convert_struct_index(p->module, type, 1);
 				unsigned len_index = lb_convert_struct_index(p->module, type, 1);
 				if (lb_is_const(slice)) {
 				if (lb_is_const(slice)) {
 					unsigned indices[1] = {len_index};
 					unsigned indices[1] = {len_index};
-					count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
+					count.value = llvm_const_extract_value(p->module, slice.value, indices, gb_count_of(indices));
 				} else {
 				} else {
 					count.value = LLVMBuildExtractValue(p->builder, slice.value, len_index, "");
 					count.value = LLVMBuildExtractValue(p->builder, slice.value, len_index, "");
 				}
 				}

+ 55 - 4
src/llvm_backend_general.cpp

@@ -90,6 +90,8 @@ gb_internal void lb_init_module(lbModule *m, Checker *c) {
 	map_init(&m->map_cell_info_map, 0);
 	map_init(&m->map_cell_info_map, 0);
 	map_init(&m->exact_value_compound_literal_addr_map, 1024);
 	map_init(&m->exact_value_compound_literal_addr_map, 1024);
 
 
+	m->const_dummy_builder = LLVMCreateBuilderInContext(m->ctx);
+
 }
 }
 
 
 gb_internal bool lb_init_generator(lbGenerator *gen, Checker *c) {
 gb_internal bool lb_init_generator(lbGenerator *gen, Checker *c) {
@@ -276,11 +278,60 @@ gb_internal lbValue lb_zero(lbModule *m, Type *t) {
 	v.type = t;
 	v.type = t;
 	return v;
 	return v;
 }
 }
+gb_internal LLVMValueRef llvm_const_extract_value(lbModule *m, LLVMValueRef agg, unsigned index) {
+	LLVMValueRef res = agg;
+	GB_ASSERT(LLVMIsConstant(res));
+	res = LLVMBuildExtractValue(m->const_dummy_builder, res, index, "");
+	GB_ASSERT(LLVMIsConstant(res));
+	return res;
+}
+
+gb_internal LLVMValueRef llvm_const_extract_value(lbModule *m, LLVMValueRef agg, unsigned *indices, isize count) {
+	// return LLVMConstExtractValue(value, indices, count);
+	LLVMValueRef res = agg;
+	GB_ASSERT(LLVMIsConstant(res));
+	for (isize i = 0; i < count; i++) {
+		res = LLVMBuildExtractValue(m->const_dummy_builder, res, indices[i], "");
+		GB_ASSERT(LLVMIsConstant(res));
+	}
+	return res;
+}
+
+gb_internal LLVMValueRef llvm_const_insert_value(lbModule *m, LLVMValueRef agg, LLVMValueRef val, unsigned index) {
+	GB_ASSERT(LLVMIsConstant(agg));
+	GB_ASSERT(LLVMIsConstant(val));
+
+	LLVMValueRef extracted_value = val;
+	LLVMValueRef nested = llvm_const_extract_value(m, agg, index);
+	GB_ASSERT(LLVMIsConstant(nested));
+	extracted_value = LLVMBuildInsertValue(m->const_dummy_builder, nested, extracted_value, index, "");
+	GB_ASSERT(LLVMIsConstant(extracted_value));
+	return extracted_value;
+}
+
+
+gb_internal LLVMValueRef llvm_const_insert_value(lbModule *m, LLVMValueRef agg, LLVMValueRef val, unsigned *indices, isize count) {
+	GB_ASSERT(LLVMIsConstant(agg));
+	GB_ASSERT(LLVMIsConstant(val));
+	GB_ASSERT(count > 0);
+
+	LLVMValueRef extracted_value = val;
+	for (isize i = count-1; i >= 0; i--) {
+		LLVMValueRef nested = llvm_const_extract_value(m, agg, indices, i);
+		GB_ASSERT(LLVMIsConstant(nested));
+		extracted_value = LLVMBuildInsertValue(m->const_dummy_builder, nested, extracted_value, indices[i], "");
+	}
+	GB_ASSERT(LLVMIsConstant(extracted_value));
+	return extracted_value;
+}
+
+
+
 
 
 gb_internal LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
 gb_internal LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
 	lbValue v = lb_find_or_add_entity_string(m, str);
 	lbValue v = lb_find_or_add_entity_string(m, str);
 	unsigned indices[1] = {0};
 	unsigned indices[1] = {0};
-	return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
+	return llvm_const_extract_value(m, v.value, indices, gb_count_of(indices));
 }
 }
 
 
 gb_internal bool lb_is_instr_terminating(LLVMValueRef instr) {
 gb_internal bool lb_is_instr_terminating(LLVMValueRef instr) {
@@ -1888,14 +1939,14 @@ gb_internal LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
 
 
 	case Type_Array: {
 	case Type_Array: {
 		m->internal_type_level += 1;
 		m->internal_type_level += 1;
-		LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
+		LLVMTypeRef t = llvm_array_type(lb_type(m, type->Array.elem), type->Array.count);
 		m->internal_type_level -= 1;
 		m->internal_type_level -= 1;
 		return t;
 		return t;
 	}
 	}
 
 
 	case Type_EnumeratedArray: {
 	case Type_EnumeratedArray: {
 		m->internal_type_level += 1;
 		m->internal_type_level += 1;
-		LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
+		LLVMTypeRef t = llvm_array_type(lb_type(m, type->EnumeratedArray.elem), type->EnumeratedArray.count);
 		m->internal_type_level -= 1;
 		m->internal_type_level -= 1;
 		return t;
 		return t;
 	}
 	}
@@ -2129,7 +2180,7 @@ gb_internal LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
 			m->internal_type_level -= 1;
 			m->internal_type_level -= 1;
 			
 			
 			LLVMTypeRef elem = lb_type(m, type->Matrix.elem);
 			LLVMTypeRef elem = lb_type(m, type->Matrix.elem);
-			LLVMTypeRef t = LLVMArrayType(elem, cast(unsigned)elem_count);
+			LLVMTypeRef t = llvm_array_type(elem, elem_count);
 			
 			
 			m->internal_type_level += 1;
 			m->internal_type_level += 1;
 			return t;
 			return t;

+ 12 - 4
src/llvm_backend_opt.cpp

@@ -56,8 +56,7 @@ gb_internal void lb_populate_function_pass_manager_specific(lbModule *m, LLVMPas
 #endif
 #endif
 
 
 gb_internal bool lb_opt_ignore(i32 optimization_level) {
 gb_internal bool lb_opt_ignore(i32 optimization_level) {
-	optimization_level = gb_clamp(optimization_level, -1, 2);
-	return optimization_level == -1;
+	return optimization_level < 0;
 }
 }
 
 
 gb_internal void lb_basic_populate_function_pass_manager(LLVMPassManagerRef fpm, i32 optimization_level) {
 gb_internal void lb_basic_populate_function_pass_manager(LLVMPassManagerRef fpm, i32 optimization_level) {
@@ -65,6 +64,7 @@ gb_internal void lb_basic_populate_function_pass_manager(LLVMPassManagerRef fpm,
 		return;
 		return;
 	}
 	}
 
 
+#if !LB_USE_NEW_PASS_SYSTEM
 	if (false && optimization_level <= 0 && build_context.ODIN_DEBUG) {
 	if (false && optimization_level <= 0 && build_context.ODIN_DEBUG) {
 		LLVMAddMergedLoadStoreMotionPass(fpm);
 		LLVMAddMergedLoadStoreMotionPass(fpm);
 	} else {
 	} else {
@@ -75,6 +75,7 @@ gb_internal void lb_basic_populate_function_pass_manager(LLVMPassManagerRef fpm,
 			LLVMAddEarlyCSEPass(fpm);
 			LLVMAddEarlyCSEPass(fpm);
 		}
 		}
 	}
 	}
+#endif
 }
 }
 
 
 gb_internal void lb_populate_function_pass_manager(lbModule *m, LLVMPassManagerRef fpm, bool ignore_memcpy_pass, i32 optimization_level) {
 gb_internal void lb_populate_function_pass_manager(lbModule *m, LLVMPassManagerRef fpm, bool ignore_memcpy_pass, i32 optimization_level) {
@@ -82,6 +83,7 @@ gb_internal void lb_populate_function_pass_manager(lbModule *m, LLVMPassManagerR
 		return;
 		return;
 	}
 	}
 
 
+#if !LB_USE_NEW_PASS_SYSTEM
 	if (ignore_memcpy_pass) {
 	if (ignore_memcpy_pass) {
 		lb_basic_populate_function_pass_manager(fpm, optimization_level);
 		lb_basic_populate_function_pass_manager(fpm, optimization_level);
 		return;
 		return;
@@ -109,6 +111,7 @@ gb_internal void lb_populate_function_pass_manager(lbModule *m, LLVMPassManagerR
 	LLVMAddEarlyCSEPass(fpm);
 	LLVMAddEarlyCSEPass(fpm);
 	LLVMAddLowerExpectIntrinsicPass(fpm);
 	LLVMAddLowerExpectIntrinsicPass(fpm);
 #endif
 #endif
+#endif
 }
 }
 
 
 gb_internal void lb_populate_function_pass_manager_specific(lbModule *m, LLVMPassManagerRef fpm, i32 optimization_level) {
 gb_internal void lb_populate_function_pass_manager_specific(lbModule *m, LLVMPassManagerRef fpm, i32 optimization_level) {
@@ -116,6 +119,7 @@ gb_internal void lb_populate_function_pass_manager_specific(lbModule *m, LLVMPas
 		return;
 		return;
 	}
 	}
 
 
+#if !LB_USE_NEW_PASS_SYSTEM
 	if (optimization_level <= 0) {
 	if (optimization_level <= 0) {
 		LLVMAddMemCpyOptPass(fpm);
 		LLVMAddMemCpyOptPass(fpm);
 		lb_basic_populate_function_pass_manager(fpm, optimization_level);
 		lb_basic_populate_function_pass_manager(fpm, optimization_level);
@@ -148,9 +152,11 @@ gb_internal void lb_populate_function_pass_manager_specific(lbModule *m, LLVMPas
 	LLVMAddEarlyCSEPass(fpm);
 	LLVMAddEarlyCSEPass(fpm);
 	LLVMAddLowerExpectIntrinsicPass(fpm);
 	LLVMAddLowerExpectIntrinsicPass(fpm);
 #endif
 #endif
+#endif
 }
 }
 
 
 gb_internal void lb_add_function_simplifcation_passes(LLVMPassManagerRef mpm, i32 optimization_level) {
 gb_internal void lb_add_function_simplifcation_passes(LLVMPassManagerRef mpm, i32 optimization_level) {
+#if !LB_USE_NEW_PASS_SYSTEM
 	LLVMAddCFGSimplificationPass(mpm);
 	LLVMAddCFGSimplificationPass(mpm);
 
 
 	LLVMAddJumpThreadingPass(mpm);
 	LLVMAddJumpThreadingPass(mpm);
@@ -183,6 +189,7 @@ gb_internal void lb_add_function_simplifcation_passes(LLVMPassManagerRef mpm, i3
 	LLVMAddLoopRerollPass(mpm);
 	LLVMAddLoopRerollPass(mpm);
 	LLVMAddAggressiveDCEPass(mpm);
 	LLVMAddAggressiveDCEPass(mpm);
 	LLVMAddCFGSimplificationPass(mpm);
 	LLVMAddCFGSimplificationPass(mpm);
+#endif
 }
 }
 
 
 
 
@@ -193,7 +200,7 @@ gb_internal void lb_populate_module_pass_manager(LLVMTargetMachineRef target_mac
 	if (optimization_level <= 0 && build_context.ODIN_DEBUG) {
 	if (optimization_level <= 0 && build_context.ODIN_DEBUG) {
 		return;
 		return;
 	}
 	}
-
+#if !LB_USE_NEW_PASS_SYSTEM
 	LLVMAddAlwaysInlinerPass(mpm);
 	LLVMAddAlwaysInlinerPass(mpm);
 	LLVMAddStripDeadPrototypesPass(mpm);
 	LLVMAddStripDeadPrototypesPass(mpm);
 	LLVMAddAnalysisPasses(target_machine, mpm);
 	LLVMAddAnalysisPasses(target_machine, mpm);
@@ -263,6 +270,7 @@ gb_internal void lb_populate_module_pass_manager(LLVMTargetMachineRef target_mac
 	}
 	}
 
 
 	LLVMAddCFGSimplificationPass(mpm);
 	LLVMAddCFGSimplificationPass(mpm);
+#endif
 }
 }
 
 
 
 
@@ -435,7 +443,7 @@ gb_internal void lb_append_to_compiler_used(lbModule *m, LLVMValueRef func) {
 	}
 	}
 
 
 	LLVMTypeRef Int8PtrTy = LLVMPointerType(LLVMInt8TypeInContext(m->ctx), 0);
 	LLVMTypeRef Int8PtrTy = LLVMPointerType(LLVMInt8TypeInContext(m->ctx), 0);
-	LLVMTypeRef ATy = LLVMArrayType(Int8PtrTy, operands);
+	LLVMTypeRef ATy = llvm_array_type(Int8PtrTy, operands);
 
 
 	constants[operands - 1] = LLVMConstBitCast(func, Int8PtrTy);
 	constants[operands - 1] = LLVMConstBitCast(func, Int8PtrTy);
 	LLVMValueRef initializer = LLVMConstArray(Int8PtrTy, constants, operands);
 	LLVMValueRef initializer = LLVMConstArray(Int8PtrTy, constants, operands);

+ 28 - 4
src/llvm_backend_proc.cpp

@@ -139,7 +139,7 @@ gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool i
 
 
 	lb_ensure_abi_function_type(m, p);
 	lb_ensure_abi_function_type(m, p);
 	lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
 	lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
-	
+
 	if (pt->Proc.diverging) {
 	if (pt->Proc.diverging) {
 		lb_add_attribute_to_proc(m, p->value, "noreturn");
 		lb_add_attribute_to_proc(m, p->value, "noreturn");
 	}
 	}
@@ -152,7 +152,6 @@ gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool i
 		lb_add_attribute_to_proc(m, p->value, "noredzone");
 		lb_add_attribute_to_proc(m, p->value, "noredzone");
 	}
 	}
 
 
-
 	switch (p->inlining) {
 	switch (p->inlining) {
 	case ProcInlining_inline:
 	case ProcInlining_inline:
 		lb_add_attribute_to_proc(m, p->value, "alwaysinline");
 		lb_add_attribute_to_proc(m, p->value, "alwaysinline");
@@ -318,6 +317,18 @@ gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool i
 		}
 		}
 	}
 	}
 
 
+	if (p->body && entity->pkg && ((entity->pkg->kind == Package_Normal) || (entity->pkg->kind == Package_Init))) {
+		if (build_context.sanitizer_flags & SanitizerFlag_Address) {
+			lb_add_attribute_to_proc(m, p->value, "sanitize_address");
+		}
+		if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
+			lb_add_attribute_to_proc(m, p->value, "sanitize_memory");
+		}
+		if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
+			lb_add_attribute_to_proc(m, p->value, "sanitize_thread");
+		}
+	}
+
 	lbValue proc_value = {p->value, p->type};
 	lbValue proc_value = {p->value, p->type};
 	lb_add_entity(m, entity,  proc_value);
 	lb_add_entity(m, entity,  proc_value);
 	lb_add_member(m, p->name, proc_value);
 	lb_add_member(m, p->name, proc_value);
@@ -853,8 +864,21 @@ gb_internal lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue
 			for (unsigned i = 0; i < param_count; i++) {
 			for (unsigned i = 0; i < param_count; i++) {
 				LLVMTypeRef param_type = param_types[i];
 				LLVMTypeRef param_type = param_types[i];
 				LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
 				LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
-				// LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
-				// LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
+				if (LB_USE_NEW_PASS_SYSTEM &&
+				    arg_type != param_type) {
+					LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
+					LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
+					if (arg_kind == param_kind &&
+					    arg_kind == LLVMPointerTypeKind) {
+						// NOTE(bill): LLVM's newer `ptr` only type system seems to fail at times
+						// I don't know why...
+						args[i] = LLVMBuildPointerCast(p->builder, args[i], param_type, "");
+						gb_printf_err("%s\n", LLVMPrintValueToString(args[i]));
+						arg_type = param_type;
+						continue;
+					}
+				}
+
 				GB_ASSERT_MSG(
 				GB_ASSERT_MSG(
 					arg_type == param_type,
 					arg_type == param_type,
 					"Parameter types do not match: %s != %s, argument: %s\n\t%s",
 					"Parameter types do not match: %s != %s, argument: %s\n\t%s",

File diff suppressed because it is too large
+ 915 - 41
src/llvm_backend_type.cpp


+ 13 - 2
src/llvm_backend_utility.cpp

@@ -980,12 +980,12 @@ gb_internal LLVMTypeRef lb_type_padding_filler(lbModule *m, i64 padding, i64 pad
 		
 		
 		GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
 		GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
 		if (len != 1) {
 		if (len != 1) {
-			return LLVMArrayType(elem, cast(unsigned)len);
+			return llvm_array_type(elem, len);
 		} else {
 		} else {
 			return elem;
 			return elem;
 		}
 		}
 	} else {
 	} else {
-		return LLVMArrayType(lb_type(m, t_u8), cast(unsigned)padding);
+		return llvm_array_type(lb_type(m, t_u8), padding);
 	}
 	}
 }
 }
 
 
@@ -1437,6 +1437,17 @@ gb_internal lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue inde
 	return res;
 	return res;
 }
 }
 
 
+gb_internal lbValue lb_const_ptr_offset(lbModule *m, lbValue ptr, lbValue index) {
+	LLVMValueRef indices[1] = {index.value};
+	lbValue res = {};
+	res.type = ptr.type;
+	LLVMTypeRef type = lb_type(m, type_deref(res.type, true));
+
+	GB_ASSERT(lb_is_const(ptr) && lb_is_const(index));
+	res.value = LLVMConstGEP2(type, ptr.value, indices, 1);
+	return res;
+}
+
 gb_internal lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
 gb_internal lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
 	Type *t = s.type;
 	Type *t = s.type;
 	GB_ASSERT(is_type_pointer(t));
 	GB_ASSERT(is_type_pointer(t));

+ 40 - 2
src/main.cpp

@@ -300,6 +300,8 @@ enum BuildFlagKind {
 
 
 	BuildFlag_Tilde,
 	BuildFlag_Tilde,
 
 
+	BuildFlag_Sanitize,
+
 #if defined(GB_SYSTEM_WINDOWS)
 #if defined(GB_SYSTEM_WINDOWS)
 	BuildFlag_IgnoreVsSearch,
 	BuildFlag_IgnoreVsSearch,
 	BuildFlag_ResourceFile,
 	BuildFlag_ResourceFile,
@@ -410,7 +412,6 @@ gb_internal bool parse_build_flags(Array<String> args) {
 	add_flag(&build_flags, BuildFlag_SingleFile,              str_lit("file"),                      BuildFlagParam_None,    Command__does_build | Command__does_check);
 	add_flag(&build_flags, BuildFlag_SingleFile,              str_lit("file"),                      BuildFlagParam_None,    Command__does_build | Command__does_check);
 	add_flag(&build_flags, BuildFlag_OutFile,                 str_lit("out"),                       BuildFlagParam_String,  Command__does_build | Command_test);
 	add_flag(&build_flags, BuildFlag_OutFile,                 str_lit("out"),                       BuildFlagParam_String,  Command__does_build | Command_test);
 	add_flag(&build_flags, BuildFlag_OptimizationMode,        str_lit("o"),                         BuildFlagParam_String,  Command__does_build);
 	add_flag(&build_flags, BuildFlag_OptimizationMode,        str_lit("o"),                         BuildFlagParam_String,  Command__does_build);
-	add_flag(&build_flags, BuildFlag_OptimizationMode,        str_lit("O"),                         BuildFlagParam_String,  Command__does_build);
 	add_flag(&build_flags, BuildFlag_ShowTimings,             str_lit("show-timings"),              BuildFlagParam_None,    Command__does_check);
 	add_flag(&build_flags, BuildFlag_ShowTimings,             str_lit("show-timings"),              BuildFlagParam_None,    Command__does_check);
 	add_flag(&build_flags, BuildFlag_ShowMoreTimings,         str_lit("show-more-timings"),         BuildFlagParam_None,    Command__does_check);
 	add_flag(&build_flags, BuildFlag_ShowMoreTimings,         str_lit("show-more-timings"),         BuildFlagParam_None,    Command__does_check);
 	add_flag(&build_flags, BuildFlag_ExportTimings,           str_lit("export-timings"),            BuildFlagParam_String,  Command__does_check);
 	add_flag(&build_flags, BuildFlag_ExportTimings,           str_lit("export-timings"),            BuildFlagParam_String,  Command__does_check);
@@ -486,6 +487,8 @@ gb_internal bool parse_build_flags(Array<String> args) {
 	add_flag(&build_flags, BuildFlag_Tilde,                   str_lit("tilde"),                     BuildFlagParam_None,    Command__does_build);
 	add_flag(&build_flags, BuildFlag_Tilde,                   str_lit("tilde"),                     BuildFlagParam_None,    Command__does_build);
 #endif
 #endif
 
 
+	add_flag(&build_flags, BuildFlag_Sanitize,                str_lit("sanitize"),                  BuildFlagParam_String,  Command__does_build, true);
+
 #if defined(GB_SYSTEM_WINDOWS)
 #if defined(GB_SYSTEM_WINDOWS)
 	add_flag(&build_flags, BuildFlag_IgnoreVsSearch,          str_lit("ignore-vs-search"),          BuildFlagParam_None,    Command__does_build);
 	add_flag(&build_flags, BuildFlag_IgnoreVsSearch,          str_lit("ignore-vs-search"),          BuildFlagParam_None,    Command__does_build);
 	add_flag(&build_flags, BuildFlag_ResourceFile,            str_lit("resource"),                  BuildFlagParam_String,  Command__does_build);
 	add_flag(&build_flags, BuildFlag_ResourceFile,            str_lit("resource"),                  BuildFlagParam_String,  Command__does_build);
@@ -660,12 +663,18 @@ gb_internal bool parse_build_flags(Array<String> args) {
 							} else if (value.value_string == "speed") {
 							} else if (value.value_string == "speed") {
 								build_context.custom_optimization_level = true;
 								build_context.custom_optimization_level = true;
 								build_context.optimization_level = 2;
 								build_context.optimization_level = 2;
+							} else if (value.value_string == "aggressive" && LB_USE_NEW_PASS_SYSTEM) {
+								build_context.custom_optimization_level = true;
+								build_context.optimization_level = 3;
 							} else {
 							} else {
 								gb_printf_err("Invalid optimization mode for -o:<string>, got %.*s\n", LIT(value.value_string));
 								gb_printf_err("Invalid optimization mode for -o:<string>, got %.*s\n", LIT(value.value_string));
 								gb_printf_err("Valid optimization modes:\n");
 								gb_printf_err("Valid optimization modes:\n");
 								gb_printf_err("\tminimal\n");
 								gb_printf_err("\tminimal\n");
 								gb_printf_err("\tsize\n");
 								gb_printf_err("\tsize\n");
 								gb_printf_err("\tspeed\n");
 								gb_printf_err("\tspeed\n");
+								if (LB_USE_NEW_PASS_SYSTEM) {
+									gb_printf_err("\taggressive\n");
+								}
 								gb_printf_err("\tnone (useful for -debug builds)\n");
 								gb_printf_err("\tnone (useful for -debug builds)\n");
 								bad_flags = true;
 								bad_flags = true;
 							}
 							}
@@ -1194,6 +1203,21 @@ gb_internal bool parse_build_flags(Array<String> args) {
 							build_context.tilde_backend = true;
 							build_context.tilde_backend = true;
 							break;
 							break;
 
 
+						case BuildFlag_Sanitize:
+							GB_ASSERT(value.kind == ExactValue_String);
+
+							if (str_eq_ignore_case(value.value_string, str_lit("address"))) {
+								build_context.sanitizer_flags |= SanitizerFlag_Address;
+							} else if (str_eq_ignore_case(value.value_string, str_lit("memory"))) {
+								build_context.sanitizer_flags |= SanitizerFlag_Memory;
+							} else if (str_eq_ignore_case(value.value_string, str_lit("thread"))) {
+								build_context.sanitizer_flags |= SanitizerFlag_Thread;
+							} else {
+								gb_printf_err("-sanitize:<string> options are 'address', 'memory', and 'thread'\n");
+								bad_flags = true;
+							}
+							break;
+
 					#if defined(GB_SYSTEM_WINDOWS)
 					#if defined(GB_SYSTEM_WINDOWS)
 						case BuildFlag_IgnoreVsSearch: {
 						case BuildFlag_IgnoreVsSearch: {
 							GB_ASSERT(value.kind == ExactValue_Invalid);
 							GB_ASSERT(value.kind == ExactValue_Invalid);
@@ -1649,8 +1673,13 @@ gb_internal void print_show_help(String const arg0, String const &command) {
 
 
 		print_usage_line(1, "-o:<string>");
 		print_usage_line(1, "-o:<string>");
 		print_usage_line(2, "Set the optimization mode for compilation");
 		print_usage_line(2, "Set the optimization mode for compilation");
-		print_usage_line(2, "Accepted values: minimal, size, speed, none");
+		if (LB_USE_NEW_PASS_SYSTEM) {
+			print_usage_line(2, "Accepted values: none, minimal, size, speed, aggressive");
+		} else {
+			print_usage_line(2, "Accepted values: none, minimal, size, speed");
+		}
 		print_usage_line(2, "Example: -o:speed");
 		print_usage_line(2, "Example: -o:speed");
+		print_usage_line(2, "The default is -o:minimal");
 		print_usage_line(0, "");
 		print_usage_line(0, "");
 	}
 	}
 
 
@@ -1929,6 +1958,15 @@ gb_internal void print_show_help(String const arg0, String const &command) {
 
 
 	}
 	}
 
 
+	if (run_or_build) {
+		print_usage_line(1, "-sanitize:<string>");
+		print_usage_line(1, "Enables sanitization analysis");
+		print_usage_line(1, "Options are 'address', 'memory', and 'thread'");
+		print_usage_line(1, "NOTE: This flag can be used multiple times");
+		print_usage_line(0, "");
+
+	}
+
 	if (run_or_build) {
 	if (run_or_build) {
 		#if defined(GB_SYSTEM_WINDOWS)
 		#if defined(GB_SYSTEM_WINDOWS)
 		print_usage_line(1, "-ignore-vs-search");
 		print_usage_line(1, "-ignore-vs-search");

+ 1 - 0
src/parser.hpp

@@ -60,6 +60,7 @@ enum PackageKind {
 	Package_Normal,
 	Package_Normal,
 	Package_Runtime,
 	Package_Runtime,
 	Package_Init,
 	Package_Init,
+	Package_Builtin,
 };
 };
 
 
 struct ImportedFile {
 struct ImportedFile {

Some files were not shown because too many files changed in this diff