Merge pull request #595 from odin-lang/llvm-integration

LLVM C API Integration
This commit is contained in:
gingerBill
2020-03-26 17:41:38 +00:00
committed by GitHub
62 changed files with 22054 additions and 368 deletions

BIN
LLVM-C.dll Normal file

Binary file not shown.

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

Binary file not shown.

View File

@@ -13,12 +13,14 @@ if "%1" == "1" (
)
set compiler_flags= -nologo -Oi -TP -fp:precise -Gm- -MP -FC -EHsc- -GR- -GF
set compiler_defines= -DLLVM_BACKEND_SUPPORT
if %release_mode% EQU 0 ( rem Debug
set compiler_flags=%compiler_flags% -Od -MDd -Z7
rem -DDISPLAY_TIMING
) else ( rem Release
set compiler_flags=%compiler_flags% -O2 -MT -Z7 -DNO_ARRAY_BOUNDS_CHECK
set compiler_flags=%compiler_flags% -O2 -MT -Z7
set compiler_defines=%compiler_defines% -DNO_ARRAY_BOUNDS_CHECK
)
set compiler_warnings= ^
@@ -30,7 +32,8 @@ set compiler_warnings= ^
set compiler_includes=
set libs= ^
kernel32.lib
kernel32.lib ^
bin\llvm\windows\LLVM-C.lib
set linker_flags= -incremental:no -opt:ref -subsystem:console
@@ -40,7 +43,7 @@ if %release_mode% EQU 0 ( rem Debug
set linker_flags=%linker_flags% -debug
)
set compiler_settings=%compiler_includes% %compiler_flags% %compiler_warnings%
set compiler_settings=%compiler_includes% %compiler_flags% %compiler_warnings% %compiler_defines%
set linker_settings=%libs% %linker_flags%
del *.pdb > NUL 2> NUL
@@ -49,6 +52,9 @@ del *.ilk > NUL 2> NUL
cl %compiler_settings% "src\main.cpp" ^
/link %linker_settings% -OUT:%exe_name% ^
&& odin run examples/demo/demo.odin
if %errorlevel% neq 0 (
goto end_of_build
)
del *.obj > NUL 2> NUL

View File

@@ -59,13 +59,13 @@ fprintf :: proc(fd: os.Handle, fmt: string, args: ..any) -> int {
// print* procedures return the number of bytes written
print :: proc(args: ..any) -> int { return fprint(context.stdout, ..args); }
println :: proc(args: ..any) -> int { return fprintln(context.stdout, ..args); }
printf :: proc(fmt: string, args: ..any) -> int { return fprintf(context.stdout, fmt, ..args); }
print :: proc(args: ..any) -> int { return fprint(os.stdout, ..args); }
println :: proc(args: ..any) -> int { return fprintln(os.stdout, ..args); }
printf :: proc(fmt: string, args: ..any) -> int { return fprintf(os.stdout, fmt, ..args); }
eprint :: proc(args: ..any) -> int { return fprint(context.stderr, ..args); }
eprintln :: proc(args: ..any) -> int { return fprintln(context.stderr, ..args); }
eprintf :: proc(fmt: string, args: ..any) -> int { return fprintf(context.stderr, fmt, ..args); }
eprint :: proc(args: ..any) -> int { return fprint(os.stderr, ..args); }
eprintln :: proc(args: ..any) -> int { return fprintln(os.stderr, ..args); }
eprintf :: proc(fmt: string, args: ..any) -> int { return fprintf(os.stderr, fmt, ..args); }
@(deprecated="prefer eprint") print_err :: proc(args: ..any) -> int { return eprint(..args); }

View File

@@ -13,16 +13,26 @@ swap :: proc{swap16, swap32, swap64};
set :: proc "contextless" (data: rawptr, value: byte, len: int) -> rawptr {
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
llvm_memset :: proc(dst: rawptr, val: byte, len: int, align: i32, is_volatile: bool) ---;
when ODIN_USE_LLVM_API {
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memset.p0i8.i32")
memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool = false) ---;
}
} else {
@(link_name="llvm.memset.p0i8.i32")
llvm_memset :: proc(dst: rawptr, val: byte, len: int, align: i32, is_volatile: bool) ---;
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memset.p0i8.i32")
memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---;
}
}
}
llvm_memset(data, value, len, 1, false);
memset(data, value, len);
return data;
}
zero :: inline proc "contextless" (data: rawptr, len: int) -> rawptr {

View File

@@ -201,7 +201,7 @@ stdout := get_std_handle(win32.STD_OUTPUT_HANDLE);
stderr := get_std_handle(win32.STD_ERROR_HANDLE);
get_std_handle :: proc(h: int) -> Handle {
get_std_handle :: proc "contextless" (h: int) -> Handle {
fd := win32.get_std_handle(i32(h));
win32.set_handle_information(fd, win32.HANDLE_FLAG_INHERIT, 0);
return Handle(fd);

View File

@@ -288,9 +288,9 @@ Context :: struct {
assertion_failure_proc: Assertion_Failure_Proc,
logger: Logger,
stdin: os.Handle,
stdout: os.Handle,
stderr: os.Handle,
// stdin: os.Handle,
// stdout: os.Handle,
// stderr: os.Handle,
thread_id: int,
@@ -463,9 +463,9 @@ __init_context :: proc "contextless" (c: ^Context) {
c.logger.procedure = default_logger_proc;
c.logger.data = nil;
c.stdin = os.stdin;
c.stdout = os.stdout;
c.stderr = os.stderr;
// c.stdin = os.stdin;
// c.stdout = os.stdout;
// c.stderr = os.stderr;
}
@builtin
@@ -474,7 +474,7 @@ init_global_temporary_allocator :: proc(data: []byte, backup_allocator := contex
}
default_assertion_failure_proc :: proc(prefix, message: string, loc: Source_Code_Location) {
fd := context.stderr;
fd := os.stderr;
print_caller_location(fd, loc);
os.write_string(fd, " ");
os.write_string(fd, prefix);

View File

@@ -40,12 +40,22 @@ mem_zero :: proc "contextless" (data: rawptr, len: int) -> rawptr {
if len < 0 do return data;
when !#defined(memset) {
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---;
when ODIN_USE_LLVM_API {
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memset.p0i8.i32")
memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool = false) ---;
}
} else {
@(link_name="llvm.memset.p0i8.i32")
memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---;
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memset.p0i8.i32")
memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---;
}
}
}
}
@@ -57,15 +67,25 @@ mem_copy :: proc "contextless" (dst, src: rawptr, len: int) -> rawptr {
if src == nil do return dst;
// NOTE(bill): This _must_ be implemented like C's memmove
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memmove.p0i8.p0i8.i64")
llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
when ODIN_USE_LLVM_API {
when size_of(rawptr) == 8 {
@(link_name="llvm.memmove.p0i8.p0i8.i64")
llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memmove.p0i8.p0i8.i32")
llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---;
}
} else {
@(link_name="llvm.memmove.p0i8.p0i8.i32")
llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
when size_of(rawptr) == 8 {
@(link_name="llvm.memmove.p0i8.p0i8.i64")
llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memmove.p0i8.p0i8.i32")
llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---;
}
}
}
llvm_memmove(dst, src, len, 1, false);
llvm_memmove(dst, src, len);
return dst;
}
@@ -73,15 +93,25 @@ mem_copy_non_overlapping :: proc "contextless" (dst, src: rawptr, len: int) -> r
if src == nil do return dst;
// NOTE(bill): This _must_ be implemented like C's memcpy
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memcpy.p0i8.p0i8.i64")
llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
when ODIN_USE_LLVM_API {
when size_of(rawptr) == 8 {
@(link_name="llvm.memcpy.p0i8.p0i8.i64")
llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memcpy.p0i8.p0i8.i32")
llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---;
}
} else {
@(link_name="llvm.memcpy.p0i8.p0i8.i32")
llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
when size_of(rawptr) == 8 {
@(link_name="llvm.memcpy.p0i8.p0i8.i64")
llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---;
} else {
@(link_name="llvm.memcpy.p0i8.p0i8.i32")
llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---;
}
}
}
llvm_memcpy(dst, src, len, 1, false);
llvm_memcpy(dst, src, len);
return dst;
}

View File

