/* csbe.h -- Compiler backend for cslul Copyright © 2022-2024 Samuel Lidén Borell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CSBE_H #define CSBE_H #include #include #define CSBE_API_VERSION_0 0 typedef uint8_t CsbeUint8; typedef uint16_t CsbeUint16; typedef uint32_t CsbeUint32; typedef uint64_t CsbeUint64; typedef int8_t CsbeInt8; typedef int16_t CsbeInt16; typedef int32_t CsbeInt32; typedef int64_t CsbeInt64; struct Csbe; struct CsbeLibrary; struct CsbeSymVer; /** * Type of the user-supplied allocation function. * * \param userctx The userctx parameter that was passed to csbe_config_new. * \param size Size of allocation in bytes. * \param align Alignment requirement. Never larger than the largest * pointer type, so a normal malloc will always satisfy * this requirement. * \return Pointer to the allocated data. */ typedef void *(CsbeAllocFunc)(void *userctx, size_t size, size_t align); /** * Type of the optional user-supplied buffer allocation function to * csbe_output(). * * \param userparam Custom data. * \param size Allocation size in bytes. * \return Pointer the buffer (does not have to be aligned), * or NULL on error. */ typedef void *(CsbeBufferAllocFunc)(void *userparam, size_t size); struct CsbeFuncPtrs { /** Set to a function that tracks memory allocation (e.g. a arena allocator, or a garbage collecting allocator). If set to NULL, then memory is allocated with malloc and leaked, which might be acceptable for CLI applications. */ CsbeAllocFunc *fptr_alloc; /* csbe_config_new must be updated if new fields are to be added */ }; enum CsbeErr { CSBEE_OK = 0, /**< No error. */ CSBEE_OUT_OF_MEM, /**< Out of memory */ CSBEE_INVALID_PARAM, /**< Invalid parameter to a function */ CSBEE_TYPE_TOO_LARGE, /**< Too many fields (max 4096) or elems (2^31-1) */ CSBEE_TOO_MANY_ITEMS, /**< Too many items, e.g. EBB's or func params */ CSBEE_UNKNOWN_ARCH, /**< Unknown CPU or OS type. */ CSBEE_ARCH_NOT_SUPPORTED, /**< E.g. unsupported CPU/OS for output format */ CSBEE_UNSUPPORTED_FEATURE_PARAM, /**< CPU/OS does't support this feature */ CSBEE_INTERNAL_ERROR /**< Internal error (i.e. a bug) */ }; /* FIXME this overlaps with CsbeOutputFormat! */ enum CsbeModuleType { CSBEMT_EXEC, /**< Output is an executable file */ CSBEMT_DYNLIB, /**< Output is a dynamic library (.so or .dll) */ CSBEMT_STATICLIB, /**< Output is a static library (.a or .lib) */ CSBEMT_DYNSTATICLIB,/**< Output is a static library for use in dynamic libraries (somewhat uncommon case) */ CSBEMT_STATICOBJ, /**< Output is an object file for use in executables or regular static libraries. */ CSBEMT_DYNOBJ /**< Output is an object file for use in dynamic libraries */ }; enum CsbeSymverExportMode { /** Export versioned symbols as versioned if the target platform supports it. Symbol versioning is possible on ELF/SysV platforms */ CSBESEM_DEFAULT, /** Disable symbol versioning for exported symbols. All current platforms support unversioned symbols. This option is useful if the language performs versioning using some other means, for example using "marker symbols". */ CSBESEM_AVOID }; enum CsbeOutputStatus { CSBEOS_ERROR = -1, CSBEOS_FINISHED = 0, CSBEOS_MORE = 1 }; enum CsbeTypeKind { CSBET_BOOL, CSBET_INT, CSBET_UINT, CSBET_LONG, CSBET_ULONG, CSBET_I8, CSBET_U8, CSBET_I16, CSBET_U16, CSBET_I32, CSBET_U32, CSBET_I64, CSBET_U64, CSBET_F32, CSBET_F64, CSBET_SSIZE, CSBET_USIZE, CSBET_DPTR, CSBET_DPTR_ALIASED, CSBET_DPTR_THREADED, CSBET_FPTR }; #define NUM_TYPEKINDS (CSBET_FPTR+1) enum CsbePackMode { /** C struct packing. Fields are always added last with necessary alignment padding between fields. */ CSBEPM_CPACK, /** Union packing. All fields are placed at offset 0 */ CSBEPM_UNION, /* Optimized stable struct packing. Fields are added last, unless they fit in an alignment hole. Smaller alignment holes are prioritized before larger ones, and if equally sized, ones with lower address are prioritized over ones with higher address. */ /*CSBEPM_OPTSTABLEPACK,*/ /* TODO not yet implemented */ /** Any struct packing. Can be optimized freely by the backend */ CSBEPM_ANYPACK }; /* XXX replace quals with a flag to operations? */ /*enum CsbeTypeQuals { CSBETQ_VAR = 0x01, CSBETQ_ALIASED = 0x02, CSBETQ_THREADED = 0x04, };*/ enum CsbeAbi { CSBEABI_C_NORMAL, CSBEABI_ANYCALL /*CSBEABI_SLUL_NORMAL, CSBEABI_SLUL_TIGHTCALL*/ /* uses less regs */ }; #define CSBEFD_NORETURN 0x1 /**< Function never returns */ #define CSBEFD_OBJGLOBAL 0x2 /**< Available to other object files */ /** * Main function. This should have the following definition: * * int main(int arg1, void *arg2) * * On systems that use a system-wide C library (Linux, BSD, etc.) * the parameters work as follows: * * int arg1 Argument count, >= 0 * char **arg2 Arguments, != NULL * * On Windows, no argument information is passed at startup, * and the parameters are simply NULL: * * int arg1 Reserved, always -1 * void *arg2 Reserved, always NULL * * Note that the main function is NOT the entry point. The entry point * consists of some system-specific glue code, that at least aligns the * stack before it calls the main function. */ #define CSBEFD_MAIN 0x4 #define CSBEDD_EXTERNAL 0x1 /**< External definition */ #define CSBEDD_OBJGLOBAL 0x2 /**< Available to other object files */ /*#define CSBEDD_MODIFIABLE 0x4 *< The data can be modified (TODO implement) */ #define CSBEDD_NON_UNIQUE 0x8 /**< Does NOT need a unique address */ enum CsbeCallMode { CSBECM_NORMAL, CSBECM_TAILCALL /* XXX remove, and auto-detect instead? */ }; enum CsbeBranchType { CSBEBT_Z, CSBEBT_NZ, CSBEBT_LZ, CSBEBT_GEZ, CSBEBT_GZ, CSBEBT_LEZ }; enum CsbeBranchBalance { CSBEBB_UNKNOWN, CSBEBB_EQUAL, CSBEBB_NEVER, /**< For very unlikely events such as errors */ CSBEBB_ALWAYS, /**< For very likely events, such as no error */ CSBEBB_SOMEWHAT_UNLIKELY, CSBEBB_SOMEWHAT_LIKELY }; enum CsbeSelectBalance { CSBESB_UNKNOWN, CSBESB_EQUAL, CSBESB_1_ONLY, /**< Only value 1 can be selected in normal conditions */ CSBESB_2_ONLY, CSBESB_1_MAINLY, CSBESB_2_MAINLY }; enum CsbeSizeofKind { CSBES_SIZEOF_ALIGNED, CSBES_SIZEOF_INNER, CSBES_ALIGNOF }; #define CSBE_OPDEF0(op) op, #define CSBE_OPDEF1(op,a) op, #define CSBE_OPDEF2(op,a,b) op, #define CSBE_OPDEF3(op,a,b,c) op, #define CSBE_OPDEF4(op,a,b,c,d) op, #define CSBE_OPDEF5(op,a,b,c,d,e) op, #define CSBE_OPDEF_LAST CSBEO_LAST enum CsbeOp { # include "csbe_ops.h" }; enum CsbeSymbolType { /** Imports/exports the last function definition */ CSBEST_LAST_FUNC, /** Imports/exports the last data definition */ CSBEST_LAST_DATA, /** Imports/exports a "marker" (a symbol that has no real function body, but must be resolvable at load time). These can be used to require a particular version of a library, or a particular compile-time optional feature of a library, or similar. */ CSBEST_MARKER }; /* Values that are guaranteed to never be valid ID's. Can be used as sentinel/none values. */ #define CSBE_INVALID_TYPEDEF ((unsigned)-1) #define CSBE_INVALID_FUNCDEF ((unsigned)-1) #define CSBE_INVALID_DATADEF ((unsigned)-1) #define CSBE_INVALID_VARIABLE ((unsigned)-1) #define CSBE_INVALID_EBB ((unsigned)-1) /* ======================================================================= |||||||||||||||||||||||||| Initialization ||||||||||||||||||||||||||| ======================================================================= All CSBE operations work on a CSBE context object (struct Csbe *). The context object is created from a configuration object, which in turn decides which CPU architectures to target. Usually, at least one CPU architecture should be added using csbe_config_add_arch. */ /** * Creates a new CSBE context with the given configuration * * If you wish to be able to free allocated memory, you must do so by passing * a custom allocation function in funcptrs. For example an arena allocator * a garbage collecting allocator. CSBE does not free (or track) memory by * itself. * * \param api_version The version of CSBE API that the caller will use. * \param funcptrs Optionally specifies a custom allocator. May be NULL * \param userctx "User context" parameter that is passed to the * allocator and other callbacks * \return CsbeConfig or NULL on error */ struct CsbeConfig *csbe_config_new(int api_version, const struct CsbeFuncPtrs *funcptrs, void *userctx); /* TODO add more CPU architectures */ enum CsbeCpu { CSBEC_IR_DUMP, CSBEC_I386, CSBEC_X86_64, /* CSBEC_ARM,*/ CSBEC_AARCH64/*, CSBEC_MIPS, CSBEC_OR1K, CSBEC_PPC64, CSBEC_RV32, CSBEC_RV64, CSBEC_SH4*/ }; enum CsbeEndianness { CSBEEN_LITTLE_ENDIAN, CSBEEN_BIG_ENDIAN }; enum CsbeOsType { CSBEOS_LINUX_GLIBC, CSBEOS_LINUX_MUSL, /* TODO BSDs, MacOS etc. */ CSBEOS_WINDOWS }; #define CSBEOS_NUM_OSTYPES (CSBEOS_WINDOWS+1) enum CsbeOutputFormat { CSBEOF_RAW, /**< Raw machine code. Also used when dumping IR */ CSBEOF_ELF_EXE, /**< ELF Position Independent Executable */ CSBEOF_ELF_DYNLIB, /**< ELF dynamic library (.so) */ CSBEOF_ELF_OBJ, /**< ELF object file (.o) */ /* CSBEOF_ELF_STATLIB, CSBEOF_PE_EXE CSBEOF_PE_DLL*/ CSBEOF_PE_OBJ /* CSBEOF_PE_STATLIB*/ }; #define CSBEOS_NUM_OUTFORMATS (CSBEOF_PE_OBJ+1) #define CSBEF_COMMON_HARDFLOAT -1 /** * Adds the given target architecture. * * \param cfg CSBE configuration * \param cpu Architecture, e.g. CSBEC_X86_64 * \param endianness Endianness, CSBEEN_LITTLE_ENDIAN or CSBEEN_BIG_ENDIAN * \param ostype Operating system type (CSBEOS_SYSV or CSEBOS_WINDOWS) * \param outformat File format of output file (CSBEOF_*) * \param elf_interp Program interpeter (ld.so) path. Only for ELF format. * \return CSBEE_OK if supported, or an error code if not. */ enum CsbeErr csbe_config_add_arch(struct CsbeConfig *cfg, enum CsbeCpu cpu, enum CsbeEndianness endianness, enum CsbeOsType ostype, enum CsbeOutputFormat outformat); /** * Checks whether an architecture feature can be enabled/disabled * for the last added architecture. * * \param cfg CSBE configuration * \param feature Architecture specific feature, CSBEF_* * \param state Check if the feature can be: 1=enabled, 0=disabled * \return 1 if the given state is supported, 0 if not. */ int csbe_config_arch_has_feature_state(struct CsbeConfig *cfg, int feature, int state); /** * Enables/disables an architecture feature for the last added architecture. * * \param cfg CSBE configuration * \param feature Architecture specific feature, CSBEF_* * \param state 1=enable, 0=disable * \return CSBEE_OK if feature is supported, or an error code if not. */ enum CsbeErr csbe_config_arch_feature(struct CsbeConfig *cfg, int feature, int state); void csbe_config_set_moduletype(struct CsbeConfig *cfg, enum CsbeModuleType modtype); void csbe_config_set_symver_export(struct CsbeConfig *cfg, enum CsbeSymverExportMode mode); /** * Creates a new CSBE context with the given configuration * * There is no csbe_free function. You must track the allocations yourself * (e.g. using an arena allocator or garbage collector) by passing a custom * allocation function in the CsbeFuncPtrs. */ struct Csbe *csbe_new(const struct CsbeConfig *cfg); /** Checks if there is an error */ enum CsbeErr csbe_get_error(const struct Csbe *csbe); /** * Sets the name of the input being compiled. This should be the source * filename when there is a single file per compilation unit. The value * is used in the FILE symbol in ELF object files. * * \param csbe CSBE context. * \param name Name. Do not free or modify while the CSBE context is in use. */ void csbe_set_input_name(struct Csbe *csbe, const char *name); /* ======================================================================= ||||||||||||||||||||||||||||||| Types ||||||||||||||||||||||||||||||| ======================================================================= Each type fills one slot (nested types also fill one, but can contain multiple slots). Typedefs, global data definitions and variable definitions all have one slot for the type. Nested types such are function types and struct types are special: Function definitions instead have one slot for the return type and zero or more slots for the parameter types. Structs/unions have zero or more slots: One slot per field. */ /** Fills the next slot with a void type. Only applicable to function returns */ void csbe_type_void(struct Csbe *csbe); /** Fills the next slot with a simple type such as int, bool or a pointer */ void csbe_type_simple(struct Csbe *csbe, enum CsbeTypeKind kind); /** Fills the next slot with a "named type", i.e. a reference to a typedef */ enum CsbeErr csbe_type_named(struct Csbe *csbe, unsigned typedef_id); /** Fills the next slot with an array. Multidimensional array types are automatically merged into a single array type, by multiplying the lengths. The element type is defined by the following slot, which can be any type (except void). */ enum CsbeErr csbe_type_array(struct Csbe *csbe, unsigned array_length); /** Fills the next slot with a struct type. csbe_type_struct_done must be called after the last slot (=field) has been filled (=added). */ enum CsbeErr csbe_type_struct_start(struct Csbe *csbe, int num_fields, enum CsbePackMode packmode); enum CsbeErr csbe_type_struct_end(struct Csbe *csbe); /** Multiplies two array lengths, storing the result in prod_out. An error is returned if the array is larger than supported, or if overflow occurs. */ enum CsbeErr csbe_multiply_arraylengths(struct Csbe *csbe, unsigned *prod_out, unsigned l1, unsigned l2); /* ======================================================================= |||||||||||||||||||||||| Imports and Exports |||||||||||||||||||||||| ======================================================================= */ /** * Adds a library import. * * Note: The string is NOT copied. It must NOT be modified or free'd * until after the last CSBE call using the same struct Csbe. * * \param csbe CSBE context * \param libname Name of library, without "lib", ".so", ".dll", etc. * \param libnamelen Length of libname * \return Opaque CsbeLibrary object, or NULL on error. */ struct CsbeLibrary *csbe_add_libimport(struct Csbe *csbe, const char *libname, unsigned libnamelen); /** * Defines a symbol version. The symbol versions MUST be defined in * ascending order. * * Note: The strings are NOT copied. It must NOT be modified or free'd * until after the last CSBE call using the same struct Csbe. * * \param csbe CSBE context * \param lib Library, or NULL for export. * \param verprefix Version prefix, typically the module name in uppercase * \param verprefixlen Length of verprefix * \param vername Version * \param vernamelen Length of vername * \return Error code, or CSBEE_OK if successful. */ struct CsbeSymVer *csbe_define_symver(struct Csbe *csbe, struct CsbeLibrary *lib, const char *verprefix, unsigned verprefixlen, const char *vername, unsigned vernamelen); /** * Marks the last declaration as an exported declaration. * * Note: The strings are NOT copied. It must NOT be modified or free'd * until after the last CSBE call using the same struct Csbe. */ enum CsbeErr csbe_export_decl(struct Csbe *csbe, enum CsbeSymbolType symtype, struct CsbeSymVer *symver, const char *name, unsigned namelen); /** * Marks the last declaration as an exported declaration. * * Note: The strings are NOT copied. It must NOT be modified or free'd * until after the last CSBE call using the same struct Csbe. */ enum CsbeErr csbe_import_decl(struct Csbe *csbe, enum CsbeSymbolType symtype, struct CsbeLibrary *lib, struct CsbeSymVer *symver, const char *name, unsigned namelen); /* ======================================================================= ||||||||||||||||||||||| Top-level Declarations |||||||||||||||||||||| ======================================================================= */ /** * Sets the number of typedefs. This allocates all typedefs, and makes it * possible to referencecs typedefs by ID (which is necessary when * creating mutually refential or self-referential definitions). * * \param csbe CSBE context. * \param count Number of typedefs (= maximum ID + 1) * \return CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory. */ enum CsbeErr csbe_set_num_typedefs(struct Csbe *csbe, unsigned count); enum CsbeErr csbe_set_num_datadefs(struct Csbe *csbe, unsigned count); enum CsbeErr csbe_set_num_funcdefs(struct Csbe *csbe, unsigned count); void csbe_typedef_start(struct Csbe *csbe, unsigned id); void csbe_typedef_end(struct Csbe *csbe); /** * Starts a function declaration. * * Use csbe_type_* to add the function type type (can be void). * and then once for each parameter, from left to right. * * \param csbe CSBE context. * \param id ID of function declaration. * \param num_params Number of parameters (excluding return type). * \param abi Calling convention, CSBEABI_* * \param flags Bitmask of CSBEFD_* flags. * \return CSBEE_OK if successful, or an error code on error. */ enum CsbeErr csbe_funcdef_start(struct Csbe *csbe, unsigned id, int num_params, enum CsbeAbi abi, unsigned flags); /** * Sets the name of a function. This will be added in the symbol table * (but it will be a local symbol, unless it is explicitly exported). * * \param csbe CSBE context. * \param name Name of function. The pointer is stored in the CSBE context. * \param len Length of name. */ void csbe_funcdef_set_name(struct Csbe *csbe, const char *name, size_t len); void csbe_funcdef_end(struct Csbe *csbe); /** * Starts a data declaration. * * CSBE supports only non-pointers and constants only, but structs and * arrays are supported (if they don't contain pointers). * * After calling csbe_datadef_start, please call: * 1. csbe_type_* to define the type. * * And if there is an initial value: * 1. csbe_datadef_initval_start * 2. csbe_datadef_value_* to add value(s) * 3. csbe_datadef_initval_end. * For unions, the initial value applies to the first member. * * For external data, please include the flag CSBEDD_EXTERNAL * (and don't add any initial value). * * \param csbe CSBE context. * \param id ID of data declaration. * \param flags CSBEDD_* flags. */ void csbe_datadef_start(struct Csbe *csbe, unsigned id, unsigned flags); /** * Sets the name of a datadef. This will be added in the symbol table * (but it will be a local symbol, unless it is explicitly exported). * * \param csbe CSBE context. * \param name Name of datadef. The pointer is stored in the CSBE context. * \param len Length of name. */ void csbe_datadef_set_name(struct Csbe *csbe, const char *name, size_t len); enum CsbeErr csbe_datadef_initval_start(struct Csbe *csbe); /** Adds a scalar value in an initial value. */ void csbe_datadef_value_int(struct Csbe *csbe, CsbeUint64 value); /** Adds an array of int8/uint8/boolean in an initial value. The array pointer will be stored, so don't free it (or modify the contents) while the CSBE context is still in use. */ void csbe_datadef_value_bytearray(struct Csbe *csbe, const unsigned char *values, unsigned array_length); /** Adds an array of int16 or greater in an initial value. The array pointer will be stored, so don't free it while the CSBE context is still in use. */ void csbe_datadef_value_intarray(struct Csbe *csbe, const CsbeUint64 *values, unsigned array_length); void csbe_datadef_initval_end(struct Csbe *csbe); void csbe_datadef_end(struct Csbe *csbe); /** * Must be called after the definitions of types and functions are done, * and before any function bodies are added. * * Data definitions can still be added even after csbe_defs_done has been * called, in order to simplify generation of literals (e.g. inline string * constants). */ enum CsbeErr csbe_defs_done(struct Csbe *csbe); /* ======================================================================= |||||||||||||||||||||||||| Function Bodies |||||||||||||||||||||||||| ======================================================================= */ #if 0 /* TODO */ /** Function bodies can be generated in parallel (except inlined functions). This functions creates thread-safe "sub contexts" for processing function bodies */ struct Csbe *csbe_subctx_new(struct Csbe *csbe, CsbeAllocFunc *fptr_alloc, void *userctx); /** Merges a subctx into a main ctx */ enum CsbeErr csbe_subctx_merge(struct Csbe *csbe, struct Csbe *subctx); #endif /** * Adds a function body to a function declaration. * * Optionally, all temporary allocations, that can be discarded after * the code for the function has been generated, can be diverted to a * separate allocator. * * \param func_id ID of function declaration. * \param temp_alloc Allocator of temporary data. NULL to use same allocator. * \param userctx Parameter to allocator. * \param num_ebb Number of bblocks (EBB = Extended Basic Block) * \param num_vars Number of variable definitions * (including parameters and temporaries) * \return CSBEE_OK if successful, or an error code if not. */ enum CsbeErr csbe_funcbody_start(struct Csbe *csbe, unsigned func_id, CsbeAllocFunc *temp_alloc, void *userctx, unsigned num_ebb, unsigned num_vars); enum CsbeErr csbe_funcbody_end(struct Csbe *csbe); /* * * * * Variable definitions in functions. * * * * * Variables must be defined before being used. */ #define CSBEVD_SIMPLE 0x0 #define CSBEVD_MULTI_READ 0x1 /* TODO get rid of this? */ #define CSBEVD_MULTI_WRITE 0x2 /* TODO get rid of this? */ #define CSBE_VARLANE_NONE 0 /** * Defines a parameter in a function. All parameters must be defined, * and in order. * * The parameters must be defined before any other variables. * * See csbe_funcbody_vardef_start() for details. */ void csbe_funcbody_paramdef(struct Csbe *csbe, unsigned flags, unsigned var_id); /** * Defines a variable in a function. The storage location is automatically * decided (stack, register, etc.). * * Note that temporaries and function parameters must be defined, in * addition to local variables. Function parameters can be defined * automatically (based on the type in the function declaration) using * csbe_funcbody_param() * * \param csbe CSBE context * \param flags Bitwise OR of CSBEVD_* flags * \param var_id Index of variable * \param var_lane Variables that will never be used at the same time can * be placed in the same "lane". This information is used * for register allocation. This is a 1-based index or * CSBE_VARLANE_NONE. TODO perhaps remove this and only * support automatic register allocation? * FIXME should placing different types in the same varlane be allowed or not? * - for temporaries, it makes things easier if it is allowed. * - if disallowed: need to track which varlanes are non-overlapping. */ void csbe_funcbody_vardef_start(struct Csbe *csbe, unsigned flags, unsigned var_id, unsigned var_lane); void csbe_funcbody_vardef_end(struct Csbe *csbe); /* * * * * Extended Basic Block and code * * * * */ /** * Sets the basic block to jump to when a "trap" occurs. For example, if * an out-of-bounds error happens in any of the _TRAP operations. * * Must be called before calling csbe_ebb_start. * * \param csbe CSBE context * \param trap_ebb ID of basic block to jump to on error. */ void csbe_funcbody_set_trap_ebb(struct Csbe *csbe, unsigned trap_ebb); /** * Marks the start of a basic block. CSBE uses "extended basic blocks", * which can outbound jumps/calls at any location, not just at the end. * * \param csbe CSBE context. * \param ebb_id ID of basic block. * \param flags Bitwise OR of CSBEEF_* flags. * \return CSBEE_OK if successful, or an error code if not. */ enum CsbeErr csbe_ebb_start(struct Csbe *csbe, unsigned ebb_id, unsigned flags); #define CSBEEF_DEFAULT 0 /** Basic block is unlikely to be reached. It could be placed "far away" or could be optimized for size, for example. */ #define CSBEEF_UNLIKELY 0x1 /** The previously started EBB "flows into" this EBB. This will cause an implicit jump to be inserted if the EBB does not come directly after the previous one. */ #define CSBEEF_FLOWINTO 0x2 /** * If the EBB is the last one in the source language, but not the highest * numbered EBB in CSBE, then this function can be used to tell CSBE to * add a RETURN_VOID operation if the function is a void function. * * \param csbe CSBE context * \return CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory. */ enum CsbeErr csbe_ebb_implicit_return(struct Csbe *csbe); /* ======================================================================= |||||||||||||||||||||||||||| Operations ||||||||||||||||||||||||||||| ======================================================================= */ /** * Marks the beginning of an operation inside a bblock. * Operands should be set with csbe_operand_*, and then csbe_op_end() * should be called. The operands depend on the operations; see csbe_ops.h * * \param csbe CSBE context * \param op Operation, a CSBEO_* constant * \return CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory. */ enum CsbeErr csbe_op_start(struct Csbe *csbe, enum CsbeOp op); void csbe_op_end(struct Csbe *csbe); /** * Adds a variable input operand. * * If this is the last time the variable is used, then it can be discarded * using the flag CSBE_OPV_DISCARD. That can reduce unnecessary usage * of callee-saved registers (that need to be saved/restored). * * \param csbe CSBE context * \param var_num Variable number. 0-based index. * \param flags Bitwise OR of CSBE_OPV_* flags. */ void csbe_operand_var_in(struct Csbe *csbe, unsigned var_num, unsigned flags); /** Variable is discarded after use (input vars only) */ #define CSBE_OPV_DISCARD 0x1 /** * Adds a variable output/result operand. * * \param csbe CSBE context * \param var_num Variable number. 0-based index. * \param flags Bitwise OR of CSBE_OPV_* flags * (none exists yet; must be 0). */ void csbe_operand_var_out(struct Csbe *csbe, unsigned var_num, unsigned flags); /** * Diverts the result of the last operation to another variable. * More precisely, this modifies the last csbe_operand_var_out() call. * * This function will "delete" the previous result variable by marking * it as unused. So this function should ONLY be used when the previous * result went to a temporary variable. * * \param csbe CSBE context * \param var_num New variable number. 0-based index. * \param flags Bitwise OR of CSBE_OPV_* flags * (none exists yet; must be 0). */ void csbe_divert_result(struct Csbe *csbe, unsigned var_num, unsigned flags); /** * Adds an integer value as an operand. * Note that static indexes should be added with csbe_operand_index(). * * \param csbe CSBE context * \param typekind Type of value (CSBET_*) * \param value The value. Signed values are simply casted. */ void csbe_operand_immed(struct Csbe *csbe, enum CsbeTypeKind typekind, CsbeUint64 value); /** Adds an index as an operand. */ void csbe_operand_index(struct Csbe *csbe, unsigned index); /** * Adds a basic block ID as an operand. * * \param csbe CSBE context * \param ebb_num ID of basic block. */ void csbe_operand_ebb(struct Csbe *csbe, unsigned ebb_num); /** Adds a function ID as an operand. */ void csbe_operand_funcdef(struct Csbe *csbe, unsigned funcdef_num); /** Adds a global datadef ID as an operand. */ void csbe_operand_datadef(struct Csbe *csbe, unsigned datadef_num); /** * Adds an operation-specific bitmask as an operand. * * \param csbe CSBE context * \param flags Bitwise OR of operation-specific flags. */ void csbe_operand_flags(struct Csbe *csbe, unsigned flags); /** * Adds an operation-specific enum value as an operand. * * \param csbe CSBE context * \param enumval Value from operation-specific enum. */ void csbe_operand_enum(struct Csbe *csbe, int enumval); /** * Adds an operation-specific pointer as an operand. * * \param csbe CSBE context * \param enumval Operation-specific pointer. */ void csbe_operand_ptr(struct Csbe *csbe, void *p); /** * Adds a type as an operand. * Must be followed by call(s) for csbe_type_...() * and finally csbe_operand_type_end() * * \param csbe CSBE context * \return CSBEE_OK if successful, or CSBEE_OUT_OF_MEM if out of memory. */ enum CsbeErr csbe_operand_type_start(struct Csbe *csbe); /** * Finalizes a type operand started with csbe_operand_type_start(). */ void csbe_operand_type_end(struct Csbe *csbe); /** * Marks the start of a function. Internally, this adds a * CSBEO_CALL_START and sets some internal information. * * \param csbe CSBE context * \param num_args Number of arguments (including "this" parameter, * but excluding the return value) * \return CSBEE_OK if successful, or an error code if not. */ enum CsbeErr csbe_call_start(struct Csbe *csbe, unsigned num_args); /** * Marks the start of a function argument. Internally, this starts a * CSBEO_CALL_ARG operation and sets some internal information. * * After this function call, csbe_operand_var_in() or * csbe_operand_immed() should be called, and then csbe_call_arg_end(). */ enum CsbeErr csbe_call_arg_start(struct Csbe *csbe); /** Marks the end of a function argument */ void csbe_call_arg_end(struct Csbe *csbe); /** This produces the first parameter to CSBEO_CALL_FUNC* */ void csbe_operand_callinfo(struct Csbe *csbe); /* ======================================================================= ||||||||||||||||||||||||| Output Generation ||||||||||||||||||||||||| ======================================================================= */ /** * Generates an output file (e.g. executable, library, etc) for the * architecture with the given index. * * \param csbe CSBE context * \param arch_id 0-based index of the architecture, in the order they * were added with csbe_config_add_arch * Should be 0 if there is only one. * \param buffer_out Result is allocated and placed here. * \param size_out Size is placed here. * \param allocfn Optional function to use for allocating the result * buffer. The buffer needs no alignment. * If NULL, then malloc is used. * \param userparam User parameter to pass to the allocator. * \return CSBEE_OK if successful, or an error code if not. */ enum CsbeErr csbe_output(struct Csbe *csbe, int arch_id, unsigned char **buffer_out, size_t *size_out, CsbeBufferAllocFunc *allocfn, void *userparam); #endif