@@ -2,15 +2,15 @@ package runtime
foreign import kernel32 "system:Kernel32.lib"
@private
@(link_name="_tls_index")
_tls_index: u32;
// @private
// @(link_name="_tls_index")
// _tls_index: u32;
@private
@(link_name="_fltused")
_fltused: i32 = 0x9875;
// @private
// @(link_name="_fltused")
// _fltused: i32 = 0x9875;
@(link_name="memcpy")
// @(link_name="memcpy")
memcpy :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
foreign kernel32 {
RtlCopyMemory :: proc "c" (dst, src: rawptr, len: int) ---
@@ -19,7 +19,7 @@ memcpy :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
return dst;
}
@(link_name="memmove")
// @(link_name="memmove")
memmove :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
foreign kernel32 {
RtlMoveMemory :: proc "c" (dst, src: rawptr, len: int) ---
@@ -28,7 +28,7 @@ memmove :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
return dst;
}
@(link_name="memset")
// @(link_name="memset")
memset :: proc "c" (ptr: rawptr, val: i32, len: int) -> rawptr {
foreign kernel32 {
RtlFillMemory :: proc "c" (dst: rawptr, len: int, fill: byte) ---

View File

@@ -1245,7 +1245,7 @@ implicit_selector_expression :: proc() {
switch f {
case .A:
fmt.println("HERE");
fmt.println("HITHER");
case .B:
fmt.println("NEVER");
case .C:
@@ -1742,6 +1742,7 @@ range_statements_with_multiple_return_values :: proc() {
}
}
soa_struct_layout :: proc() {
// IMPORTANT NOTE(bill, 2019-11-03): This feature is subject to be changed/removed
// NOTE(bill): Most likely #soa [N]T

View File

@@ -0,0 +1,7 @@
package demo
import "core:fmt"
main :: proc() {
fmt.println("Hellope!", 123, true, 1.3);
}

View File

@@ -128,6 +128,8 @@ struct BuildContext {
bool cross_compiling;
bool use_subsystem_windows;
bool use_llvm_api;
QueryDataSetSettings query_data_set_settings;
gbAffinity affinity;

View File

@@ -625,6 +625,7 @@ void check_proc_decl(CheckerContext *ctx, Entity *e, DeclInfo *d) {
check_open_scope(ctx, pl->type);
defer (check_close_scope(ctx));
ctx->scope->procedure_entity = e;
Type *decl_type = nullptr;

View File

@@ -5675,7 +5675,7 @@ isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs
c->decl = decl; // will be reset by the 'defer' any way
for_array(k, decl->deps.entries) {
Entity *dep = decl->deps.entries[k].ptr;
add_declaration_dependency(c, dep); // TODO(bill): Should this be here?
add_declaration_dependency(c, dep); // TODO(bill): Should this be here?
}
}
}
@@ -7257,6 +7257,16 @@ ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Type *t
}
Type *pt = base_type(proc_type);
#if 0
if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
init_core_context(c->checker);
GB_ASSERT(t_context != nullptr);
GB_ASSERT(t_context->kind == Type_Named);
add_declaration_dependency(c, t_context->Named.type_name);
}
#endif
if (result_type == nullptr) {
operand->mode = Addressing_NoValue;
} else {
@@ -7680,6 +7690,7 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type
return kind;
}
pl->decl = decl;
check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
}
check_close_scope(&ctx);

View File

@@ -711,6 +711,7 @@ void init_universal(void) {
add_global_string_constant(str_lit("ODIN_ROOT"), bc->ODIN_ROOT);
add_global_constant(str_lit("ODIN_DEBUG"), t_untyped_bool, exact_value_bool(bc->ODIN_DEBUG));
add_global_constant(str_lit("ODIN_DISABLE_ASSERT"), t_untyped_bool, exact_value_bool(bc->ODIN_DISABLE_ASSERT));
add_global_constant(str_lit("ODIN_USE_LLVM_API"), t_untyped_bool, exact_value_bool(bc->use_llvm_api));
// Builtin Procedures
@@ -1627,6 +1628,7 @@ void add_dependency_to_set(Checker *c, Entity *entity) {
if (decl == nullptr) {
return;
}
for_array(i, decl->type_info_deps.entries) {
Type *type = decl->type_info_deps.entries[i].ptr;
add_min_dep_type_info(c, type);
@@ -1672,8 +1674,8 @@ void generate_minimum_dependency_set(Checker *c, Entity *start) {
str_lit("type_table"),
str_lit("__type_info_of"),
str_lit("default_temp_allocator"),
str_lit("default_temp_allocator_init"),
str_lit("default_temp_allocator_destroy"),
// str_lit("default_temp_allocator_init"),
// str_lit("default_temp_allocator_destroy"),
str_lit("default_temp_allocator_proc"),
str_lit("Type_Info"),
@@ -1686,6 +1688,8 @@ void generate_minimum_dependency_set(Checker *c, Entity *start) {
str_lit("udivti3"),
str_lit("memset"),
str_lit("memcpy"),
str_lit("memmove"),
str_lit("memory_compare"),
str_lit("memory_compare_zero"),

View File

@@ -182,6 +182,7 @@ struct Scope {
union {
AstPackage *pkg;
AstFile * file;
Entity * procedure_entity;
};
};
@@ -381,3 +382,5 @@ void destroy_checker_poly_path(CheckerPolyPath *);
void check_poly_path_push(CheckerContext *c, Type *t);
Type *check_poly_path_pop (CheckerContext *c);
void init_core_context(Checker *c);

View File

@@ -1021,8 +1021,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
} else if (is_type_enumerated_array(type)) {
ast_node(cl, CompoundLit, value.value_compound);
Type *index_type = type->EnumeratedArray.elem;
Type *elem_type = type->Array.elem;
Type *elem_type = type->EnumeratedArray.elem;
isize elem_count = cl->elems.count;
if (elem_count == 0) {
ir_write_str_lit(f, "zeroinitializer");

65
src/llvm-c/Analysis.h Normal file
View File

@@ -0,0 +1,65 @@
/*===-- llvm-c/Analysis.h - Analysis 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 libLLVMAnalysis.a, which *|
|* implements various analyses 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_ANALYSIS_H
#define LLVM_C_ANALYSIS_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCAnalysis Analysis
* @ingroup LLVMC
*
* @{
*/
typedef enum {
LLVMAbortProcessAction, /* verifier will print to stderr and abort() */
LLVMPrintMessageAction, /* verifier will print to stderr and return 1 */
LLVMReturnStatusAction /* verifier will just return 1 */
} LLVMVerifierFailureAction;
/* Verifies that a module is valid, taking the specified action if not.
Optionally returns a human-readable description of any invalid constructs.
OutMessage must be disposed with LLVMDisposeMessage. */
LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
char **OutMessage);
/* Verifies that a single function is valid, taking the specified action. Useful
for debugging. */
LLVMBool LLVMVerifyFunction(LLVMValueRef Fn, LLVMVerifierFailureAction Action);
/* Open up a ghostview window that displays the CFG of the current function.
Useful for debugging. */
void LLVMViewFunctionCFG(LLVMValueRef Fn);
void LLVMViewFunctionCFGOnly(LLVMValueRef Fn);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

85
src/llvm-c/BitReader.h Normal file
View File

@@ -0,0 +1,85 @@
/*===-- llvm-c/BitReader.h - BitReader 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 libLLVMBitReader.a, which *|
|* implements input of the LLVM bitcode format. *|
|* *|
|* 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_BITREADER_H
#define LLVM_C_BITREADER_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCBitReader Bit Reader
* @ingroup LLVMC
*
* @{
*/
/* Builds a module from the bitcode in the specified memory buffer, returning a
reference to the module via the OutModule parameter. Returns 0 on success.
Optionally returns a human-readable error message via OutMessage.
This is deprecated. Use LLVMParseBitcode2. */
LLVMBool LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutModule,
char **OutMessage);
/* Builds a module from the bitcode in the specified memory buffer, returning a
reference to the module via the OutModule parameter. Returns 0 on success. */
LLVMBool LLVMParseBitcode2(LLVMMemoryBufferRef MemBuf,
LLVMModuleRef *OutModule);
/* This is deprecated. Use LLVMParseBitcodeInContext2. */
LLVMBool LLVMParseBitcodeInContext(LLVMContextRef ContextRef,
LLVMMemoryBufferRef MemBuf,
LLVMModuleRef *OutModule, char **OutMessage);
LLVMBool LLVMParseBitcodeInContext2(LLVMContextRef ContextRef,
LLVMMemoryBufferRef MemBuf,
LLVMModuleRef *OutModule);
/** Reads a module from the specified path, returning via the OutMP parameter
a module provider which performs lazy deserialization. Returns 0 on success.
Optionally returns a human-readable error message via OutMessage.
This is deprecated. Use LLVMGetBitcodeModuleInContext2. */
LLVMBool LLVMGetBitcodeModuleInContext(LLVMContextRef ContextRef,
LLVMMemoryBufferRef MemBuf,
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. */
LLVMBool LLVMGetBitcodeModuleInContext2(LLVMContextRef ContextRef,
LLVMMemoryBufferRef MemBuf,
LLVMModuleRef *OutM);
/* This is deprecated. Use LLVMGetBitcodeModule2. */
LLVMBool LLVMGetBitcodeModule(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
char **OutMessage);
LLVMBool LLVMGetBitcodeModule2(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

59
src/llvm-c/BitWriter.h Normal file
View File

@@ -0,0 +1,59 @@
/*===-- llvm-c/BitWriter.h - BitWriter 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 libLLVMBitWriter.a, which *|
|* implements output of the LLVM bitcode format. *|
|* *|
|* 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_BITWRITER_H
#define LLVM_C_BITWRITER_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCBitWriter Bit Writer
* @ingroup LLVMC
*
* @{
*/
/*===-- Operations on modules ---------------------------------------------===*/
/** Writes a module to the specified path. Returns 0 on success. */
int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path);
/** Writes a module to an open file descriptor. Returns 0 on success. */
int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose,
int Unbuffered);
/** Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file
descriptor. Returns 0 on success. Closes the Handle. */
int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle);
/** Writes a module to a new memory buffer and returns it. */
LLVMMemoryBufferRef LLVMWriteBitcodeToMemoryBuffer(LLVMModuleRef M);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

75
src/llvm-c/Comdat.h Normal file
View File

@@ -0,0 +1,75 @@
/*===-- llvm-c/Comdat.h - Module Comdat 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 file defines the C interface to COMDAT. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_COMDAT_H
#define LLVM_C_COMDAT_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
LLVMAnyComdatSelectionKind, ///< The linker may choose any COMDAT.
LLVMExactMatchComdatSelectionKind, ///< The data referenced by the COMDAT must
///< be the same.
LLVMLargestComdatSelectionKind, ///< The linker will choose the largest
///< COMDAT.
LLVMNoDuplicatesComdatSelectionKind, ///< No other Module may specify this
///< COMDAT.
LLVMSameSizeComdatSelectionKind ///< The data referenced by the COMDAT must be
///< the same size.
} LLVMComdatSelectionKind;
/**
* Return the Comdat in the module with the specified name. It is created
* if it didn't already exist.
*
* @see llvm::Module::getOrInsertComdat()
*/
LLVMComdatRef LLVMGetOrInsertComdat(LLVMModuleRef M, const char *Name);
/**
* Get the Comdat assigned to the given global object.
*
* @see llvm::GlobalObject::getComdat()
*/
LLVMComdatRef LLVMGetComdat(LLVMValueRef V);
/**
* Assign the Comdat to the given global object.
*
* @see llvm::GlobalObject::setComdat()
*/
void LLVMSetComdat(LLVMValueRef V, LLVMComdatRef C);
/*
* Get the conflict resolution selection kind for the Comdat.
*
* @see llvm::Comdat::getSelectionKind()
*/
LLVMComdatSelectionKind LLVMGetComdatSelectionKind(LLVMComdatRef C);
/*
* Set the conflict resolution selection kind for the Comdat.
*
* @see llvm::Comdat::setSelectionKind()
*/
void LLVMSetComdatSelectionKind(LLVMComdatRef C, LLVMComdatSelectionKind Kind);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,44 @@
/*===- llvm/Config/AsmParsers.def - LLVM Assembly Parsers -------*- 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 file enumerates all of the assembly-language parsers *|
|* supported by this build of LLVM. Clients of this file should define *|
|* the LLVM_ASM_PARSER macro to be a function-like macro with a *|
|* single parameter (the name of the target whose assembly can be *|
|* generated); including this file will then enumerate all of the *|
|* targets with assembly parsers. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_ASM_PARSER
# error Please define the macro LLVM_ASM_PARSER(TargetName)
#endif
LLVM_ASM_PARSER(AArch64)
LLVM_ASM_PARSER(AMDGPU)
LLVM_ASM_PARSER(ARM)
LLVM_ASM_PARSER(BPF)
LLVM_ASM_PARSER(Hexagon)
LLVM_ASM_PARSER(Lanai)
LLVM_ASM_PARSER(Mips)
LLVM_ASM_PARSER(MSP430)
LLVM_ASM_PARSER(PowerPC)
LLVM_ASM_PARSER(RISCV)
LLVM_ASM_PARSER(Sparc)
LLVM_ASM_PARSER(SystemZ)
LLVM_ASM_PARSER(WebAssembly)
LLVM_ASM_PARSER(X86)
LLVM_ASM_PARSER(AVR)
#undef LLVM_ASM_PARSER

View File

@@ -0,0 +1,46 @@
/*===- llvm/Config/AsmPrinters.def - LLVM Assembly Printers -----*- 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 file enumerates all of the assembly-language printers *|
|* supported by this build of LLVM. Clients of this file should define *|
|* the LLVM_ASM_PRINTER macro to be a function-like macro with a *|
|* single parameter (the name of the target whose assembly can be *|
|* generated); including this file will then enumerate all of the *|
|* targets with assembly printers. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_ASM_PRINTER
# error Please define the macro LLVM_ASM_PRINTER(TargetName)
#endif
LLVM_ASM_PRINTER(AArch64)
LLVM_ASM_PRINTER(AMDGPU)
LLVM_ASM_PRINTER(ARM)
LLVM_ASM_PRINTER(BPF)
LLVM_ASM_PRINTER(Hexagon)
LLVM_ASM_PRINTER(Lanai)
LLVM_ASM_PRINTER(Mips)
LLVM_ASM_PRINTER(MSP430)
LLVM_ASM_PRINTER(NVPTX)
LLVM_ASM_PRINTER(PowerPC)
LLVM_ASM_PRINTER(RISCV)
LLVM_ASM_PRINTER(Sparc)
LLVM_ASM_PRINTER(SystemZ)
LLVM_ASM_PRINTER(WebAssembly)
LLVM_ASM_PRINTER(X86)
LLVM_ASM_PRINTER(XCore)
LLVM_ASM_PRINTER(AVR)
#undef LLVM_ASM_PRINTER

View File

@@ -0,0 +1,45 @@
/*===- llvm/Config/Disassemblers.def - LLVM Assembly Parsers ----*- 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 file enumerates all of the assembly-language parsers *|
|* supported by this build of LLVM. Clients of this file should define *|
|* the LLVM_DISASSEMBLER macro to be a function-like macro with a *|
|* single parameter (the name of the target whose assembly can be *|
|* generated); including this file will then enumerate all of the *|
|* targets with assembly parsers. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_DISASSEMBLER
# error Please define the macro LLVM_DISASSEMBLER(TargetName)
#endif
LLVM_DISASSEMBLER(AArch64)
LLVM_DISASSEMBLER(AMDGPU)
LLVM_DISASSEMBLER(ARM)
LLVM_DISASSEMBLER(BPF)
LLVM_DISASSEMBLER(Hexagon)
LLVM_DISASSEMBLER(Lanai)
LLVM_DISASSEMBLER(Mips)
LLVM_DISASSEMBLER(MSP430)
LLVM_DISASSEMBLER(PowerPC)
LLVM_DISASSEMBLER(RISCV)
LLVM_DISASSEMBLER(Sparc)
LLVM_DISASSEMBLER(SystemZ)
LLVM_DISASSEMBLER(WebAssembly)
LLVM_DISASSEMBLER(X86)
LLVM_DISASSEMBLER(XCore)
LLVM_DISASSEMBLER(AVR)
#undef LLVM_DISASSEMBLER

View File

@@ -0,0 +1,45 @@
/*===- llvm/Config/Targets.def - LLVM Target Architectures ------*- 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 file enumerates all of the target architectures supported by *|
|* this build of LLVM. Clients of this file should define the *|
|* LLVM_TARGET macro to be a function-like macro with a single *|
|* parameter (the name of the target); including this file will then *|
|* enumerate all of the targets. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_TARGET
# error Please define the macro LLVM_TARGET(TargetName)
#endif
LLVM_TARGET(AArch64)
LLVM_TARGET(AMDGPU)
LLVM_TARGET(ARM)
LLVM_TARGET(BPF)
LLVM_TARGET(Hexagon)
LLVM_TARGET(Lanai)
LLVM_TARGET(Mips)
LLVM_TARGET(MSP430)
LLVM_TARGET(NVPTX)
LLVM_TARGET(PowerPC)
LLVM_TARGET(RISCV)
LLVM_TARGET(Sparc)
LLVM_TARGET(SystemZ)
LLVM_TARGET(WebAssembly)
LLVM_TARGET(X86)
LLVM_TARGET(XCore)
LLVM_TARGET(AVR)
#undef LLVM_TARGET

View File

@@ -0,0 +1,62 @@
/*===------- llvm/Config/abi-breaking.h - llvm configuration -------*- 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 file controls the C++ ABI break introduced in LLVM public header. */
#ifndef LLVM_ABI_BREAKING_CHECKS_H
#define LLVM_ABI_BREAKING_CHECKS_H
/* Define to enable checks that alter the LLVM C++ ABI */
#define LLVM_ENABLE_ABI_BREAKING_CHECKS 0
/* Define to enable reverse iteration of unordered llvm containers */
#define LLVM_ENABLE_REVERSE_ITERATION 0
/* Allow selectively disabling link-time mismatch checking so that header-only
ADT content from LLVM can be used without linking libSupport. */
#if !LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING
// ABI_BREAKING_CHECKS protection: provides link-time failure when clients build
// mismatch with LLVM
#if defined(_MSC_VER)
// Use pragma with MSVC
#define LLVM_XSTR(s) LLVM_STR(s)
#define LLVM_STR(s) #s
#pragma detect_mismatch("LLVM_ENABLE_ABI_BREAKING_CHECKS", LLVM_XSTR(LLVM_ENABLE_ABI_BREAKING_CHECKS))
#undef LLVM_XSTR
#undef LLVM_STR
#elif defined(_WIN32) || defined(__CYGWIN__) // Win32 w/o #pragma detect_mismatch
// FIXME: Implement checks without weak.
#elif defined(__cplusplus)
#if !(defined(_AIX) && defined(__GNUC__) && !defined(__clang__))
#define LLVM_HIDDEN_VISIBILITY __attribute__ ((visibility("hidden")))
#else
// GCC on AIX does not support visibility attributes. Symbols are not
// exported by default on AIX.
#define LLVM_HIDDEN_VISIBILITY
#endif
namespace llvm {
#if LLVM_ENABLE_ABI_BREAKING_CHECKS
extern int EnableABIBreakingChecks;
LLVM_HIDDEN_VISIBILITY
__attribute__((weak)) int *VerifyEnableABIBreakingChecks =
&EnableABIBreakingChecks;
#else
extern int DisableABIBreakingChecks;
LLVM_HIDDEN_VISIBILITY
__attribute__((weak)) int *VerifyDisableABIBreakingChecks =
&DisableABIBreakingChecks;
#endif
}
#undef LLVM_HIDDEN_VISIBILITY
#endif // _MSC_VER
#endif // LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING
#endif

View File

@@ -0,0 +1,85 @@
/*===------- llvm/Config/llvm-config.h - llvm configuration -------*- 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 file enumerates variables from the LLVM configuration so that they
can be in exported headers and won't override package specific directives.
This is a C header that can be included in the llvm-c headers. */
#ifndef LLVM_CONFIG_H
#define LLVM_CONFIG_H
/* Define if LLVM_ENABLE_DUMP is enabled */
/* #undef LLVM_ENABLE_DUMP */
/* Define if we link Polly to the tools */
/* #undef LINK_POLLY_INTO_TOOLS */
/* Target triple LLVM will generate code for by default */
#define LLVM_DEFAULT_TARGET_TRIPLE "x86_64-pc-windows-msvc"
/* Define if threads enabled */
#define LLVM_ENABLE_THREADS 1
/* Has gcc/MSVC atomic intrinsics */
#define LLVM_HAS_ATOMICS 1
/* Host triple LLVM will be executed on */
#define LLVM_HOST_TRIPLE "x86_64-pc-windows-msvc"
/* LLVM architecture name for the native architecture, if available */
#define LLVM_NATIVE_ARCH X86
/* LLVM name for the native AsmParser init function, if available */
#define LLVM_NATIVE_ASMPARSER LLVMInitializeX86AsmParser
/* LLVM name for the native AsmPrinter init function, if available */
#define LLVM_NATIVE_ASMPRINTER LLVMInitializeX86AsmPrinter
/* LLVM name for the native Disassembler init function, if available */
#define LLVM_NATIVE_DISASSEMBLER LLVMInitializeX86Disassembler
/* LLVM name for the native Target init function, if available */
#define LLVM_NATIVE_TARGET LLVMInitializeX86Target
/* LLVM name for the native TargetInfo init function, if available */
#define LLVM_NATIVE_TARGETINFO LLVMInitializeX86TargetInfo
/* LLVM name for the native target MC init function, if available */
#define LLVM_NATIVE_TARGETMC LLVMInitializeX86TargetMC
/* Define if this is Unixish platform */
/* #undef LLVM_ON_UNIX */
/* Define if we have the Intel JIT API runtime support library */
#define LLVM_USE_INTEL_JITEVENTS 0
/* Define if we have the oprofile JIT-support library */
#define LLVM_USE_OPROFILE 0
/* Define if we have the perf JIT-support library */
#define LLVM_USE_PERF 0
/* Major version of the LLVM API */
#define LLVM_VERSION_MAJOR 9
/* Minor version of the LLVM API */
#define LLVM_VERSION_MINOR 0
/* Patch version of the LLVM API */
#define LLVM_VERSION_PATCH 0
/* LLVM version string */
#define LLVM_VERSION_STRING "9.0.0"
/* Whether LLVM records statistics for use with GetStatistics(),
* PrintStatistics() or PrintStatisticsJSON()
*/
#define LLVM_FORCE_ENABLE_STATS 0
#endif

4079
src/llvm-c/Core.h Normal file

File diff suppressed because it is too large Load Diff

90
src/llvm-c/DataTypes.h Normal file
View File

@@ -0,0 +1,90 @@
/*===-- include/llvm-c/DataTypes.h - Define fixed size types ------*- 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 file contains definitions to figure out the size of _HOST_ data types.*|
|* This file is important because different host OS's define different macros,*|
|* which makes portability tough. This file exports the following *|
|* definitions: *|
|* *|
|* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*|
|* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *|
|* *|
|* No library is required when using these functions. *|
|* *|
|*===----------------------------------------------------------------------===*/
/* Please leave this file C-compatible. */
#ifndef LLVM_C_DATATYPES_H
#define LLVM_C_DATATYPES_H
#ifdef __cplusplus
#include <cmath>
#else
#include <math.h>
#endif
#include <inttypes.h>
#include <stdint.h>
#ifndef _MSC_VER
#if !defined(UINT32_MAX)
# error "The standard header <cstdint> is not C++11 compliant. Must #define "\
"__STDC_LIMIT_MACROS before #including llvm-c/DataTypes.h"
#endif
#if !defined(UINT32_C)
# error "The standard header <cstdint> is not C++11 compliant. Must #define "\
"__STDC_CONSTANT_MACROS before #including llvm-c/DataTypes.h"
#endif
/* Note that <inttypes.h> includes <stdint.h>, if this is a C99 system. */
#include <sys/types.h>
#ifdef _AIX
// GCC is strict about defining large constants: they must have LL modifier.
#undef INT64_MAX
#undef INT64_MIN
#endif
#else /* _MSC_VER */
#ifdef __cplusplus
#include <cstddef>
#include <cstdlib>
#else
#include <stddef.h>
#include <stdlib.h>
#endif
#include <sys/types.h>
#if defined(_WIN64)
typedef signed __int64 ssize_t;
#else
typedef signed int ssize_t;
#endif /* _WIN64 */
#endif /* _MSC_VER */
/* Set defaults for constants which we cannot find. */
#if !defined(INT64_MAX)
# define INT64_MAX 9223372036854775807LL
#endif
#if !defined(INT64_MIN)
# define INT64_MIN ((-INT64_MAX)-1)
#endif
#if !defined(UINT64_MAX)
# define UINT64_MAX 0xffffffffffffffffULL
#endif
#ifndef HUGE_VALF
#define HUGE_VALF (float)HUGE_VAL
#endif
#endif /* LLVM_C_DATATYPES_H */

1315
src/llvm-c/DebugInfo.h Normal file

File diff suppressed because it is too large Load Diff

113
src/llvm-c/Disassembler.h Normal file
View File

@@ -0,0 +1,113 @@
/*===-- llvm-c/Disassembler.h - Disassembler 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 public interface to a disassembler library. *|
|* LLVM provides an implementation of this interface. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_DISASSEMBLER_H
#define LLVM_C_DISASSEMBLER_H
#include "llvm-c/DisassemblerTypes.h"
/**
* @defgroup LLVMCDisassembler Disassembler
* @ingroup LLVMC
*
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif /* !defined(__cplusplus) */
/**
* Create a disassembler for the TripleName. Symbolic disassembly is supported
* by passing a block of information in the DisInfo parameter and specifying the
* TagType and callback functions as described above. These can all be passed
* as NULL. If successful, this returns a disassembler context. If not, it
* returns NULL. This function is equivalent to calling
* LLVMCreateDisasmCPUFeatures() with an empty CPU name and feature set.
*/
LLVMDisasmContextRef LLVMCreateDisasm(const char *TripleName, void *DisInfo,
int TagType, LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp);
/**
* Create a disassembler for the TripleName and a specific CPU. Symbolic
* disassembly is supported by passing a block of information in the DisInfo
* parameter and specifying the TagType and callback functions as described
* above. These can all be passed * as NULL. If successful, this returns a
* disassembler context. If not, it returns NULL. This function is equivalent
* to calling LLVMCreateDisasmCPUFeatures() with an empty feature set.
*/
LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *Triple, const char *CPU,
void *DisInfo, int TagType,
LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp);
/**
* Create a disassembler for the TripleName, a specific CPU and specific feature
* string. Symbolic disassembly is supported by passing a block of information
* in the DisInfo parameter and specifying the TagType and callback functions as
* described above. These can all be passed * as NULL. If successful, this
* returns a disassembler context. If not, it returns NULL.
*/
LLVMDisasmContextRef
LLVMCreateDisasmCPUFeatures(const char *Triple, const char *CPU,
const char *Features, void *DisInfo, int TagType,
LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp);
/**
* Set the disassembler's options. Returns 1 if it can set the Options and 0
* otherwise.
*/
int LLVMSetDisasmOptions(LLVMDisasmContextRef DC, uint64_t Options);
/* The option to produce marked up assembly. */
#define LLVMDisassembler_Option_UseMarkup 1
/* The option to print immediates as hex. */
#define LLVMDisassembler_Option_PrintImmHex 2
/* The option use the other assembler printer variant */
#define LLVMDisassembler_Option_AsmPrinterVariant 4
/* The option to set comment on instructions */
#define LLVMDisassembler_Option_SetInstrComments 8
/* The option to print latency information alongside instructions */
#define LLVMDisassembler_Option_PrintLatency 16
/**
* Dispose of a disassembler context.
*/
void LLVMDisasmDispose(LLVMDisasmContextRef DC);
/**
* Disassemble a single instruction using the disassembler context specified in
* the parameter DC. The bytes of the instruction are specified in the
* parameter Bytes, and contains at least BytesSize number of bytes. The
* instruction is at the address specified by the PC parameter. If a valid
* instruction can be disassembled, its string is returned indirectly in
* OutString whose size is specified in the parameter OutStringSize. This
* function returns the number of bytes in the instruction or zero if there was
* no valid instruction.
*/
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DC, uint8_t *Bytes,
uint64_t BytesSize, uint64_t PC,
char *OutString, size_t OutStringSize);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* !defined(__cplusplus) */
#endif /* LLVM_C_DISASSEMBLER_H */

View File

@@ -0,0 +1,160 @@
/*===-- llvm-c/DisassemblerTypedefs.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 *|
|* *|
|*===----------------------------------------------------------------------===*/
#ifndef LLVM_DISASSEMBLER_TYPES_H
#define LLVM_DISASSEMBLER_TYPES_H
#include "llvm-c/DataTypes.h"
#ifdef __cplusplus
#include <cstddef>
#else
#include <stddef.h>
#endif
/**
* An opaque reference to a disassembler context.
*/
typedef void *LLVMDisasmContextRef;
/**
* The type for the operand information call back function. This is called to
* get the symbolic information for an operand of an instruction. Typically
* this is from the relocation information, symbol table, etc. That block of
* information is saved when the disassembler context is created and passed to
* the call back in the DisInfo parameter. The instruction containing operand
* is at the PC parameter. For some instruction sets, there can be more than
* one operand with symbolic information. To determine the symbolic operand
* 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
* 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.
*/
typedef int (*LLVMOpInfoCallback)(void *DisInfo, uint64_t PC,
uint64_t Offset, uint64_t Size,
int TagType, void *TagBuf);
/**
* The initial support in LLVM MC for the most general form of a relocatable
* expression is "AddSymbol - SubtractSymbol + Offset". For some Darwin targets
* this full form is encoded in the relocation information so that AddSymbol and
* SubtractSymbol can be link edited independent of each other. Many other
* platforms only allow a relocatable expression of the form AddSymbol + Offset
* to be encoded.
*
* The LLVMOpInfoCallback() for the TagType value of 1 uses the struct
* LLVMOpInfo1. The value of the relocatable expression for the operand,
* including any PC adjustment, is passed in to the call back in the Value
* field. The symbolic information about the operand is returned using all
* the fields of the structure with the Offset of the relocatable expression
* returned in the Value field. It is possible that some symbols in the
* relocatable expression were assembly temporary symbols, for example
* "Ldata - LpicBase + constant", and only the Values of the symbols without
* symbol names are present in the relocation information. The VariantKind
* type is one of the Target specific #defines below and is used to print
* operands like "_foo@GOT", ":lower16:_foo", etc.
*/
struct LLVMOpInfoSymbol1 {
uint64_t Present; /* 1 if this symbol is present */
const char *Name; /* symbol name if not NULL */
uint64_t Value; /* symbol value if name is NULL */
};
struct LLVMOpInfo1 {
struct LLVMOpInfoSymbol1 AddSymbol;
struct LLVMOpInfoSymbol1 SubtractSymbol;
uint64_t Value;
uint64_t VariantKind;
};
/**
* The operand VariantKinds for symbolic disassembly.
*/
#define LLVMDisassembler_VariantKind_None 0 /* all targets */
/**
* The ARM target VariantKinds.
*/
#define LLVMDisassembler_VariantKind_ARM_HI16 1 /* :upper16: */
#define LLVMDisassembler_VariantKind_ARM_LO16 2 /* :lower16: */
/**
* The ARM64 target VariantKinds.
*/
#define LLVMDisassembler_VariantKind_ARM64_PAGE 1 /* @page */
#define LLVMDisassembler_VariantKind_ARM64_PAGEOFF 2 /* @pageoff */
#define LLVMDisassembler_VariantKind_ARM64_GOTPAGE 3 /* @gotpage */
#define LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF 4 /* @gotpageoff */
#define LLVMDisassembler_VariantKind_ARM64_TLVP 5 /* @tvlppage */
#define LLVMDisassembler_VariantKind_ARM64_TLVOFF 6 /* @tvlppageoff */
/**
* The type for the symbol lookup function. This may be called by the
* disassembler for things like adding a comment for a PC plus a constant
* offset load instruction to use a symbol name instead of a load address value.
* It is passed the block information is saved when the disassembler context is
* created and the ReferenceValue to look up as a symbol. If no symbol is found
* for the ReferenceValue NULL is returned. The ReferenceType of the
* instruction is passed indirectly as is the PC of the instruction in
* ReferencePC. If the output reference can be determined its type is returned
* indirectly in ReferenceType along with ReferenceName if any, or that is set
* to NULL.
*/
typedef const char *(*LLVMSymbolLookupCallback)(void *DisInfo,
uint64_t ReferenceValue,
uint64_t *ReferenceType,
uint64_t ReferencePC,
const char **ReferenceName);
/**
* The reference types on input and output.
*/
/* No input reference type or no output reference type. */
#define LLVMDisassembler_ReferenceType_InOut_None 0
/* The input reference is from a branch instruction. */
#define LLVMDisassembler_ReferenceType_In_Branch 1
/* The input reference is from a PC relative load instruction. */
#define LLVMDisassembler_ReferenceType_In_PCrel_Load 2
/* The input reference is from an ARM64::ADRP instruction. */
#define LLVMDisassembler_ReferenceType_In_ARM64_ADRP 0x100000001
/* The input reference is from an ARM64::ADDXri instruction. */
#define LLVMDisassembler_ReferenceType_In_ARM64_ADDXri 0x100000002
/* The input reference is from an ARM64::LDRXui instruction. */
#define LLVMDisassembler_ReferenceType_In_ARM64_LDRXui 0x100000003
/* The input reference is from an ARM64::LDRXl instruction. */
#define LLVMDisassembler_ReferenceType_In_ARM64_LDRXl 0x100000004
/* The input reference is from an ARM64::ADR instruction. */
#define LLVMDisassembler_ReferenceType_In_ARM64_ADR 0x100000005
/* The output reference is to as symbol stub. */
#define LLVMDisassembler_ReferenceType_Out_SymbolStub 1
/* The output reference is to a symbol address in a literal pool. */
#define LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr 2
/* The output reference is to a cstring address in a literal pool. */
#define LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr 3
/* The output reference is to a Objective-C CoreFoundation string. */
#define LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref 4
/* The output reference is to a Objective-C message. */
#define LLVMDisassembler_ReferenceType_Out_Objc_Message 5
/* The output reference is to a Objective-C message ref. */
#define LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref 6
/* The output reference is to a Objective-C selector ref. */
#define LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref 7
/* The output reference is to a Objective-C class ref. */
#define LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref 8
/* The output reference is to a C++ symbol name. */
#define LLVMDisassembler_ReferenceType_DeMangled_Name 9
#endif

69
src/llvm-c/Error.h Normal file
View File

@@ -0,0 +1,69 @@
/*===------- llvm-c/Error.h - llvm::Error class 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 file defines the C interface to LLVM's Error class. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_ERROR_H
#define LLVM_C_ERROR_H
#ifdef __cplusplus
extern "C" {
#endif
#define LLVMErrorSuccess 0
/**
* Opaque reference to an error instance. Null serves as the 'success' value.
*/
typedef struct LLVMOpaqueError *LLVMErrorRef;
/**
* Error type identifier.
*/
typedef const void *LLVMErrorTypeId;
/**
* Returns the type id for the given error instance, which must be a failure
* value (i.e. non-null).
*/
LLVMErrorTypeId LLVMGetErrorTypeId(LLVMErrorRef Err);
/**
* Dispose of the given error without handling it. This operation consumes the
* error, and the given LLVMErrorRef value is not usable once this call returns.
* Note: This method *only* needs to be called if the error is not being passed
* to some other consuming operation, e.g. LLVMGetErrorMessage.
*/
void LLVMConsumeError(LLVMErrorRef Err);
/**
* Returns the given string's error message. This operation consumes the error,
* and the given LLVMErrorRef value is not usable once this call returns.
* The caller is responsible for disposing of the string by calling
* LLVMDisposeErrorMessage.
*/
char *LLVMGetErrorMessage(LLVMErrorRef Err);
/**
* Dispose of the given error message.
*/
void LLVMDisposeErrorMessage(char *ErrMsg);
/**
* Returns the type id for llvm StringError.
*/
LLVMErrorTypeId LLVMGetStringErrorTypeId(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,49 @@
/*===-- llvm-c/ErrorHandling.h - Error Handling 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 file defines the C interface to LLVM's error handling mechanism. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_ERROR_HANDLING_H
#define LLVM_C_ERROR_HANDLING_H
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*LLVMFatalErrorHandler)(const char *Reason);
/**
* Install a fatal error handler. By default, if LLVM detects a fatal error, it
* will call exit(1). This may not be appropriate in many contexts. For example,
* doing exit(1) will bypass many crash reporting/tracing system tools. This
* function allows you to install a callback that will be invoked prior to the
* call to exit(1).
*/
void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler);
/**
* Reset the fatal error handler. This resets LLVM's fatal error handling
* behavior to the default.
*/
void LLVMResetFatalErrorHandler(void);
/**
* Enable LLVM's built-in stack trace code. This intercepts the OS's crash
* signals and prints which component of LLVM you were in at the time if the
* crash.
*/
void LLVMEnablePrettyStackTrace(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,200 @@
/*===-- llvm-c/ExecutionEngine.h - ExecutionEngine 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 libLLVMExecutionEngine.o, which *|
|* implements various analyses 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_EXECUTIONENGINE_H
#define LLVM_C_EXECUTIONENGINE_H
#include "llvm-c/Target.h"
#include "llvm-c/TargetMachine.h"
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCExecutionEngine Execution Engine
* @ingroup LLVMC
*
* @{
*/
void LLVMLinkInMCJIT(void);
void LLVMLinkInInterpreter(void);
typedef struct LLVMOpaqueGenericValue *LLVMGenericValueRef;
typedef struct LLVMOpaqueExecutionEngine *LLVMExecutionEngineRef;
typedef struct LLVMOpaqueMCJITMemoryManager *LLVMMCJITMemoryManagerRef;
struct LLVMMCJITCompilerOptions {
unsigned OptLevel;
LLVMCodeModel CodeModel;
LLVMBool NoFramePointerElim;
LLVMBool EnableFastISel;
LLVMMCJITMemoryManagerRef MCJMM;
};
/*===-- Operations on generic values --------------------------------------===*/
LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty,
unsigned long long N,
LLVMBool IsSigned);
LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P);
LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef Ty, double N);
unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef);
unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenVal,
LLVMBool IsSigned);
void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal);
double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal);
void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal);
/*===-- Operations on execution engines -----------------------------------===*/
LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE,
LLVMModuleRef M,
char **OutError);
LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp,
LLVMModuleRef M,
char **OutError);
LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
LLVMModuleRef M,
unsigned OptLevel,
char **OutError);
void LLVMInitializeMCJITCompilerOptions(
struct LLVMMCJITCompilerOptions *Options, size_t SizeOfOptions);
/**
* Create an MCJIT execution engine for a module, with the given options. It is
* the responsibility of the caller to ensure that all fields in Options up to
* the given SizeOfOptions are initialized. It is correct to pass a smaller
* value of SizeOfOptions that omits some fields. The canonical way of using
* this is:
*
* LLVMMCJITCompilerOptions options;
* LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
* ... fill in those options you care about
* LLVMCreateMCJITCompilerForModule(&jit, mod, &options, sizeof(options),
* &error);
*
* Note that this is also correct, though possibly suboptimal:
*
* LLVMCreateMCJITCompilerForModule(&jit, mod, 0, 0, &error);
*/
LLVMBool LLVMCreateMCJITCompilerForModule(
LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M,
struct LLVMMCJITCompilerOptions *Options, size_t SizeOfOptions,
char **OutError);
void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE);
void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE);
void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE);
int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F,
unsigned ArgC, const char * const *ArgV,
const char * const *EnvP);
LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F,
unsigned NumArgs,
LLVMGenericValueRef *Args);
void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F);
void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M);
LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M,
LLVMModuleRef *OutMod, char **OutError);
LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name,
LLVMValueRef *OutFn);
void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE,
LLVMValueRef Fn);
LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE);
LLVMTargetMachineRef
LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE);
void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global,
void* Addr);
void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global);
uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name);
uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name);
/*===-- Operations on memory managers -------------------------------------===*/
typedef uint8_t *(*LLVMMemoryManagerAllocateCodeSectionCallback)(
void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID,
const char *SectionName);
typedef uint8_t *(*LLVMMemoryManagerAllocateDataSectionCallback)(
void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID,
const char *SectionName, LLVMBool IsReadOnly);
typedef LLVMBool (*LLVMMemoryManagerFinalizeMemoryCallback)(
void *Opaque, char **ErrMsg);
typedef void (*LLVMMemoryManagerDestroyCallback)(void *Opaque);
/**
* Create a simple custom MCJIT memory manager. This memory manager can
* intercept allocations in a module-oblivious way. This will return NULL
* if any of the passed functions are NULL.
*
* @param Opaque An opaque client object to pass back to the callbacks.
* @param AllocateCodeSection Allocate a block of memory for executable code.
* @param AllocateDataSection Allocate a block of memory for data.
* @param FinalizeMemory Set page permissions and flush cache. Return 0 on
* success, 1 on error.
*/
LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager(
void *Opaque,
LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection,
LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection,
LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory,
LLVMMemoryManagerDestroyCallback Destroy);
void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM);
/*===-- JIT Event Listener functions -------------------------------------===*/
LLVMJITEventListenerRef LLVMCreateGDBRegistrationListener(void);
LLVMJITEventListenerRef LLVMCreateIntelJITEventListener(void);
LLVMJITEventListenerRef LLVMCreateOProfileJITEventListener(void);
LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

40
src/llvm-c/IRReader.h Normal file
View File

@@ -0,0 +1,40 @@
/*===-- llvm-c/IRReader.h - IR Reader 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 file defines the C interface to the IR Reader. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_IRREADER_H
#define LLVM_C_IRREADER_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Read LLVM IR from a memory buffer and convert it into an in-memory Module
* object. Returns 0 on success.
* Optionally returns a human-readable description of any errors that
* occurred during parsing IR. OutMessage must be disposed with
* LLVMDisposeMessage.
*
* @see llvm::ParseIR()
*/
LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef,
LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM,
char **OutMessage);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,56 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @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);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,68 @@
//===-- 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
#ifdef __cplusplus
extern "C" {
#endif
/**
* @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);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

41
src/llvm-c/Linker.h Normal file
View File

@@ -0,0 +1,41 @@
/*===-- llvm-c/Linker.h - Module Linker 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 file defines the C interface to the module/file/archive linker. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_LINKER_H
#define LLVM_C_LINKER_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/* This enum is provided for backwards-compatibility only. It has no effect. */
typedef enum {
LLVMLinkerDestroySource = 0, /* This is the default behavior. */
LLVMLinkerPreserveSource_Removed = 1 /* This option has been deprecated and
should not be used. */
} LLVMLinkerMode;
/* Links the source module into the destination module. The source module is
* destroyed.
* The return value is true if an error occurred, false otherwise.
* Use the diagnostic handler to get any diagnostic message.
*/
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src);
#ifdef __cplusplus
}
#endif
#endif

233
src/llvm-c/Object.h Normal file
View File

@@ -0,0 +1,233 @@
/*===-- llvm-c/Object.h - Object 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 libLLVMObject.a, which */
/* implements object file reading and writing. */
/* */
/* 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_OBJECT_H
#define LLVM_C_OBJECT_H
#include "llvm-c/Types.h"
#include "Config/llvm-config.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCObject Object file reading and writing
* @ingroup LLVMC
*
* @{
*/
// Opaque type wrappers
typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef;
typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef;
typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef;
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. */
} LLVMBinaryType;
/**
* Create a binary file from the given memory buffer.
*
* The exact type of the binary file will be inferred automatically, and the
* appropriate implementation selected. The context may be NULL except if
* the resulting file is an LLVM IR file.
*
* The memory buffer is not consumed by this function. It is the responsibilty
* of the caller to free it with \c LLVMDisposeMemoryBuffer.
*
* If NULL is returned, the \p ErrorMessage parameter is populated with the
* error's description. It is then the caller's responsibility to free this
* message by calling \c LLVMDisposeMessage.
*
* @see llvm::object::createBinary
*/
LLVMBinaryRef LLVMCreateBinary(LLVMMemoryBufferRef MemBuf,
LLVMContextRef Context,
char **ErrorMessage);
/**
* Dispose of a binary file.
*
* The binary file does not own its backing buffer. It is the responsibilty
* of the caller to free it with \c LLVMDisposeMemoryBuffer.
*/
void LLVMDisposeBinary(LLVMBinaryRef BR);
/**
* Retrieves a copy of the memory buffer associated with this object file.
*
* The returned buffer is merely a shallow copy and does not own the actual
* backing buffer of the binary. Nevertheless, it is the responsibility of the
* caller to free it with \c LLVMDisposeMemoryBuffer.
*
* @see llvm::object::getMemoryBufferRef
*/
LLVMMemoryBufferRef LLVMBinaryCopyMemoryBuffer(LLVMBinaryRef BR);
/**
* Retrieve the specific type of a binary.
*
* @see llvm::object::Binary::getType
*/
LLVMBinaryType LLVMBinaryGetType(LLVMBinaryRef BR);
/*
* For a Mach-O universal binary file, retrieves the object file corresponding
* to the given architecture if it is present as a slice.
*
* If NULL is returned, the \p ErrorMessage parameter is populated with the
* error's description. It is then the caller's responsibility to free this
* message by calling \c LLVMDisposeMessage.
*
* It is the responsiblity of the caller to free the returned object file by
* calling \c LLVMDisposeBinary.
*/
LLVMBinaryRef LLVMMachOUniversalBinaryCopyObjectForArch(LLVMBinaryRef BR,
const char *Arch,
size_t ArchLen,
char **ErrorMessage);
/**
* Retrieve a copy of the section iterator for this object file.
*
* If there are no sections, the result is NULL.
*
* The returned iterator is merely a shallow copy. Nevertheless, it is
* the responsibility of the caller to free it with
* \c LLVMDisposeSectionIterator.
*
* @see llvm::object::sections()
*/
LLVMSectionIteratorRef LLVMObjectFileCopySectionIterator(LLVMBinaryRef BR);
/**
* Returns whether the given section iterator is at the end.
*
* @see llvm::object::section_end
*/
LLVMBool LLVMObjectFileIsSectionIteratorAtEnd(LLVMBinaryRef BR,
LLVMSectionIteratorRef SI);
/**
* Retrieve a copy of the symbol iterator for this object file.
*
* If there are no symbols, the result is NULL.
*
* The returned iterator is merely a shallow copy. Nevertheless, it is
* the responsibility of the caller to free it with
* \c LLVMDisposeSymbolIterator.
*
* @see llvm::object::symbols()
*/
LLVMSymbolIteratorRef LLVMObjectFileCopySymbolIterator(LLVMBinaryRef BR);
/**
* Returns whether the given symbol iterator is at the end.
*
* @see llvm::object::symbol_end
*/
LLVMBool LLVMObjectFileIsSymbolIteratorAtEnd(LLVMBinaryRef BR,
LLVMSymbolIteratorRef SI);
void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI);
void LLVMMoveToNextSection(LLVMSectionIteratorRef SI);
void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect,
LLVMSymbolIteratorRef Sym);
// ObjectFile Symbol iterators
void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI);
void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI);
// SectionRef accessors
const char *LLVMGetSectionName(LLVMSectionIteratorRef SI);
uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI);
const char *LLVMGetSectionContents(LLVMSectionIteratorRef SI);
uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI);
LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI,
LLVMSymbolIteratorRef Sym);
// Section Relocation iterators
LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Section);
void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef RI);
LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section,
LLVMRelocationIteratorRef RI);
void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef RI);
// SymbolRef accessors
const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI);
uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI);
uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI);
// RelocationRef accessors
uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI);
LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI);
uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI);
// NOTE: Caller takes ownership of returned string of the two
// following functions.
const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI);
const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI);
/** Deprecated: Use LLVMBinaryRef instead. */
typedef struct LLVMOpaqueObjectFile *LLVMObjectFileRef;
/** Deprecated: Use LLVMCreateBinary instead. */
LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf);
/** Deprecated: Use LLVMDisposeBinary instead. */
void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile);
/** Deprecated: Use LLVMObjectFileCopySectionIterator instead. */
LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile);
/** Deprecated: Use LLVMObjectFileIsSectionIteratorAtEnd instead. */
LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile,
LLVMSectionIteratorRef SI);
/** Deprecated: Use LLVMObjectFileCopySymbolIterator instead. */
LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile);
/** Deprecated: Use LLVMObjectFileIsSymbolIteratorAtEnd instead. */
LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile,
LLVMSymbolIteratorRef SI);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

172
src/llvm-c/OrcBindings.h Normal file
View File

@@ -0,0 +1,172 @@
/*===----------- 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 "llvm-c/Error.h"
#include "llvm-c/Object.h"
#include "llvm-c/TargetMachine.h"
#ifdef __cplusplus
extern "C" {
#endif
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);
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* LLVM_C_ORCBINDINGS_H */

329
src/llvm-c/Remarks.h Normal file
View File

@@ -0,0 +1,329 @@
/*===-- llvm-c/Remarks.h - Remarks 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 public interface to a remark diagnostics library. *|
|* LLVM provides an implementation of this interface. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_REMARKS_H
#define LLVM_C_REMARKS_H
#include "llvm-c/Types.h"
#ifdef __cplusplus
#include <cstddef>
extern "C" {
#else
#include <stddef.h>
#endif /* !defined(__cplusplus) */
/**
* @defgroup LLVMCREMARKS Remarks
* @ingroup LLVMC
*
* @{
*/
#define REMARKS_API_VERSION 0
/**
* The type of the emitted remark.
*/
enum LLVMRemarkType {
LLVMRemarkTypeUnknown,
LLVMRemarkTypePassed,
LLVMRemarkTypeMissed,
LLVMRemarkTypeAnalysis,
LLVMRemarkTypeAnalysisFPCommute,
LLVMRemarkTypeAnalysisAliasing,
LLVMRemarkTypeFailure
};
/**
* String containing a buffer and a length. The buffer is not guaranteed to be
* zero-terminated.
*
* \since REMARKS_API_VERSION=0
*/
typedef struct LLVMRemarkOpaqueString *LLVMRemarkStringRef;
/**
* Returns the buffer holding the string.
*
* \since REMARKS_API_VERSION=0
*/
extern const char *LLVMRemarkStringGetData(LLVMRemarkStringRef String);
/**
* Returns the size of the string.
*
* \since REMARKS_API_VERSION=0
*/
extern uint32_t LLVMRemarkStringGetLen(LLVMRemarkStringRef String);
/**
* DebugLoc containing File, Line and Column.
*
* \since REMARKS_API_VERSION=0
*/
typedef struct LLVMRemarkOpaqueDebugLoc *LLVMRemarkDebugLocRef;
/**
* Return the path to the source file for a debug location.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkStringRef
LLVMRemarkDebugLocGetSourceFilePath(LLVMRemarkDebugLocRef DL);
/**
* Return the line in the source file for a debug location.
*
* \since REMARKS_API_VERSION=0
*/
extern uint32_t LLVMRemarkDebugLocGetSourceLine(LLVMRemarkDebugLocRef DL);
/**
* Return the column in the source file for a debug location.
*
* \since REMARKS_API_VERSION=0
*/
extern uint32_t LLVMRemarkDebugLocGetSourceColumn(LLVMRemarkDebugLocRef DL);
/**
* Element of the "Args" list. The key might give more information about what
* the semantics of the value are, e.g. "Callee" will tell you that the value
* is a symbol that names a function.
*
* \since REMARKS_API_VERSION=0
*/
typedef struct LLVMRemarkOpaqueArg *LLVMRemarkArgRef;
/**
* Returns the key of an argument. The key defines what the value is, and the
* same key can appear multiple times in the list of arguments.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkStringRef LLVMRemarkArgGetKey(LLVMRemarkArgRef Arg);
/**
* Returns the value of an argument. This is a string that can contain newlines.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkStringRef LLVMRemarkArgGetValue(LLVMRemarkArgRef Arg);
/**
* Returns the debug location that is attached to the value of this argument.
*
* If there is no debug location, the return value will be `NULL`.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkDebugLocRef LLVMRemarkArgGetDebugLoc(LLVMRemarkArgRef Arg);
/**
* A remark emitted by the compiler.
*
* \since REMARKS_API_VERSION=0
*/
typedef struct LLVMRemarkOpaqueEntry *LLVMRemarkEntryRef;
/**
* Free the resources used by the remark entry.
*
* \since REMARKS_API_VERSION=0
*/
extern void LLVMRemarkEntryDispose(LLVMRemarkEntryRef Remark);
/**
* The type of the remark. For example, it can allow users to only keep the
* missed optimizations from the compiler.
*
* \since REMARKS_API_VERSION=0
*/
extern enum LLVMRemarkType LLVMRemarkEntryGetType(LLVMRemarkEntryRef Remark);
/**
* Get the name of the pass that emitted this remark.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkStringRef
LLVMRemarkEntryGetPassName(LLVMRemarkEntryRef Remark);
/**
* Get an identifier of the remark.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkStringRef
LLVMRemarkEntryGetRemarkName(LLVMRemarkEntryRef Remark);
/**
* Get the name of the function being processed when the remark was emitted.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkStringRef
LLVMRemarkEntryGetFunctionName(LLVMRemarkEntryRef Remark);
/**
* Returns the debug location that is attached to this remark.
*
* If there is no debug location, the return value will be `NULL`.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkDebugLocRef
LLVMRemarkEntryGetDebugLoc(LLVMRemarkEntryRef Remark);
/**
* Return the hotness of the remark.
*
* A hotness of `0` means this value is not set.
*
* \since REMARKS_API_VERSION=0
*/
extern uint64_t LLVMRemarkEntryGetHotness(LLVMRemarkEntryRef Remark);
/**
* The number of arguments the remark holds.
*
* \since REMARKS_API_VERSION=0
*/
extern uint32_t LLVMRemarkEntryGetNumArgs(LLVMRemarkEntryRef Remark);
/**
* Get a new iterator to iterate over a remark's argument.
*
* If there are no arguments in \p Remark, the return value will be `NULL`.
*
* The lifetime of the returned value is bound to the lifetime of \p Remark.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkArgRef LLVMRemarkEntryGetFirstArg(LLVMRemarkEntryRef Remark);
/**
* Get the next argument in \p Remark from the position of \p It.
*
* Returns `NULL` if there are no more arguments available.
*
* The lifetime of the returned value is bound to the lifetime of \p Remark.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkArgRef LLVMRemarkEntryGetNextArg(LLVMRemarkArgRef It,
LLVMRemarkEntryRef Remark);
typedef struct LLVMRemarkOpaqueParser *LLVMRemarkParserRef;
/**
* Creates a remark parser that can be used to parse the buffer located in \p
* Buf of size \p Size bytes.
*
* \p Buf cannot be `NULL`.
*
* This function should be paired with LLVMRemarkParserDispose() to avoid
* leaking resources.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkParserRef LLVMRemarkParserCreateYAML(const void *Buf,
uint64_t Size);
/**
* Returns the next remark in the file.
*
* The value pointed to by the return value needs to be disposed using a call to
* LLVMRemarkEntryDispose().
*
* All the entries in the returned value that are of LLVMRemarkStringRef type
* will become invalidated once a call to LLVMRemarkParserDispose is made.
*
* If the parser reaches the end of the buffer, the return value will be `NULL`.
*
* In the case of an error, the return value will be `NULL`, and:
*
* 1) LLVMRemarkParserHasError() will return `1`.
*
* 2) LLVMRemarkParserGetErrorMessage() will return a descriptive error
* message.
*
* An error may occur if:
*
* 1) An argument is invalid.
*
* 2) There is a parsing error. This can occur on things like malformed YAML.
*
* 3) There is a Remark semantic error. This can occur on well-formed files with
* missing or extra fields.
*
* Here is a quick example of the usage:
*
* ```
* LLVMRemarkParserRef Parser = LLVMRemarkParserCreateYAML(Buf, Size);
* LLVMRemarkEntryRef Remark = NULL;
* while ((Remark = LLVMRemarkParserGetNext(Parser))) {
* // use Remark
* LLVMRemarkEntryDispose(Remark); // Release memory.
* }
* bool HasError = LLVMRemarkParserHasError(Parser);
* LLVMRemarkParserDispose(Parser);
* ```
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMRemarkEntryRef LLVMRemarkParserGetNext(LLVMRemarkParserRef Parser);
/**
* Returns `1` if the parser encountered an error while parsing the buffer.
*
* \since REMARKS_API_VERSION=0
*/
extern LLVMBool LLVMRemarkParserHasError(LLVMRemarkParserRef Parser);
/**
* Returns a null-terminated string containing an error message.
*
* In case of no error, the result is `NULL`.
*
* The memory of the string is bound to the lifetime of \p Parser. If
* LLVMRemarkParserDispose() is called, the memory of the string will be
* released.
*
* \since REMARKS_API_VERSION=0
*/
extern const char *LLVMRemarkParserGetErrorMessage(LLVMRemarkParserRef Parser);
/**
* Releases all the resources used by \p Parser.
*
* \since REMARKS_API_VERSION=0
*/
extern void LLVMRemarkParserDispose(LLVMRemarkParserRef Parser);
/**
* Returns the version of the remarks library.
*
* \since REMARKS_API_VERSION=0
*/
extern uint32_t LLVMRemarkVersion(void);
/**
* @} // endgoup LLVMCREMARKS
*/
#ifdef __cplusplus
}
#endif /* !defined(__cplusplus) */
#endif /* LLVM_C_REMARKS_H */

65
src/llvm-c/Support.h Normal file
View File

@@ -0,0 +1,65 @@
/*===-- llvm-c/Support.h - Support 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 file defines the C interface to the LLVM support library. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_SUPPORT_H
#define LLVM_C_SUPPORT_H
#include "llvm-c/DataTypes.h"
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* This function permanently loads the dynamic library at the given path.
* It is safe to call this function multiple times for the same library.
*
* @see sys::DynamicLibrary::LoadLibraryPermanently()
*/
LLVMBool LLVMLoadLibraryPermanently(const char* Filename);
/**
* This function parses the given arguments using the LLVM command line parser.
* Note that the only stable thing about this function is its signature; you
* cannot rely on any particular set of command line arguments being interpreted
* the same way across LLVM versions.
*
* @see llvm::cl::ParseCommandLineOptions()
*/
void LLVMParseCommandLineOptions(int argc, const char *const *argv,
const char *Overview);
/**
* This function will search through all previously loaded dynamic
* libraries for the symbol \p symbolName. If it is found, the address of
* that symbol is returned. If not, null is returned.
*
* @see sys::DynamicLibrary::SearchForAddressOfSymbol()
*/
void *LLVMSearchForAddressOfSymbol(const char *symbolName);
/**
* This functions permanently adds the symbol \p symbolName with the
* value \p symbolValue. These symbols are searched before any
* libraries.
*
* @see sys::DynamicLibrary::AddSymbol()
*/
void LLVMAddSymbol(const char *symbolName, void *symbolValue);
#ifdef __cplusplus
}
#endif
#endif

295
src/llvm-c/Target.h Normal file
View File

@@ -0,0 +1,295 @@
/*===-- llvm-c/Target.h - Target 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 libLLVMTarget.a, which */
/* implements target information. */
/* */
/* 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_TARGET_H
#define LLVM_C_TARGET_H
#include "Types.h"
#include "Config/llvm-config.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTarget Target information
* @ingroup LLVMC
*
* @{
*/
enum LLVMByteOrdering { LLVMBigEndian, LLVMLittleEndian };
typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
typedef struct LLVMOpaqueTargetLibraryInfotData *LLVMTargetLibraryInfoRef;
/* Declare all of the target-initialization functions that are available. */
#define LLVM_TARGET(TargetName) \
void LLVMInitialize##TargetName##TargetInfo(void);
#include "Config/Targets.def"
#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
#define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(void);
#include "Config/Targets.def"
#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
#define LLVM_TARGET(TargetName) \
void LLVMInitialize##TargetName##TargetMC(void);
#include "Config/Targets.def"
#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
/* Declare all of the available assembly printer initialization functions. */
#define LLVM_ASM_PRINTER(TargetName) \
void LLVMInitialize##TargetName##AsmPrinter(void);
#include "Config/AsmPrinters.def"
#undef LLVM_ASM_PRINTER /* Explicit undef to make SWIG happier */
/* Declare all of the available assembly parser initialization functions. */
#define LLVM_ASM_PARSER(TargetName) \
void LLVMInitialize##TargetName##AsmParser(void);
#include "Config/AsmParsers.def"
#undef LLVM_ASM_PARSER /* Explicit undef to make SWIG happier */
/* Declare all of the available disassembler initialization functions. */
#define LLVM_DISASSEMBLER(TargetName) \
void LLVMInitialize##TargetName##Disassembler(void);
#include "Config/Disassemblers.def"
#undef LLVM_DISASSEMBLER /* Explicit undef to make SWIG happier */
/** LLVMInitializeAllTargetInfos - The main program should call this function if
it wants access to all available targets that LLVM is configured to
support. */
static inline void LLVMInitializeAllTargetInfos(void) {
#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
#include "Config/Targets.def"
#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
}
/** LLVMInitializeAllTargets - The main program should call this function if it
wants to link in all available targets that LLVM is configured to
support. */
static inline void LLVMInitializeAllTargets(void) {
#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
#include "Config/Targets.def"
#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
}
/** LLVMInitializeAllTargetMCs - The main program should call this function if
it wants access to all available target MC that LLVM is configured to
support. */
static inline void LLVMInitializeAllTargetMCs(void) {
#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
#include "Config/Targets.def"
#undef LLVM_TARGET /* Explicit undef to make SWIG happier */
}
/** LLVMInitializeAllAsmPrinters - The main program should call this function if
it wants all asm printers that LLVM is configured to support, to make them
available via the TargetRegistry. */
static inline void LLVMInitializeAllAsmPrinters(void) {
#define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter();
#include "Config/AsmPrinters.def"
#undef LLVM_ASM_PRINTER /* Explicit undef to make SWIG happier */
}
/** LLVMInitializeAllAsmParsers - The main program should call this function if
it wants all asm parsers that LLVM is configured to support, to make them
available via the TargetRegistry. */
static inline void LLVMInitializeAllAsmParsers(void) {
#define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser();
#include "Config/AsmParsers.def"
#undef LLVM_ASM_PARSER /* Explicit undef to make SWIG happier */
}
/** LLVMInitializeAllDisassemblers - The main program should call this function
if it wants all disassemblers that LLVM is configured to support, to make
them available via the TargetRegistry. */
static inline void LLVMInitializeAllDisassemblers(void) {
#define LLVM_DISASSEMBLER(TargetName) \
LLVMInitialize##TargetName##Disassembler();
#include "Config/Disassemblers.def"
#undef LLVM_DISASSEMBLER /* Explicit undef to make SWIG happier */
}
/** LLVMInitializeNativeTarget - The main program should call this function to
initialize the native target corresponding to the host. This is useful
for JIT applications to ensure that the target gets linked in correctly. */
static inline LLVMBool LLVMInitializeNativeTarget(void) {
/* If we have a native target, initialize it to ensure it is linked in. */
#ifdef LLVM_NATIVE_TARGET
LLVM_NATIVE_TARGETINFO();
LLVM_NATIVE_TARGET();
LLVM_NATIVE_TARGETMC();
return 0;
#else
return 1;
#endif
}
/** LLVMInitializeNativeTargetAsmParser - The main program should call this
function to initialize the parser for the native target corresponding to the
host. */
static inline LLVMBool LLVMInitializeNativeAsmParser(void) {
#ifdef LLVM_NATIVE_ASMPARSER
LLVM_NATIVE_ASMPARSER();
return 0;
#else
return 1;
#endif
}
/** LLVMInitializeNativeTargetAsmPrinter - The main program should call this
function to initialize the printer for the native target corresponding to
the host. */
static inline LLVMBool LLVMInitializeNativeAsmPrinter(void) {
#ifdef LLVM_NATIVE_ASMPRINTER
LLVM_NATIVE_ASMPRINTER();
return 0;
#else
return 1;
#endif
}
/** LLVMInitializeNativeTargetDisassembler - The main program should call this
function to initialize the disassembler for the native target corresponding
to the host. */
static inline LLVMBool LLVMInitializeNativeDisassembler(void) {
#ifdef LLVM_NATIVE_DISASSEMBLER
LLVM_NATIVE_DISASSEMBLER();
return 0;
#else
return 1;
#endif
}
/*===-- Target Data -------------------------------------------------------===*/
/**
* Obtain the data layout for a module.
*
* @see Module::getDataLayout()
*/
LLVMTargetDataRef LLVMGetModuleDataLayout(LLVMModuleRef M);
/**
* Set the data layout for a module.
*
* @see Module::setDataLayout()
*/
void LLVMSetModuleDataLayout(LLVMModuleRef M, LLVMTargetDataRef DL);
/** Creates target data from a target layout string.
See the constructor llvm::DataLayout::DataLayout. */
LLVMTargetDataRef LLVMCreateTargetData(const char *StringRep);
/** Deallocates a TargetData.
See the destructor llvm::DataLayout::~DataLayout. */
void LLVMDisposeTargetData(LLVMTargetDataRef TD);
/** Adds target library information to a pass manager. This does not take
ownership of the target library info.
See the method llvm::PassManagerBase::add. */
void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,
LLVMPassManagerRef PM);
/** Converts target data to a target layout string. The string must be disposed
with LLVMDisposeMessage.
See the constructor llvm::DataLayout::DataLayout. */
char *LLVMCopyStringRepOfTargetData(LLVMTargetDataRef TD);
/** Returns the byte order of a target, either LLVMBigEndian or
LLVMLittleEndian.
See the method llvm::DataLayout::isLittleEndian. */
enum LLVMByteOrdering LLVMByteOrder(LLVMTargetDataRef TD);
/** Returns the pointer size in bytes for a target.
See the method llvm::DataLayout::getPointerSize. */
unsigned LLVMPointerSize(LLVMTargetDataRef TD);
/** Returns the pointer size in bytes for a target for a specified
address space.
See the method llvm::DataLayout::getPointerSize. */
unsigned LLVMPointerSizeForAS(LLVMTargetDataRef TD, unsigned AS);
/** Returns the integer type that is the same size as a pointer on a target.
See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrType(LLVMTargetDataRef TD);
/** Returns the integer type that is the same size as a pointer on a target.
This version allows the address space to be specified.
See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrTypeForAS(LLVMTargetDataRef TD, unsigned AS);
/** Returns the integer type that is the same size as a pointer on a target.
See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrTypeInContext(LLVMContextRef C, LLVMTargetDataRef TD);
/** Returns the integer type that is the same size as a pointer on a target.
This version allows the address space to be specified.
See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrTypeForASInContext(LLVMContextRef C, LLVMTargetDataRef TD,
unsigned AS);
/** Computes the size of a type in bytes for a target.
See the method llvm::DataLayout::getTypeSizeInBits. */
unsigned long long LLVMSizeOfTypeInBits(LLVMTargetDataRef TD, LLVMTypeRef Ty);
/** Computes the storage size of a type in bytes for a target.
See the method llvm::DataLayout::getTypeStoreSize. */
unsigned long long LLVMStoreSizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
/** Computes the ABI size of a type in bytes for a target.
See the method llvm::DataLayout::getTypeAllocSize. */
unsigned long long LLVMABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
/** Computes the ABI alignment of a type in bytes for a target.
See the method llvm::DataLayout::getTypeABISize. */
unsigned LLVMABIAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
/** Computes the call frame alignment of a type in bytes for a target.
See the method llvm::DataLayout::getTypeABISize. */
unsigned LLVMCallFrameAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
/** Computes the preferred alignment of a type in bytes for a target.
See the method llvm::DataLayout::getTypeABISize. */
unsigned LLVMPreferredAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
/** Computes the preferred alignment of a global variable in bytes for a target.
See the method llvm::DataLayout::getPreferredAlignment. */
unsigned LLVMPreferredAlignmentOfGlobal(LLVMTargetDataRef TD,
LLVMValueRef GlobalVar);
/** Computes the structure element that contains the byte offset for a target.
See the method llvm::StructLayout::getElementContainingOffset. */
unsigned LLVMElementAtOffset(LLVMTargetDataRef TD, LLVMTypeRef StructTy,
unsigned long long Offset);
/** Computes the byte offset of the indexed struct element for a target.
See the method llvm::StructLayout::getElementContainingOffset. */
unsigned long long LLVMOffsetOfElement(LLVMTargetDataRef TD,
LLVMTypeRef StructTy, unsigned Element);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

163
src/llvm-c/TargetMachine.h Normal file
View File

@@ -0,0 +1,163 @@
/*===-- llvm-c/TargetMachine.h - Target Machine 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 the Target and TargetMachine *|
|* classes, which can be used to generate assembly or object files. *|
|* *|
|* 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_TARGETMACHINE_H
#define LLVM_C_TARGETMACHINE_H
#include "llvm-c/Target.h"
#include "llvm-c/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
typedef struct LLVMTarget *LLVMTargetRef;
typedef enum {
LLVMCodeGenLevelNone,
LLVMCodeGenLevelLess,
LLVMCodeGenLevelDefault,
LLVMCodeGenLevelAggressive
} LLVMCodeGenOptLevel;
typedef enum {
LLVMRelocDefault,
LLVMRelocStatic,
LLVMRelocPIC,
LLVMRelocDynamicNoPic,
LLVMRelocROPI,
LLVMRelocRWPI,
LLVMRelocROPI_RWPI
} LLVMRelocMode;
typedef enum {
LLVMCodeModelDefault,
LLVMCodeModelJITDefault,
LLVMCodeModelTiny,
LLVMCodeModelSmall,
LLVMCodeModelKernel,
LLVMCodeModelMedium,
LLVMCodeModelLarge
} LLVMCodeModel;
typedef enum {
LLVMAssemblyFile,
LLVMObjectFile
} LLVMCodeGenFileType;
/** Returns the first llvm::Target in the registered targets list. */
LLVMTargetRef LLVMGetFirstTarget(void);
/** Returns the next llvm::Target given a previous one (or null if there's none) */
LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T);
/*===-- Target ------------------------------------------------------------===*/
/** Finds the target corresponding to the given name and stores it in \p T.
Returns 0 on success. */
LLVMTargetRef LLVMGetTargetFromName(const char *Name);
/** Finds the target corresponding to the given triple and stores it in \p T.
Returns 0 on success. Optionally returns any error in ErrorMessage.
Use LLVMDisposeMessage to dispose the message. */
LLVMBool LLVMGetTargetFromTriple(const char* Triple, LLVMTargetRef *T,
char **ErrorMessage);
/** Returns the name of a target. See llvm::Target::getName */
const char *LLVMGetTargetName(LLVMTargetRef T);
/** Returns the description of a target. See llvm::Target::getDescription */
const char *LLVMGetTargetDescription(LLVMTargetRef T);
/** Returns if the target has a JIT */
LLVMBool LLVMTargetHasJIT(LLVMTargetRef T);
/** Returns if the target has a TargetMachine associated */
LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T);
/** Returns if the target as an ASM backend (required for emitting output) */
LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T);
/*===-- Target Machine ----------------------------------------------------===*/
/** Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine */
LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T,
const char *Triple, const char *CPU, const char *Features,
LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel);
/** Dispose the LLVMTargetMachineRef instance generated by
LLVMCreateTargetMachine. */
void LLVMDisposeTargetMachine(LLVMTargetMachineRef T);
/** Returns the Target used in a TargetMachine */
LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T);
/** Returns the triple used creating this target machine. See
llvm::TargetMachine::getTriple. The result needs to be disposed with
LLVMDisposeMessage. */
char *LLVMGetTargetMachineTriple(LLVMTargetMachineRef T);
/** Returns the cpu used creating this target machine. See
llvm::TargetMachine::getCPU. The result needs to be disposed with
LLVMDisposeMessage. */
char *LLVMGetTargetMachineCPU(LLVMTargetMachineRef T);
/** Returns the feature string used creating this target machine. See
llvm::TargetMachine::getFeatureString. The result needs to be disposed with
LLVMDisposeMessage. */
char *LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T);
/** Create a DataLayout based on the targetMachine. */
LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T);
/** Set the target machine's ASM verbosity. */
void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T,
LLVMBool VerboseAsm);
/** Emits an asm or object file for the given module to the filename. This
wraps several c++ only classes (among them a file stream). Returns any
error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */
LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage);
/** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */
LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M,
LLVMCodeGenFileType codegen, char** ErrorMessage, LLVMMemoryBufferRef *OutMemBuf);
/*===-- Triple ------------------------------------------------------------===*/
/** Get a triple for the host machine as a string. The result needs to be
disposed with LLVMDisposeMessage. */
char* LLVMGetDefaultTargetTriple(void);
/** Normalize a target triple. The result needs to be disposed with
LLVMDisposeMessage. */
char* LLVMNormalizeTargetTriple(const char* triple);
/** Get the host CPU as a string. The result needs to be disposed with
LLVMDisposeMessage. */
char* LLVMGetHostCPUName(void);
/** Get the host CPU's features as a string. The result needs to be disposed
with LLVMDisposeMessage. */
char* LLVMGetHostCPUFeatures(void);
/** Adds the target-specific analysis passes to the pass manager. */
void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,43 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTransformsAggressiveInstCombine Aggressive Instruction Combining transformations
* @ingroup LLVMCTransforms
*
* @{
*/
/** See llvm::createAggressiveInstCombinerPass function. */
void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

View File

@@ -0,0 +1,55 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTransformsCoroutines Coroutine transformations
* @ingroup LLVMCTransforms
*
* @{
*/
/** See llvm::createCoroEarlyPass function. */
void LLVMAddCoroEarlyPass(LLVMPassManagerRef PM);
/** See llvm::createCoroSplitPass function. */
void LLVMAddCoroSplitPass(LLVMPassManagerRef PM);
/** See llvm::createCoroElidePass function. */
void LLVMAddCoroElidePass(LLVMPassManagerRef PM);
/** See llvm::createCoroCleanupPass function. */
void LLVMAddCoroCleanupPass(LLVMPassManagerRef PM);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

View File

@@ -0,0 +1,84 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTransformsIPO Interprocedural transformations
* @ingroup LLVMCTransforms
*
* @{
*/
/** See llvm::createArgumentPromotionPass function. */
void LLVMAddArgumentPromotionPass(LLVMPassManagerRef PM);
/** See llvm::createConstantMergePass function. */
void LLVMAddConstantMergePass(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::createIPConstantPropagationPass function. */
void LLVMAddIPConstantPropagationPass(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);
/** See llvm::createStripDeadPrototypesPass function. */
void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM);
/** See llvm::createStripSymbolsPass function. */
void LLVMAddStripSymbolsPass(LLVMPassManagerRef PM);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

View File

@@ -0,0 +1,43 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTransformsInstCombine Instruction Combining transformations
* @ingroup LLVMCTransforms
*
* @{
*/
/** See llvm::createInstructionCombiningPass function. */
void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

View File

@@ -0,0 +1,90 @@
/*===-- 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/Types.h"
typedef struct LLVMOpaquePassManagerBuilder *LLVMPassManagerBuilderRef;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @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);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,167 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTransformsScalar Scalar transformations
* @ingroup LLVMCTransforms
*
* @{
*/
/** See llvm::createAggressiveDCEPass function. */
void LLVMAddAggressiveDCEPass(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::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::createConstantPropagationPass function. */
void LLVMAddConstantPropagationPass(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::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);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

View File

@@ -0,0 +1,53 @@
/*===-- 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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @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);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

View File

@@ -0,0 +1,50 @@
/*===---------------------------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/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCTransformsVectorize Vectorization transformations
* @ingroup LLVMCTransforms
*
* @{
*/
/** See llvm::createLoopVectorizePass function. */
void LLVMAddLoopVectorizePass(LLVMPassManagerRef PM);
/** See llvm::createSLPVectorizerPass function. */
void LLVMAddSLPVectorizePass(LLVMPassManagerRef PM);
/**
* @}
*/
#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */
#endif

179
src/llvm-c/Types.h Normal file
View File

@@ -0,0 +1,179 @@
/*===-- llvm-c/Support.h - C Interface Types declarations ---------*- 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 file defines types used by the C interface to LLVM. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_TYPES_H
#define LLVM_C_TYPES_H
#include "llvm-c/DataTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup LLVMCSupportTypes Types and Enumerations
*
* @{
*/
typedef int LLVMBool;
/* Opaque types. */
/**
* LLVM uses a polymorphic type hierarchy which C cannot represent, therefore
* parameters must be passed as base types. Despite the declared types, most
* of the functions provided operate only on branches of the type hierarchy.
* The declared parameter names are descriptive and specify which type is
* required. Additionally, each type hierarchy is documented along with the
* functions that operate upon it. For more detail, refer to LLVM's C++ code.
* If in doubt, refer to Core.cpp, which performs parameter downcasts in the
* form unwrap<RequiredType>(Param).
*/
/**
* Used to pass regions of memory through LLVM interfaces.
*
* @see llvm::MemoryBuffer
*/
typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef;
/**
* The top-level container for all LLVM global data. See the LLVMContext class.
*/
typedef struct LLVMOpaqueContext *LLVMContextRef;
/**
* The top-level container for all other LLVM Intermediate Representation (IR)
* objects.
*
* @see llvm::Module
*/
typedef struct LLVMOpaqueModule *LLVMModuleRef;
/**
* Each value in the LLVM IR has a type, an LLVMTypeRef.
*
* @see llvm::Type
*/
typedef struct LLVMOpaqueType *LLVMTypeRef;
/**
* Represents an individual value in LLVM IR.
*
* This models llvm::Value.
*/
typedef struct LLVMOpaqueValue *LLVMValueRef;
/**
* Represents a basic block of instructions in LLVM IR.
*
* This models llvm::BasicBlock.
*/
typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef;
/**
* Represents an LLVM Metadata.
*
* This models llvm::Metadata.
*/
typedef struct LLVMOpaqueMetadata *LLVMMetadataRef;
/**
* Represents an LLVM Named Metadata Node.
*
* This models llvm::NamedMDNode.
*/
typedef struct LLVMOpaqueNamedMDNode *LLVMNamedMDNodeRef;
/**
* Represents an entry in a Global Object's metadata attachments.
*
* This models std::pair<unsigned, MDNode *>
*/
typedef struct LLVMOpaqueValueMetadataEntry LLVMValueMetadataEntry;
/**
* Represents an LLVM basic block builder.
*
* This models llvm::IRBuilder.
*/
typedef struct LLVMOpaqueBuilder *LLVMBuilderRef;
/**
* Represents an LLVM debug info builder.
*
* This models llvm::DIBuilder.
*/
typedef struct LLVMOpaqueDIBuilder *LLVMDIBuilderRef;
/**
* Interface used to provide a module to JIT or interpreter.
* This is now just a synonym for llvm::Module, but we have to keep using the
* different type to keep binary compatibility.
*/
typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef;
/** @see llvm::PassManagerBase */
typedef struct LLVMOpaquePassManager *LLVMPassManagerRef;
/** @see llvm::PassRegistry */
typedef struct LLVMOpaquePassRegistry *LLVMPassRegistryRef;
/**
* Used to get the users and usees of a Value.
*
* @see llvm::Use */
typedef struct LLVMOpaqueUse *LLVMUseRef;
/**
* Used to represent an attributes.
*
* @see llvm::Attribute
*/
typedef struct LLVMOpaqueAttributeRef *LLVMAttributeRef;
/**
* @see llvm::DiagnosticInfo
*/
typedef struct LLVMOpaqueDiagnosticInfo *LLVMDiagnosticInfoRef;
/**
* @see llvm::Comdat
*/
typedef struct LLVMComdat *LLVMComdatRef;
/**
* @see llvm::Module::ModuleFlagEntry
*/
typedef struct LLVMOpaqueModuleFlagEntry LLVMModuleFlagEntry;
/**
* @see llvm::JITEventListener
*/
typedef struct LLVMOpaqueJITEventListener *LLVMJITEventListenerRef;
/**
* @see llvm::object::Binary
*/
typedef struct LLVMOpaqueBinary *LLVMBinaryRef;
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif

899
src/llvm-c/lto.h Normal file
View File

@@ -0,0 +1,899 @@
/*===-- llvm-c/lto.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 public interface to an abstract link time optimization*|
|* library. LLVM provides an implementation of this interface for use with *|
|* llvm bitcode files. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_C_LTO_H
#define LLVM_C_LTO_H
#ifdef __cplusplus
#include <cstddef>
#else
#include <stddef.h>
#endif
#include <sys/types.h>
#ifndef __cplusplus
#if !defined(_MSC_VER)
#include <stdbool.h>
typedef bool lto_bool_t;
#else
/* MSVC in particular does not have anything like _Bool or bool in C, but we can
at least make sure the type is the same size. The implementation side will
use C++ bool. */
typedef unsigned char lto_bool_t;
#endif
#else
typedef bool lto_bool_t;
#endif
/**
* @defgroup LLVMCLTO LTO
* @ingroup LLVMC
*
* @{
*/
#define LTO_API_VERSION 24
/**
* \since prior to LTO_API_VERSION=3
*/
typedef enum {
LTO_SYMBOL_ALIGNMENT_MASK = 0x0000001F, /* log2 of alignment */
LTO_SYMBOL_PERMISSIONS_MASK = 0x000000E0,
LTO_SYMBOL_PERMISSIONS_CODE = 0x000000A0,
LTO_SYMBOL_PERMISSIONS_DATA = 0x000000C0,
LTO_SYMBOL_PERMISSIONS_RODATA = 0x00000080,
LTO_SYMBOL_DEFINITION_MASK = 0x00000700,
LTO_SYMBOL_DEFINITION_REGULAR = 0x00000100,
LTO_SYMBOL_DEFINITION_TENTATIVE = 0x00000200,
LTO_SYMBOL_DEFINITION_WEAK = 0x00000300,
LTO_SYMBOL_DEFINITION_UNDEFINED = 0x00000400,
LTO_SYMBOL_DEFINITION_WEAKUNDEF = 0x00000500,
LTO_SYMBOL_SCOPE_MASK = 0x00003800,
LTO_SYMBOL_SCOPE_INTERNAL = 0x00000800,
LTO_SYMBOL_SCOPE_HIDDEN = 0x00001000,
LTO_SYMBOL_SCOPE_PROTECTED = 0x00002000,
LTO_SYMBOL_SCOPE_DEFAULT = 0x00001800,
LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN = 0x00002800,
LTO_SYMBOL_COMDAT = 0x00004000,
LTO_SYMBOL_ALIAS = 0x00008000
} lto_symbol_attributes;
/**
* \since prior to LTO_API_VERSION=3
*/
typedef enum {
LTO_DEBUG_MODEL_NONE = 0,
LTO_DEBUG_MODEL_DWARF = 1
} lto_debug_model;
/**
* \since prior to LTO_API_VERSION=3
*/
typedef enum {
LTO_CODEGEN_PIC_MODEL_STATIC = 0,
LTO_CODEGEN_PIC_MODEL_DYNAMIC = 1,
LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC = 2,
LTO_CODEGEN_PIC_MODEL_DEFAULT = 3
} lto_codegen_model;
/** opaque reference to a loaded object module */
typedef struct LLVMOpaqueLTOModule *lto_module_t;
/** opaque reference to a code generator */
typedef struct LLVMOpaqueLTOCodeGenerator *lto_code_gen_t;
/** opaque reference to a thin code generator */
typedef struct LLVMOpaqueThinLTOCodeGenerator *thinlto_code_gen_t;
#ifdef __cplusplus
extern "C" {
#endif
/**
* Returns a printable string.
*
* \since prior to LTO_API_VERSION=3
*/
extern const char*
lto_get_version(void);
/**
* Returns the last error string or NULL if last operation was successful.
*
* \since prior to LTO_API_VERSION=3
*/
extern const char*
lto_get_error_message(void);
/**
* Checks if a file is a loadable object file.
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t
lto_module_is_object_file(const char* path);
/**
* Checks if a file is a loadable object compiled for requested target.
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t
lto_module_is_object_file_for_target(const char* path,
const char* target_triple_prefix);
/**
* Return true if \p Buffer contains a bitcode file with ObjC code (category
* or class) in it.
*
* \since LTO_API_VERSION=20
*/
extern lto_bool_t
lto_module_has_objc_category(const void *mem, size_t length);
/**
* Checks if a buffer is a loadable object file.
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t lto_module_is_object_file_in_memory(const void *mem,
size_t length);
/**
* Checks if a buffer is a loadable object compiled for requested target.
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t
lto_module_is_object_file_in_memory_for_target(const void* mem, size_t length,
const char* target_triple_prefix);
/**
* Loads an object file from disk.
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_module_t
lto_module_create(const char* path);
/**
* Loads an object file from memory.
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_module_t
lto_module_create_from_memory(const void* mem, size_t length);
/**
* Loads an object file from memory with an extra path argument.
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=9
*/
extern lto_module_t
lto_module_create_from_memory_with_path(const void* mem, size_t length,
const char *path);
/**
* Loads an object file in its own context.
*
* Loads an object file in its own LLVMContext. This function call is
* thread-safe. However, modules created this way should not be merged into an
* lto_code_gen_t using \a lto_codegen_add_module().
*
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=11
*/
extern lto_module_t
lto_module_create_in_local_context(const void *mem, size_t length,
const char *path);
/**
* Loads an object file in the codegen context.
*
* Loads an object file into the same context as \c cg. The module is safe to
* add using \a lto_codegen_add_module().
*
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=11
*/
extern lto_module_t
lto_module_create_in_codegen_context(const void *mem, size_t length,
const char *path, lto_code_gen_t cg);
/**
* Loads an object file from disk. The seek point of fd is not preserved.
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=5
*/
extern lto_module_t
lto_module_create_from_fd(int fd, const char *path, size_t file_size);
/**
* Loads an object file from disk. The seek point of fd is not preserved.
* Returns NULL on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=5
*/
extern lto_module_t
lto_module_create_from_fd_at_offset(int fd, const char *path, size_t file_size,
size_t map_size, off_t offset);
/**
* Frees all memory internally allocated by the module.
* Upon return the lto_module_t is no longer valid.
*
* \since prior to LTO_API_VERSION=3
*/
extern void
lto_module_dispose(lto_module_t mod);
/**
* Returns triple string which the object module was compiled under.
*
* \since prior to LTO_API_VERSION=3
*/
extern const char*
lto_module_get_target_triple(lto_module_t mod);
/**
* Sets triple string with which the object will be codegened.
*
* \since LTO_API_VERSION=4
*/
extern void
lto_module_set_target_triple(lto_module_t mod, const char *triple);
/**
* Returns the number of symbols in the object module.
*
* \since prior to LTO_API_VERSION=3
*/
extern unsigned int
lto_module_get_num_symbols(lto_module_t mod);
/**
* Returns the name of the ith symbol in the object module.
*
* \since prior to LTO_API_VERSION=3
*/
extern const char*
lto_module_get_symbol_name(lto_module_t mod, unsigned int index);
/**
* Returns the attributes of the ith symbol in the object module.
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_symbol_attributes
lto_module_get_symbol_attribute(lto_module_t mod, unsigned int index);
/**
* Returns the module's linker options.
*
* The linker options may consist of multiple flags. It is the linker's
* responsibility to split the flags using a platform-specific mechanism.
*
* \since LTO_API_VERSION=16
*/
extern const char*
lto_module_get_linkeropts(lto_module_t mod);
/**
* Diagnostic severity.
*
* \since LTO_API_VERSION=7
*/
typedef enum {
LTO_DS_ERROR = 0,
LTO_DS_WARNING = 1,
LTO_DS_REMARK = 3, // Added in LTO_API_VERSION=10.
LTO_DS_NOTE = 2
} lto_codegen_diagnostic_severity_t;
/**
* Diagnostic handler type.
* \p severity defines the severity.
* \p diag is the actual diagnostic.
* The diagnostic is not prefixed by any of severity keyword, e.g., 'error: '.
* \p ctxt is used to pass the context set with the diagnostic handler.
*
* \since LTO_API_VERSION=7
*/
typedef void (*lto_diagnostic_handler_t)(
lto_codegen_diagnostic_severity_t severity, const char *diag, void *ctxt);
/**
* Set a diagnostic handler and the related context (void *).
* This is more general than lto_get_error_message, as the diagnostic handler
* can be called at anytime within lto.
*
* \since LTO_API_VERSION=7
*/
extern void lto_codegen_set_diagnostic_handler(lto_code_gen_t,
lto_diagnostic_handler_t,
void *);
/**
* Instantiates a code generator.
* Returns NULL on error (check lto_get_error_message() for details).
*
* All modules added using \a lto_codegen_add_module() must have been created
* in the same context as the codegen.
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_code_gen_t
lto_codegen_create(void);
/**
* Instantiate a code generator in its own context.
*
* Instantiates a code generator in its own context. Modules added via \a
* lto_codegen_add_module() must have all been created in the same context,
* using \a lto_module_create_in_codegen_context().
*
* \since LTO_API_VERSION=11
*/
extern lto_code_gen_t
lto_codegen_create_in_local_context(void);
/**
* Frees all code generator and all memory it internally allocated.
* Upon return the lto_code_gen_t is no longer valid.
*
* \since prior to LTO_API_VERSION=3
*/
extern void
lto_codegen_dispose(lto_code_gen_t);
/**
* Add an object module to the set of modules for which code will be generated.
* Returns true on error (check lto_get_error_message() for details).
*
* \c cg and \c mod must both be in the same context. See \a
* lto_codegen_create_in_local_context() and \a
* lto_module_create_in_codegen_context().
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t
lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod);
/**
* Sets the object module for code generation. This will transfer the ownership
* of the module to the code generator.
*
* \c cg and \c mod must both be in the same context.
*
* \since LTO_API_VERSION=13
*/
extern void
lto_codegen_set_module(lto_code_gen_t cg, lto_module_t mod);
/**
* Sets if debug info should be generated.
* Returns true on error (check lto_get_error_message() for details).
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t
lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model);
/**
* Sets which PIC code model to generated.
* Returns true on error (check lto_get_error_message() for details).
*
* \since prior to LTO_API_VERSION=3
*/
extern lto_bool_t
lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model);
/**
* Sets the cpu to generate code for.
*
* \since LTO_API_VERSION=4
*/
extern void
lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu);
/**
* Sets the location of the assembler tool to run. If not set, libLTO
* will use gcc to invoke the assembler.
*
* \since LTO_API_VERSION=3
*/
extern void
lto_codegen_set_assembler_path(lto_code_gen_t cg, const char* path);
/**
* Sets extra arguments that libLTO should pass to the assembler.
*
* \since LTO_API_VERSION=4
*/
extern void
lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
int nargs);
/**
* Adds to a list of all global symbols that must exist in the final generated
* code. If a function is not listed there, it might be inlined into every usage
* and optimized away.
*
* \since prior to LTO_API_VERSION=3
*/
extern void
lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol);
/**
* Writes a new object file at the specified path that contains the
* merged contents of all modules added so far.
* Returns true on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=5
*/
extern lto_bool_t
lto_codegen_write_merged_modules(lto_code_gen_t cg, const char* path);
/**
* Generates code for all added modules into one native object file.
* This calls lto_codegen_optimize then lto_codegen_compile_optimized.
*
* On success returns a pointer to a generated mach-o/ELF buffer and
* length set to the buffer size. The buffer is owned by the
* lto_code_gen_t and will be freed when lto_codegen_dispose()
* is called, or lto_codegen_compile() is called again.
* On failure, returns NULL (check lto_get_error_message() for details).
*
* \since prior to LTO_API_VERSION=3
*/
extern const void*
lto_codegen_compile(lto_code_gen_t cg, size_t* length);
/**
* Generates code for all added modules into one native object file.
* This calls lto_codegen_optimize then lto_codegen_compile_optimized (instead
* of returning a generated mach-o/ELF buffer, it writes to a file).
*
* The name of the file is written to name. Returns true on error.
*
* \since LTO_API_VERSION=5
*/
extern lto_bool_t
lto_codegen_compile_to_file(lto_code_gen_t cg, const char** name);
/**
* Runs optimization for the merged module. Returns true on error.
*
* \since LTO_API_VERSION=12
*/
extern lto_bool_t
lto_codegen_optimize(lto_code_gen_t cg);
/**
* Generates code for the optimized merged module into one native object file.
* It will not run any IR optimizations on the merged module.
*
* On success returns a pointer to a generated mach-o/ELF buffer and length set
* to the buffer size. The buffer is owned by the lto_code_gen_t and will be
* freed when lto_codegen_dispose() is called, or
* lto_codegen_compile_optimized() is called again. On failure, returns NULL
* (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=12
*/
extern const void*
lto_codegen_compile_optimized(lto_code_gen_t cg, size_t* length);
/**
* Returns the runtime API version.
*
* \since LTO_API_VERSION=12
*/
extern unsigned int
lto_api_version(void);
/**
* Sets options to help debug codegen bugs.
*
* \since prior to LTO_API_VERSION=3
*/
extern void
lto_codegen_debug_options(lto_code_gen_t cg, const char *);
/**
* Initializes LLVM disassemblers.
* FIXME: This doesn't really belong here.
*
* \since LTO_API_VERSION=5
*/
extern void
lto_initialize_disassembler(void);
/**
* Sets if we should run internalize pass during optimization and code
* generation.
*
* \since LTO_API_VERSION=14
*/
extern void
lto_codegen_set_should_internalize(lto_code_gen_t cg,
lto_bool_t ShouldInternalize);
/**
* Set whether to embed uselists in bitcode.
*
* Sets whether \a lto_codegen_write_merged_modules() should embed uselists in
* output bitcode. This should be turned on for all -save-temps output.
*
* \since LTO_API_VERSION=15
*/
extern void
lto_codegen_set_should_embed_uselists(lto_code_gen_t cg,
lto_bool_t ShouldEmbedUselists);
/**
* @} // endgoup LLVMCLTO
* @defgroup LLVMCTLTO ThinLTO
* @ingroup LLVMC
*
* @{
*/
/**
* Type to wrap a single object returned by ThinLTO.
*
* \since LTO_API_VERSION=18
*/
typedef struct {
const char *Buffer;
size_t Size;
} LTOObjectBuffer;
/**
* Instantiates a ThinLTO code generator.
* Returns NULL on error (check lto_get_error_message() for details).
*
*
* The ThinLTOCodeGenerator is not intended to be reuse for multiple
* compilation: the model is that the client adds modules to the generator and
* ask to perform the ThinLTO optimizations / codegen, and finally destroys the
* codegenerator.
*
* \since LTO_API_VERSION=18
*/
extern thinlto_code_gen_t thinlto_create_codegen(void);
/**
* Frees the generator and all memory it internally allocated.
* Upon return the thinlto_code_gen_t is no longer valid.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_dispose(thinlto_code_gen_t cg);
/**
* Add a module to a ThinLTO code generator. Identifier has to be unique among
* all the modules in a code generator. The data buffer stays owned by the
* client, and is expected to be available for the entire lifetime of the
* thinlto_code_gen_t it is added to.
*
* On failure, returns NULL (check lto_get_error_message() for details).
*
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_add_module(thinlto_code_gen_t cg,
const char *identifier, const char *data,
int length);
/**
* Optimize and codegen all the modules added to the codegenerator using
* ThinLTO. Resulting objects are accessible using thinlto_module_get_object().
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_process(thinlto_code_gen_t cg);
/**
* Returns the number of object files produced by the ThinLTO CodeGenerator.
*
* It usually matches the number of input files, but this is not a guarantee of
* the API and may change in future implementation, so the client should not
* assume it.
*
* \since LTO_API_VERSION=18
*/
extern unsigned int thinlto_module_get_num_objects(thinlto_code_gen_t cg);
/**
* Returns a reference to the ith object file produced by the ThinLTO
* CodeGenerator.
*
* Client should use \p thinlto_module_get_num_objects() to get the number of
* available objects.
*
* \since LTO_API_VERSION=18
*/
extern LTOObjectBuffer thinlto_module_get_object(thinlto_code_gen_t cg,
unsigned int index);
/**
* Returns the number of object files produced by the ThinLTO CodeGenerator.
*
* It usually matches the number of input files, but this is not a guarantee of
* the API and may change in future implementation, so the client should not
* assume it.
*
* \since LTO_API_VERSION=21
*/
unsigned int thinlto_module_get_num_object_files(thinlto_code_gen_t cg);
/**
* Returns the path to the ith object file produced by the ThinLTO
* CodeGenerator.
*
* Client should use \p thinlto_module_get_num_object_files() to get the number
* of available objects.
*
* \since LTO_API_VERSION=21
*/
const char *thinlto_module_get_object_file(thinlto_code_gen_t cg,
unsigned int index);
/**
* Sets which PIC code model to generate.
* Returns true on error (check lto_get_error_message() for details).
*
* \since LTO_API_VERSION=18
*/
extern lto_bool_t thinlto_codegen_set_pic_model(thinlto_code_gen_t cg,
lto_codegen_model);
/**
* Sets the path to a directory to use as a storage for temporary bitcode files.
* The intention is to make the bitcode files available for debugging at various
* stage of the pipeline.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_set_savetemps_dir(thinlto_code_gen_t cg,
const char *save_temps_dir);
/**
* Set the path to a directory where to save generated object files. This
* path can be used by a linker to request on-disk files instead of in-memory
* buffers. When set, results are available through
* thinlto_module_get_object_file() instead of thinlto_module_get_object().
*
* \since LTO_API_VERSION=21
*/
void thinlto_set_generated_objects_dir(thinlto_code_gen_t cg,
const char *save_temps_dir);
/**
* Sets the cpu to generate code for.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_set_cpu(thinlto_code_gen_t cg, const char *cpu);
/**
* Disable CodeGen, only run the stages till codegen and stop. The output will
* be bitcode.
*
* \since LTO_API_VERSION=19
*/
extern void thinlto_codegen_disable_codegen(thinlto_code_gen_t cg,
lto_bool_t disable);
/**
* Perform CodeGen only: disable all other stages.
*
* \since LTO_API_VERSION=19
*/
extern void thinlto_codegen_set_codegen_only(thinlto_code_gen_t cg,
lto_bool_t codegen_only);
/**
* Parse -mllvm style debug options.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_debug_options(const char *const *options, int number);
/**
* Test if a module has support for ThinLTO linking.
*
* \since LTO_API_VERSION=18
*/
extern lto_bool_t lto_module_is_thinlto(lto_module_t mod);
/**
* Adds a symbol to the list of global symbols that must exist in the final
* generated code. If a function is not listed there, it might be inlined into
* every usage and optimized away. For every single module, the functions
* referenced from code outside of the ThinLTO modules need to be added here.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_add_must_preserve_symbol(thinlto_code_gen_t cg,
const char *name,
int length);
/**
* Adds a symbol to the list of global symbols that are cross-referenced between
* ThinLTO files. If the ThinLTO CodeGenerator can ensure that every
* references from a ThinLTO module to this symbol is optimized away, then
* the symbol can be discarded.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_add_cross_referenced_symbol(thinlto_code_gen_t cg,
const char *name,
int length);
/**
* @} // endgoup LLVMCTLTO
* @defgroup LLVMCTLTO_CACHING ThinLTO Cache Control
* @ingroup LLVMCTLTO
*
* These entry points control the ThinLTO cache. The cache is intended to
* support incremental builds, and thus needs to be persistent across builds.
* The client enables the cache by supplying a path to an existing directory.
* The code generator will use this to store objects files that may be reused
* during a subsequent build.
* To avoid filling the disk space, a few knobs are provided:
* - The pruning interval limits the frequency at which the garbage collector
* will try to scan the cache directory to prune expired entries.
* Setting to a negative number disables the pruning.
* - The pruning expiration time indicates to the garbage collector how old an
* entry needs to be to be removed.
* - Finally, the garbage collector can be instructed to prune the cache until
* the occupied space goes below a threshold.
* @{
*/
/**
* Sets the path to a directory to use as a cache storage for incremental build.
* Setting this activates caching.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_set_cache_dir(thinlto_code_gen_t cg,
const char *cache_dir);
/**
* Sets the cache pruning interval (in seconds). A negative value disables the
* pruning. An unspecified default value will be applied, and a value of 0 will
* force prunning to occur.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_set_cache_pruning_interval(thinlto_code_gen_t cg,
int interval);
/**
* Sets the maximum cache size that can be persistent across build, in terms of
* percentage of the available space on the disk. Set to 100 to indicate
* no limit, 50 to indicate that the cache size will not be left over half the
* available space. A value over 100 will be reduced to 100, a value of 0 will
* be ignored. An unspecified default value will be applied.
*
* The formula looks like:
* AvailableSpace = FreeSpace + ExistingCacheSize
* NewCacheSize = AvailableSpace * P/100
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_set_final_cache_size_relative_to_available_space(
thinlto_code_gen_t cg, unsigned percentage);
/**
* Sets the expiration (in seconds) for an entry in the cache. An unspecified
* default value will be applied. A value of 0 will be ignored.
*
* \since LTO_API_VERSION=18
*/
extern void thinlto_codegen_set_cache_entry_expiration(thinlto_code_gen_t cg,
unsigned expiration);
/**
* Sets the maximum size of the cache directory (in bytes). A value over the
* amount of available space on the disk will be reduced to the amount of
* available space. An unspecified default value will be applied. A value of 0
* will be ignored.
*
* \since LTO_API_VERSION=22
*/
extern void thinlto_codegen_set_cache_size_bytes(thinlto_code_gen_t cg,
unsigned max_size_bytes);
/**
* Same as thinlto_codegen_set_cache_size_bytes, except the maximum size is in
* megabytes (2^20 bytes).
*
* \since LTO_API_VERSION=23
*/
extern void
thinlto_codegen_set_cache_size_megabytes(thinlto_code_gen_t cg,
unsigned max_size_megabytes);
/**
* Sets the maximum number of files in the cache directory. An unspecified
* default value will be applied. A value of 0 will be ignored.
*
* \since LTO_API_VERSION=22
*/
extern void thinlto_codegen_set_cache_size_files(thinlto_code_gen_t cg,
unsigned max_size_files);
/** Opaque reference to an LTO input file */
typedef struct LLVMOpaqueLTOInput *lto_input_t;
/**
* Creates an LTO input file from a buffer. The path
* argument is used for diagnotics as this function
* otherwise does not know which file the given buffer
* is associated with.
*
* \since LTO_API_VERSION=24
*/
extern lto_input_t lto_input_create(const void *buffer,
size_t buffer_size,
const char *path);
/**
* Frees all memory internally allocated by the LTO input file.
* Upon return the lto_module_t is no longer valid.
*
* \since LTO_API_VERSION=24
*/
extern void lto_input_dispose(lto_input_t input);
/**
* Returns the number of dependent library specifiers
* for the given LTO input file.
*
* \since LTO_API_VERSION=24
*/
extern unsigned lto_input_get_num_dependent_libraries(lto_input_t input);
/**
* Returns the ith dependent library specifier
* for the given LTO input file. The returned
* string is not null-terminated.
*
* \since LTO_API_VERSION=24
*/
extern const char * lto_input_get_dependent_library(lto_input_t input,
size_t index,
size_t *size);
/**
* @} // endgroup LLVMCTLTO_CACHING
*/
#ifdef __cplusplus
}
#endif
#endif /* LLVM_C_LTO_H */

11024
src/llvm_backend.cpp Normal file

File diff suppressed because it is too large Load Diff

407
src/llvm_backend.hpp Normal file
View File

@@ -0,0 +1,407 @@
#include "llvm-c/Core.h"
#include "llvm-c/ExecutionEngine.h"
#include "llvm-c/Target.h"
#include "llvm-c/Analysis.h"
#include "llvm-c/Object.h"
#include "llvm-c/BitWriter.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"
struct lbProcedure;
struct lbValue {
LLVMValueRef value;
Type *type;
};
enum lbAddrKind {
lbAddr_Default,
lbAddr_Map,
lbAddr_BitField,
lbAddr_Context,
lbAddr_SoaVariable,
};
struct lbAddr {
lbAddrKind kind;
lbValue addr;
union {
struct {
lbValue key;
Type *type;
Type *result;
} map;
struct {
i32 value_index;
} bit_field;
struct {
Selection sel;
} ctx;
struct {
lbValue index;
Ast *index_expr;
} soa;
};
};
struct lbModule {
LLVMModuleRef mod;
LLVMContextRef ctx;
CheckerInfo *info;
gbMutex mutex;
Map<LLVMTypeRef> types; // Key: Type *
Map<lbValue> values; // Key: Entity *
Map<lbValue> members; // Key: String
Map<lbProcedure *> procedures; // Key: String
Map<Entity *> procedure_values; // Key: LLVMValueRef
Map<LLVMValueRef> const_strings; // Key: String
Map<lbProcedure *> anonymous_proc_lits; // Key: Ast *
lbAddr global_default_context;
u32 global_array_index;
u32 global_generated_index;
u32 nested_type_name_guid;
Array<lbProcedure *> procedures_to_generate;
Array<String> foreign_library_paths;
LLVMDIBuilderRef debug_builder;
LLVMMetadataRef debug_compile_unit;
Map<LLVMMetadataRef> debug_values; // Key: Pointer
};
struct lbGenerator {
lbModule module;
CheckerInfo *info;
Array<String> output_object_paths;
String output_base;
String output_name;
};
struct lbBlock {
LLVMBasicBlockRef block;
Scope *scope;
isize scope_index;
bool appended;
Array<lbBlock *> preds;
Array<lbBlock *> succs;
};
struct lbBranchBlocks {
Ast *label;
lbBlock *break_;
lbBlock *continue_;
};
struct lbContextData {
lbAddr ctx;
isize scope_index;
};
enum lbParamPasskind {
lbParamPass_Value, // Pass by value
lbParamPass_Pointer, // Pass as a pointer rather than by value
lbParamPass_Integer, // Pass as an integer of the same size
lbParamPass_ConstRef, // Pass as a pointer but the value is immutable
lbParamPass_BitCast, // Pass by value and bit cast to the correct type
lbParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2)
};
enum lbDeferExitKind {
lbDeferExit_Default,
lbDeferExit_Return,
lbDeferExit_Branch,
};
enum lbDeferKind {
lbDefer_Node,
lbDefer_Instr,
lbDefer_Proc,
};
struct lbDefer {
lbDeferKind kind;
isize scope_index;
isize context_stack_count;
lbBlock * block;
union {
Ast *stmt;
// NOTE(bill): 'instr' will be copied every time to create a new one
lbValue instr;
struct {
lbValue deferred;
Array<lbValue> result_as_args;
} proc;
};
};
struct lbTargetList {
lbTargetList *prev;
bool is_block;
lbBlock * break_;
lbBlock * continue_;
lbBlock * fallthrough_;
};
enum lbProcedureFlag : u32 {
lbProcedureFlag_WithoutMemcpyPass = 1<<0,
};
struct lbProcedure {
u32 flags;
lbProcedure *parent;
Array<lbProcedure *> children;
Entity * entity;
lbModule * module;
String name;
Type * type;
Ast * type_expr;
Ast * body;
u64 tags;
ProcInlining inlining;
bool is_foreign;
bool is_export;
bool is_entry_point;
bool is_startup;
LLVMValueRef value;
LLVMBuilderRef builder;
bool is_done;
lbAddr return_ptr;
Array<lbValue> params;
Array<lbDefer> defer_stmts;
Array<lbBlock *> blocks;
Array<lbBranchBlocks> branch_blocks;
Scope * curr_scope;
i32 scope_index;
lbBlock * decl_block;
lbBlock * entry_block;
lbBlock * curr_block;
lbTargetList * target_list;
Array<lbContextData> context_stack;
lbValue return_ptr_hint_value;
Ast * return_ptr_hint_ast;
bool return_ptr_hint_used;
};
bool lb_init_generator(lbGenerator *gen, Checker *c);
void lb_generate_module(lbGenerator *gen);
String lb_mangle_name(lbModule *m, Entity *e);
String lb_get_entity_name(lbModule *m, Entity *e, String name = {});
LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value);
void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value);
void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name);
lbProcedure *lb_create_procedure(lbModule *module, Entity *entity);
void lb_end_procedure(lbProcedure *p);
LLVMTypeRef lb_type(lbModule *m, Type *type);
lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append=false);
lbValue lb_const_nil(lbModule *m, Type *type);
lbValue lb_const_undef(lbModule *m, Type *type);
lbValue lb_const_value(lbModule *m, Type *type, ExactValue value);
lbValue lb_const_bool(lbModule *m, Type *type, bool value);
lbValue lb_const_int(lbModule *m, Type *type, u64 value);
lbAddr lb_addr(lbValue addr);
Type *lb_addr_type(lbAddr const &addr);
LLVMTypeRef lb_addr_lb_type(lbAddr const &addr);
void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value);
lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr);
lbValue lb_emit_load(lbProcedure *p, lbValue v);
void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value);
void lb_build_stmt(lbProcedure *p, Ast *stmt);
lbValue lb_build_expr(lbProcedure *p, Ast *expr);
lbAddr lb_build_addr(lbProcedure *p, Ast *expr);
void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts);
lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) ;
lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index);
lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index);
lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, isize index);
lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index);
lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel);
lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel);
lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type);
lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type);
void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block);
lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t);
lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right);
lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false);
lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t);
lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x);
void lb_emit_jump(lbProcedure *p, lbBlock *target_block);
void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block);
void lb_start_block(lbProcedure *p, lbBlock *b);
lbValue lb_build_call_expr(lbProcedure *p, Ast *expr);
lbAddr lb_find_or_generate_context_ptr(lbProcedure *p);
void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx);
lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={});
lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_init=true, i32 param_index=0);
void lb_add_foreign_library_path(lbModule *m, Entity *e);
lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid);
lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value);
lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt);
lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init);
lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args);
lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index);
lbValue lb_string_elem(lbProcedure *p, lbValue string);
lbValue lb_string_len(lbProcedure *p, lbValue string);
lbValue lb_cstring_len(lbProcedure *p, lbValue value);
lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr);
lbValue lb_slice_elem(lbProcedure *p, lbValue slice);
lbValue lb_slice_len(lbProcedure *p, lbValue slice);
lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da);
lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da);
lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da);
lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da);
lbValue lb_map_entries(lbProcedure *p, lbValue value);
lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value);
lbValue lb_map_len(lbProcedure *p, lbValue value);
lbValue lb_map_cap(lbProcedure *p, lbValue value);
lbValue lb_soa_struct_len(lbProcedure *p, lbValue value);
void lb_emit_increment(lbProcedure *p, lbValue addr);
lbValue lb_type_info(lbModule *m, Type *type);
lbValue lb_find_or_add_entity_string(lbModule *m, String const &str);
lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent = nullptr);
bool lb_is_const(lbValue value);
bool lb_is_const_nil(lbValue value);
String lb_get_const_string(lbModule *m, lbValue value);
lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id);
lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type);
lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type);
void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value);
void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value);
lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value);
#define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime"
#define LB_STARTUP_CONTEXT_PROC_NAME "__$startup_context"
#define LB_STARTUP_TYPE_INFO_PROC_NAME "__$startup_type_info"
#define LB_TYPE_INFO_DATA_NAME "__$type_info_data"
#define LB_TYPE_INFO_TYPES_NAME "__$type_info_types_data"
#define LB_TYPE_INFO_NAMES_NAME "__$type_info_names_data"
#define LB_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data"
#define LB_TYPE_INFO_USINGS_NAME "__$type_info_usings_data"
#define LB_TYPE_INFO_TAGS_NAME "__$type_info_tags_data"
enum lbCallingConventionKind {
lbCallingConvention_C = 0,
lbCallingConvention_Fast = 8,
lbCallingConvention_Cold = 9,
lbCallingConvention_GHC = 10,
lbCallingConvention_HiPE = 11,
lbCallingConvention_WebKit_JS = 12,
lbCallingConvention_AnyReg = 13,
lbCallingConvention_PreserveMost = 14,
lbCallingConvention_PreserveAll = 15,
lbCallingConvention_Swift = 16,
lbCallingConvention_CXX_FAST_TLS = 17,
lbCallingConvention_FirstTargetCC = 64,
lbCallingConvention_X86_StdCall = 64,
lbCallingConvention_X86_FastCall = 65,
lbCallingConvention_ARM_APCS = 66,
lbCallingConvention_ARM_AAPCS = 67,
lbCallingConvention_ARM_AAPCS_VFP = 68,
lbCallingConvention_MSP430_INTR = 69,
lbCallingConvention_X86_ThisCall = 70,
lbCallingConvention_PTX_Kernel = 71,
lbCallingConvention_PTX_Device = 72,
lbCallingConvention_SPIR_FUNC = 75,
lbCallingConvention_SPIR_KERNEL = 76,
lbCallingConvention_Intel_OCL_BI = 77,
lbCallingConvention_X86_64_SysV = 78,
lbCallingConvention_Win64 = 79,
lbCallingConvention_X86_VectorCall = 80,
lbCallingConvention_HHVM = 81,
lbCallingConvention_HHVM_C = 82,
lbCallingConvention_X86_INTR = 83,
lbCallingConvention_AVR_INTR = 84,
lbCallingConvention_AVR_SIGNAL = 85,
lbCallingConvention_AVR_BUILTIN = 86,
lbCallingConvention_AMDGPU_VS = 87,
lbCallingConvention_AMDGPU_GS = 88,
lbCallingConvention_AMDGPU_PS = 89,
lbCallingConvention_AMDGPU_CS = 90,
lbCallingConvention_AMDGPU_KERNEL = 91,
lbCallingConvention_X86_RegCall = 92,
lbCallingConvention_AMDGPU_HS = 93,
lbCallingConvention_MSP430_BUILTIN = 94,
lbCallingConvention_AMDGPU_LS = 95,
lbCallingConvention_AMDGPU_ES = 96,
lbCallingConvention_AArch64_VectorCall = 97,
lbCallingConvention_MaxID = 1023,
};
lbCallingConventionKind const lb_calling_convention_map[ProcCC_MAX] = {
lbCallingConvention_C, // ProcCC_Invalid,
lbCallingConvention_C, // ProcCC_Odin,
lbCallingConvention_C, // ProcCC_Contextless,
lbCallingConvention_C, // ProcCC_CDecl,
lbCallingConvention_X86_StdCall, // ProcCC_StdCall,
lbCallingConvention_X86_FastCall, // ProcCC_FastCall,
lbCallingConvention_C, // ProcCC_None,
};

File diff suppressed because it is too large Load Diff

View File

@@ -55,12 +55,14 @@ gb_inline HashKey hash_string(String s) {
gb_inline HashKey hash_pointer(void *ptr) {
HashKey h = {HashKey_Ptr};
h.key = cast(u64)cast(uintptr)ptr;
// h.key = gb_fnv64a(&ptr, gb_size_of(void *));
h.ptr = ptr;
return h;
}
gb_inline HashKey hash_ptr_and_id(void *ptr, u64 id) {
HashKey h = {HashKey_PtrAndId};
h.key = cast(u64)cast(uintptr)ptr;
// h.key = gb_fnv64a(&ptr, gb_size_of(void *));
h.ptr_and_id.ptr = ptr;
h.ptr_and_id.id = id;
return h;

View File

@@ -98,7 +98,6 @@ struct AstFile {
Array<Ast *> imports; // 'import' 'using import'
isize directive_count;
Ast * curr_proc;
isize error_count;
@@ -111,6 +110,9 @@ struct AstFile {
#define PARSER_MAX_FIX_COUNT 6
isize fix_count;
TokenPos fix_prev_pos;
struct LLVMOpaqueMetadata *llvm_metadata;
struct LLVMOpaqueMetadata *llvm_metadata_scope;
};
@@ -174,12 +176,10 @@ enum ProcCallingConvention {
ProcCC_StdCall,
ProcCC_FastCall,
// TODO(bill): Add extra calling conventions
// ProcCC_VectorCall,
// ProcCC_ClrCall,
ProcCC_None,
ProcCC_MAX,
ProcCC_ForeignBlockDefault = -1,
};
@@ -251,6 +251,7 @@ enum StmtAllowFlag {
ProcInlining inlining; \
Token where_token; \
Array<Ast *> where_clauses; \
DeclInfo *decl; \
}) \
AST_KIND(CompoundLit, "compound literal", struct { \
Ast *type; \

View File

@@ -101,6 +101,14 @@ char *alloc_cstring(gbAllocator a, String s) {
return c_str;
}
char *cstring_duplicate(gbAllocator a, char const *s) {
isize len = gb_strlen(s);
char *c_str = gb_alloc_array(a, char, len+1);
gb_memmove(c_str, s, len);
c_str[len] = '\0';
return c_str;
}
gb_inline bool str_eq_ignore_case(String const &a, String const &b) {

View File

@@ -179,6 +179,10 @@ Token make_token_ident(String s) {
Token t = {Token_Ident, s};
return t;
}
Token make_token_ident(char const *s) {
Token t = {Token_Ident, make_string_c(s)};
return t;
}
struct ErrorCollector {
@@ -904,7 +908,7 @@ Token tokenizer_get_token(Tokenizer *t) {
}
if (token.kind == Token_Ident && token.string == "notin") {
token.kind = Token_not_in;
token.kind = Token_not_in;
}
}