PostgreSQL Source Code git master
Loading...
Searching...
No Matches
llvmjit.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * llvmjit.c
4 * Core part of the LLVM JIT provider.
5 *
6 * Copyright (c) 2016-2026, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * src/backend/jit/llvm/llvmjit.c
10 *
11 *-------------------------------------------------------------------------
12 */
13
14#include "postgres.h"
15
16#include <llvm-c/Analysis.h>
17#include <llvm-c/BitReader.h>
18#include <llvm-c/BitWriter.h>
19#include <llvm-c/Core.h>
20#include <llvm-c/ExecutionEngine.h>
21#if LLVM_VERSION_MAJOR > 16
22#include <llvm-c/Transforms/PassBuilder.h>
23#endif
24#include <llvm-c/Orc.h>
25#include <llvm-c/OrcEE.h>
26#include <llvm-c/LLJIT.h>
27#include <llvm-c/Support.h>
28#include <llvm-c/Target.h>
29#if LLVM_VERSION_MAJOR < 17
30#include <llvm-c/Transforms/IPO.h>
31#include <llvm-c/Transforms/PassManagerBuilder.h>
32#include <llvm-c/Transforms/Scalar.h>
33#include <llvm-c/Transforms/Utils.h>
34#endif
35
36#include "jit/llvmjit.h"
38#include "jit/llvmjit_emit.h"
39#include "miscadmin.h"
41#include "storage/ipc.h"
42#include "utils/memutils.h"
43#include "utils/resowner.h"
44
45#define LLVMJIT_LLVM_CONTEXT_REUSE_MAX 100
46
47/* Handle of a module emitted via ORC JIT */
53
54
55/* types & functions commonly needed for JITing */
78
82
84
85static bool llvm_session_initialized = false;
86static size_t llvm_generation = 0;
87
88/* number of LLVMJitContexts that currently are in use */
90
91/* how many times has the current LLVMContextRef been used */
93static const char *llvm_triple = NULL;
94static const char *llvm_layout = NULL;
96
97
102
103
104static void llvm_release_context(JitContext *context);
105static void llvm_session_initialize(void);
106static void llvm_shutdown(int code, Datum arg);
107static void llvm_compile_module(LLVMJitContext *context);
109
110static void llvm_create_types(void);
111static void llvm_set_target(void);
112static void llvm_recreate_llvm_context(void);
113static uint64_t llvm_resolve_symbol(const char *name, void *ctx);
114
117
118/* ResourceOwner callbacks to hold JitContexts */
119static void ResOwnerReleaseJitContext(Datum res);
120
122{
123 .name = "LLVM JIT context",
124 .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
125 .release_priority = RELEASE_PRIO_JIT_CONTEXTS,
126 .ReleaseResource = ResOwnerReleaseJitContext,
127 .DebugPrint = NULL /* the default message is fine */
128};
129
130/* Convenience wrappers over ResourceOwnerRemember/Forget */
131static inline void
136static inline void
141
143 .name = "llvmjit",
144 .version = PG_VERSION
145);
146
147
148/*
149 * Initialize LLVM JIT provider.
150 */
151void
158
159
160/*
161 * Every now and then create a new LLVMContextRef. Unfortunately, during every
162 * round of inlining, types may "leak" (they can still be found/used via the
163 * context, but new types will be created the next time in inlining is
164 * performed). To prevent that from slowly accumulating problematic amounts of
165 * memory, recreate the LLVMContextRef we use. We don't want to do so too
166 * often, as that implies some overhead (particularly re-loading the module
167 * summaries / modules is fairly expensive). A future TODO would be to make
168 * this more finegrained and only drop/recreate the LLVMContextRef when we know
169 * there has been inlining. If we can get the size of the context from LLVM
170 * then that might be a better way to determine when to drop/recreate rather
171 * then the usagecount heuristic currently employed.
172 */
173static void
175{
176 if (!llvm_context)
177 elog(ERROR, "Trying to recreate a non-existing context");
178
179 /*
180 * We can only safely recreate the LLVM context if no other code is being
181 * JITed, otherwise we'd release the types in use for that.
182 */
184 {
186 return;
187 }
188
190 {
192 return;
193 }
194
195 /*
196 * Need to reset the modules that the inlining code caches before
197 * disposing of the context. LLVM modules exist within a specific LLVM
198 * context, therefore disposing of the context before resetting the cache
199 * would lead to dangling pointers to modules.
200 */
202
206
207 /*
208 * Re-build cached type information, so code generation code can rely on
209 * that information to be present (also prevents the variables to be
210 * dangling references).
211 */
213}
214
215
216/*
217 * Create a context for JITing work.
218 *
219 * The context, including subsidiary resources, will be cleaned up either when
220 * the context is explicitly released, or when the lifetime of
221 * CurrentResourceOwner ends (usually the end of the current [sub]xact).
222 */
225{
226 LLVMJitContext *context;
227
229
231
233
235
237 sizeof(LLVMJitContext));
238 context->base.flags = jitFlags;
239
240 /* ensure cleanup */
241 context->resowner = CurrentResourceOwner;
243
245
246 return context;
247}
248
249/*
250 * Release resources required by one llvm context.
251 */
252static void
254{
256 ListCell *lc;
257
258 /*
259 * Consider as cleaned up even if we skip doing so below, that way we can
260 * verify the tracking is correct (see llvm_shutdown()).
261 */
263
264 /*
265 * When this backend is exiting, don't clean up LLVM. As an error might
266 * have occurred from within LLVM, we do not want to risk reentering. All
267 * resource cleanup is going to happen through process exit.
268 */
270 return;
271
273
274 if (llvm_jit_context->module)
275 {
277 llvm_jit_context->module = NULL;
278 }
279
280 foreach(lc, llvm_jit_context->handles)
281 {
283
284 {
287
288 LLVMOrcResourceTrackerRemove(jit_handle->resource_tracker);
289 LLVMOrcReleaseResourceTracker(jit_handle->resource_tracker);
290
291 /*
292 * Without triggering cleanup of the string pool, we'd leak
293 * memory. It'd be sufficient to do this far less often, but in
294 * experiments the required time was small enough to just always
295 * do it.
296 */
300 }
301
303 }
304 list_free(llvm_jit_context->handles);
305 llvm_jit_context->handles = NIL;
306
308
309 if (llvm_jit_context->resowner)
311}
312
313/*
314 * Return module which may be modified, e.g. by creating new functions.
315 */
318{
320
321 /*
322 * If there's no in-progress module, create a new one.
323 */
324 if (!context->module)
325 {
326 context->compiled = false;
327 context->module_generation = llvm_generation++;
328 context->module = LLVMModuleCreateWithNameInContext("pg", llvm_context);
329 LLVMSetTarget(context->module, llvm_triple);
330 LLVMSetDataLayout(context->module, llvm_layout);
331 }
332
333 return context->module;
334}
335
336/*
337 * Expand function name to be non-conflicting. This should be used by code
338 * generating code, when adding new externally visible function definitions to
339 * a Module.
340 */
341char *
342llvm_expand_funcname(struct LLVMJitContext *context, const char *basename)
343{
344 Assert(context->module != NULL);
345
346 context->base.instr.created_functions++;
347
348 /*
349 * Previously we used dots to separate, but turns out some tools, e.g.
350 * GDB, don't like that and truncate name.
351 */
352 return psprintf("%s_%zu_%d",
353 basename,
354 context->module_generation,
355 context->counter++);
356}
357
358/*
359 * Return pointer to function funcname, which has to exist. If there's pending
360 * code to be optimized and emitted, do so first.
361 */
362void *
364{
365 ListCell *lc;
366
368
369 /*
370 * If there is a pending / not emitted module, compile and emit now.
371 * Otherwise we might not find the [correct] function.
372 */
373 if (!context->compiled)
374 {
375 llvm_compile_module(context);
376 }
377
378 /*
379 * ORC's symbol table is of *unmangled* symbols. Therefore we don't need
380 * to mangle here.
381 */
382
383 foreach(lc, context->handles)
384 {
385 LLVMJitHandle *handle = (LLVMJitHandle *) lfirst(lc);
386 instr_time starttime;
390
391 INSTR_TIME_SET_CURRENT(starttime);
392
393 addr = 0;
394 error = LLVMOrcLLJITLookup(handle->lljit, &addr, funcname);
395 if (error)
396 elog(ERROR, "failed to look up symbol \"%s\": %s",
398
399 /*
400 * LLJIT only actually emits code the first time a symbol is
401 * referenced. Thus add lookup time to emission time. That's counting
402 * a bit more than with older LLVM versions, but unlikely to ever
403 * matter.
404 */
406 INSTR_TIME_ACCUM_DIFF(context->base.instr.emission_counter,
407 endtime, starttime);
408
409 if (addr)
410 return (void *) (uintptr_t) addr;
411 }
412
413 elog(ERROR, "failed to JIT: %s", funcname);
414
415 return NULL;
416}
417
418/*
419 * Return type of a variable in llvmjit_types.c. This is useful to keep types
420 * in sync between plain C and JIT related code.
421 */
423llvm_pg_var_type(const char *varname)
424{
427
428 /* this'll return a *pointer* to the global */
430 if (!v_srcvar)
431 elog(ERROR, "variable %s not in llvmjit_types.c", varname);
432
434
435 return typ;
436}
437
438/*
439 * Return function type of a variable in llvmjit_types.c. This is useful to
440 * keep function types in sync between C and JITed code.
441 */
443llvm_pg_var_func_type(const char *varname)
444{
447
449 if (!v_srcvar)
450 elog(ERROR, "function %s not in llvmjit_types.c", varname);
451
453
454 return typ;
455}
456
457/*
458 * Return declaration for a function referenced in llvmjit_types.c, adding it
459 * to the module if necessary.
460 *
461 * This is used to make functions discovered via llvm_create_types() known to
462 * the module that's currently being worked on.
463 */
466{
469
470 /* don't repeatedly add function */
472 if (v_fn)
473 return v_fn;
474
476
477 if (!v_srcfn)
478 elog(ERROR, "function %s not in llvmjit_types.c", funcname);
479
481 funcname,
484
485 return v_fn;
486}
487
488/*
489 * Copy attributes from one function to another, for a specific index (an
490 * index can reference return value, function and parameter attributes).
491 */
492static void
511
512/*
513 * Copy all attributes from one function to another. I.e. function, return and
514 * parameters will be copied.
515 */
516void
518{
520
521 /* copy function attributes */
523
525 {
526 /* and the return value attributes */
528 }
529
530 /* and each function parameter's attribute */
532
533 for (int paramidx = 1; paramidx <= param_count; paramidx++)
535}
536
537/*
538 * Return a callable LLVMValueRef for fcinfo.
539 */
542 LLVMBuilderRef builder,
544 FunctionCallInfo fcinfo)
545{
546 char *modname;
547 char *basename;
548 char *funcname;
549
551
553
554 if (modname != NULL && basename != NULL)
555 {
556 /* external function in loadable library */
557 funcname = psprintf("pgextern.%s.%s", modname, basename);
558 }
559 else if (basename != NULL)
560 {
561 /* internal function */
563 }
564 else
565 {
566 /*
567 * Function we don't know to handle, return pointer. We do so by
568 * creating a global constant containing a pointer to the function.
569 * Makes IR more readable.
570 */
572
573 funcname = psprintf("pgoidextern.%u",
574 fcinfo->flinfo->fn_oid);
576 if (v_fn != 0)
577 return l_load(builder, TypePGFunction, v_fn, "");
578
580
586
587 return l_load(builder, TypePGFunction, v_fn, "");
588 }
589
590 /* check if function already has been added */
592 if (v_fn != 0)
593 return v_fn;
594
596
597 return v_fn;
598}
599
600/*
601 * Optimize code in module using the flags set in context.
602 */
603static void
605{
606#if LLVM_VERSION_MAJOR < 17
610 LLVMValueRef func;
612
613 if (context->base.flags & PGJIT_OPT3)
615 else
617
618 /*
619 * Have to create a new pass manager builder every pass through, as the
620 * inliner has some per-builder state. Otherwise one ends up only inlining
621 * a function the first time though.
622 */
626
627 if (context->base.flags & PGJIT_OPT3)
628 {
629 /* TODO: Unscientifically determined threshold */
631 }
632 else
633 {
634 /* we rely on mem2reg heavily, so emit even in the O0 case */
636 }
637
639
640 /*
641 * Do function level optimization. This could be moved to the point where
642 * functions are emitted, to reduce memory usage a bit.
643 */
645 for (func = LLVMGetFirstFunction(context->module);
646 func != NULL;
647 func = LLVMGetNextFunction(func))
651
652 /*
653 * Perform module level optimization. We do so even in the non-optimized
654 * case, so always-inline functions etc get inlined. It's cheap enough.
655 */
658 llvm_mpm);
659 /* always use always-inliner pass */
660 if (!(context->base.flags & PGJIT_OPT3))
662 /* if doing inlining, but no expensive optimization, add inlining pass */
663 if (context->base.flags & PGJIT_INLINE
664 && !(context->base.flags & PGJIT_OPT3))
666 LLVMRunPassManager(llvm_mpm, context->module);
668
670#else
673 const char *passes;
674
675 if (context->base.flags & PGJIT_OPT3)
676 passes = "default<O3>";
677 else if (context->base.flags & PGJIT_INLINE)
678 /* if doing inlining, but no expensive optimization, add inline pass */
679 passes = "default<O0>,mem2reg,inline";
680 else
681 /* default<O0> includes always-inline pass */
682 passes = "default<O0>,mem2reg";
683
685
686#ifdef LLVM_PASS_DEBUG
688#endif
689
690 /* In assertion builds, run the LLVM verify pass. */
691#ifdef USE_ASSERT_CHECKING
693#endif
694
696
698
699 if (err)
700 elog(ERROR, "failed to JIT module: %s", llvm_error_message(err));
701
703#endif
704}
705
706/*
707 * Emit code for the currently pending module.
708 */
709static void
711{
712 LLVMJitHandle *handle;
713 MemoryContext oldcontext;
714 instr_time starttime;
717
718 if (context->base.flags & PGJIT_OPT3)
720 else
722
723 /* perform inlining */
724 if (context->base.flags & PGJIT_INLINE)
725 {
726 INSTR_TIME_SET_CURRENT(starttime);
727 llvm_inline(context->module);
729 INSTR_TIME_ACCUM_DIFF(context->base.instr.inlining_counter,
730 endtime, starttime);
731 }
732
734 {
735 char *filename;
736
737 filename = psprintf("%d.%zu.bc",
738 MyProcPid,
739 context->module_generation);
740 LLVMWriteBitcodeToFile(context->module, filename);
742 }
743
744
745 /* optimize according to the chosen optimization settings */
746 INSTR_TIME_SET_CURRENT(starttime);
747 llvm_optimize_module(context, context->module);
749 INSTR_TIME_ACCUM_DIFF(context->base.instr.optimization_counter,
750 endtime, starttime);
751
753 {
754 char *filename;
755
756 filename = psprintf("%d.%zu.optimized.bc",
757 MyProcPid,
758 context->module_generation);
759 LLVMWriteBitcodeToFile(context->module, filename);
761 }
762
763 handle = (LLVMJitHandle *)
765
766 /*
767 * Emit the code. Note that this can, depending on the optimization
768 * settings, take noticeable resources as code emission executes low-level
769 * instruction combining/selection passes etc. Without optimization a
770 * faster instruction selection mechanism is used.
771 */
772 INSTR_TIME_SET_CURRENT(starttime);
773 {
777
779
780 handle->lljit = compile_orc;
782
783 /*
784 * NB: This doesn't actually emit code. That happens lazily the first
785 * time a symbol defined in the module is requested. Due to that
786 * llvm_get_function() also accounts for emission time.
787 */
788
789 context->module = NULL; /* will be owned by LLJIT */
791 handle->resource_tracker,
792 ts_module);
793
794 if (error)
795 elog(ERROR, "failed to JIT module: %s",
797
798 /* LLVMOrcLLJITAddLLVMIRModuleWithRT takes ownership of the module */
799 }
800
802 INSTR_TIME_ACCUM_DIFF(context->base.instr.emission_counter,
803 endtime, starttime);
804
805 context->module = NULL;
806 context->compiled = true;
807
808 /* remember emitted code for cleanup and lookups */
810 context->handles = lappend(context->handles, handle);
811 MemoryContextSwitchTo(oldcontext);
812
814 (errmsg_internal("time to inline: %.3fs, opt: %.3fs, emit: %.3fs",
815 INSTR_TIME_GET_DOUBLE(context->base.instr.inlining_counter),
816 INSTR_TIME_GET_DOUBLE(context->base.instr.optimization_counter),
817 INSTR_TIME_GET_DOUBLE(context->base.instr.emission_counter)),
818 errhidestmt(true),
819 errhidecontext(true)));
820}
821
822/*
823 * Per session initialization.
824 */
825static void
827{
828 MemoryContext oldcontext;
829 char *error = NULL;
830 char *cpu = NULL;
831 char *features = NULL;
834
836 return;
837
839
843
844 if (llvm_context == NULL)
845 {
847
850 }
851
852 /*
853 * Synchronize types early, as that also includes inferring the target
854 * triple.
855 */
857
858 /*
859 * Extract target information from loaded module.
860 */
862
864 {
865 elog(FATAL, "failed to query triple %s", error);
866 }
867
868 /*
869 * We want the generated code to use all available features. Therefore
870 * grab the host CPU string and detect features of the current CPU. The
871 * latter is needed because some CPU architectures default to enabling
872 * features not all CPUs have (weird, huh).
873 */
876 elog(DEBUG2, "LLVMJIT detected CPU \"%s\", with features \"%s\"",
877 cpu, features);
878
879 opt0_tm =
884 opt3_tm =
889
891 cpu = NULL;
893 features = NULL;
894
895 /* force symbols in main binary to be loaded */
897
898 {
900
902 opt0_tm = 0;
903
905 opt3_tm = 0;
906 }
907
909
911
912 MemoryContextSwitchTo(oldcontext);
913}
914
915static void
917{
918 /*
919 * If llvm_shutdown() is reached while in a fatal-on-oom section an error
920 * has occurred in the middle of LLVM code. It is not safe to call back
921 * into LLVM (which is why a FATAL error was thrown).
922 *
923 * We do need to shutdown LLVM in other shutdown cases, otherwise e.g.
924 * profiling data won't be written out.
925 */
927 {
929 return;
930 }
931
933 elog(PANIC, "LLVMJitContext in use count not 0 at exit (is %zu)",
935
936 {
937 if (llvm_opt3_orc)
938 {
941 }
942 if (llvm_opt0_orc)
943 {
946 }
947 if (llvm_ts_context)
948 {
951 }
952 }
953}
954
955/* helper for llvm_create_types, returning a function's return type */
956static LLVMTypeRef
958{
961
962 /* this'll return a *pointer* to the function */
964 if (!value)
965 elog(ERROR, "function %s is unknown", name);
966
967 typ = LLVMGetFunctionReturnType(value); /* in llvmjit_wrap.cpp */
968
969 return typ;
970}
971
972/*
973 * Load triple & layout from clang emitted file so we're guaranteed to be
974 * compatible.
975 */
976static void
978{
980 elog(ERROR, "failed to extract target information, llvmjit_types.c not loaded");
981
982 if (llvm_triple == NULL)
984
985 if (llvm_layout == NULL)
987}
988
989/*
990 * Load required information, types, function signatures from llvmjit_types.c
991 * and make them available in global variables.
992 *
993 * Those global variables are then used while emitting code.
994 */
995static void
997{
998 char path[MAXPGPATH];
1000 char *msg;
1001
1002 snprintf(path, MAXPGPATH, "%s/%s", pkglib_path, "llvmjit_types.bc");
1003
1004 /* open file */
1006 {
1007 elog(ERROR, "LLVMCreateMemoryBufferWithContentsOfFile(%s) failed: %s",
1008 path, msg);
1009 }
1010
1011 /* eagerly load contents, going to need it all */
1013 {
1014 elog(ERROR, "LLVMParseBitcodeInContext2 of %s failed", path);
1015 }
1017
1018 TypeSizeT = llvm_pg_var_type("TypeSizeT");
1019 TypeDatum = llvm_pg_var_type("TypeDatum");
1020 TypeParamBool = load_return_type(llvm_types_module, "FunctionReturningBool");
1021 TypeStorageBool = llvm_pg_var_type("TypeStorageBool");
1022 TypePGFunction = llvm_pg_var_type("TypePGFunction");
1023 StructNullableDatum = llvm_pg_var_type("StructNullableDatum");
1024 StructExprContext = llvm_pg_var_type("StructExprContext");
1025 StructExprEvalStep = llvm_pg_var_type("StructExprEvalStep");
1026 StructExprState = llvm_pg_var_type("StructExprState");
1027 StructFunctionCallInfoData = llvm_pg_var_type("StructFunctionCallInfoData");
1028 StructMemoryContextData = llvm_pg_var_type("StructMemoryContextData");
1029 StructTupleTableSlot = llvm_pg_var_type("StructTupleTableSlot");
1030 StructHeapTupleTableSlot = llvm_pg_var_type("StructHeapTupleTableSlot");
1031 StructMinimalTupleTableSlot = llvm_pg_var_type("StructMinimalTupleTableSlot");
1032 StructHeapTupleData = llvm_pg_var_type("StructHeapTupleData");
1033 StructHeapTupleHeaderData = llvm_pg_var_type("StructHeapTupleHeaderData");
1034 StructTupleDescData = llvm_pg_var_type("StructTupleDescData");
1035 StructAggState = llvm_pg_var_type("StructAggState");
1036 StructAggStatePerGroupData = llvm_pg_var_type("StructAggStatePerGroupData");
1037 StructAggStatePerTransData = llvm_pg_var_type("StructAggStatePerTransData");
1038 StructPlanState = llvm_pg_var_type("StructPlanState");
1039 StructMinimalTupleData = llvm_pg_var_type("StructMinimalTupleData");
1040
1042 ExecEvalSubroutineTemplate = LLVMGetNamedFunction(llvm_types_module, "ExecEvalSubroutineTemplate");
1043 ExecEvalBoolSubroutineTemplate = LLVMGetNamedFunction(llvm_types_module, "ExecEvalBoolSubroutineTemplate");
1044}
1045
1046/*
1047 * Split a symbol into module / function parts. If the function is in the
1048 * main binary (or an external library) *modname will be NULL.
1049 */
1050void
1051llvm_split_symbol_name(const char *name, char **modname, char **funcname)
1052{
1053 *modname = NULL;
1054 *funcname = NULL;
1055
1056 /*
1057 * Module function names are pgextern.$module.$funcname
1058 */
1059 if (strncmp(name, "pgextern.", strlen("pgextern.")) == 0)
1060 {
1061 /*
1062 * Symbol names cannot contain a ., therefore we can split based on
1063 * first and last occurrence of one.
1064 */
1065 *funcname = strrchr(name, '.');
1066 (*funcname)++; /* jump over . */
1067
1068 *modname = pnstrdup(name + strlen("pgextern."),
1069 *funcname - name - strlen("pgextern.") - 1);
1071
1073 }
1074 else
1075 {
1076 *modname = NULL;
1077 *funcname = pstrdup(name);
1078 }
1079}
1080
1081/*
1082 * Attempt to resolve symbol, so LLVM can emit a reference to it.
1083 */
1084static uint64_t
1085llvm_resolve_symbol(const char *symname, void *ctx)
1086{
1087 uintptr_t addr;
1088 char *funcname;
1089 char *modname;
1090
1091 /*
1092 * macOS prefixes all object level symbols with an underscore. But neither
1093 * dlsym() nor PG's inliner expect that. So undo.
1094 */
1095#if defined(__darwin__)
1096 if (symname[0] != '_')
1097 elog(ERROR, "expected prefixed symbol name, but got \"%s\"", symname);
1098 symname++;
1099#endif
1100
1102
1103 /* functions that aren't resolved to names shouldn't ever get here */
1105
1106 if (modname)
1108 true, NULL);
1109 else
1111
1112 pfree(funcname);
1113 if (modname)
1114 pfree(modname);
1115
1116 /* let LLVM will error out - should never happen */
1117 if (!addr)
1118 elog(WARNING, "failed to resolve name %s", symname);
1119
1120 return (uint64_t) addr;
1121}
1122
1123static LLVMErrorRef
1156
1157/*
1158 * We cannot throw errors through LLVM (without causing a FATAL at least), so
1159 * just use WARNING here. That's OK anyway, as the error is also reported at
1160 * the top level action (with less detail) and there might be multiple
1161 * invocations of errors with details.
1162 *
1163 * This doesn't really happen during normal operation, but in cases like
1164 * symbol resolution breakage. So just using elog(WARNING) is fine.
1165 */
1166static void
1168{
1169 elog(WARNING, "error during JITing: %s",
1171}
1172
1173/*
1174 * Create our own object layer, so we can add event listeners.
1175 */
1204
1205/*
1206 * Create LLJIT instance, using the passed in target machine. Note that the
1207 * target machine afterwards is owned by the LLJIT instance.
1208 */
1209static LLVMOrcLLJITRef
1211{
1212 LLVMOrcLLJITRef lljit;
1218
1222
1225 NULL);
1226
1228 if (error)
1229 elog(ERROR, "failed to create lljit instance: %s",
1231
1234
1235 /*
1236 * Symbol resolution support for symbols in the postgres binary /
1237 * libraries already loaded.
1238 */
1241 0, NULL);
1242 if (error)
1243 elog(ERROR, "failed to create generator: %s",
1246
1247 /*
1248 * Symbol resolution support for "special" functions, e.g. a call into an
1249 * SQL callable function.
1250 */
1251#if LLVM_VERSION_MAJOR > 14
1253#else
1255#endif
1257
1258 return lljit;
1259}
1260
1261static char *
1263{
1265 char *msg = pstrdup(orig);
1266
1268
1269 return msg;
1270}
1271
1272/*
1273 * ResourceOwner callbacks
1274 */
1275static void
1277{
1278 LLVMJitContext *context = (LLVMJitContext *) DatumGetPointer(res);
1279
1280 context->resowner = NULL;
1281 jit_release_context(&context->base);
1282}
#define Assert(condition)
Definition c.h:873
uint32_t uint32
Definition c.h:546
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition dfmgr.c:95
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
int errhidestmt(bool hide_stmt)
Definition elog.c:1445
int errhidecontext(bool hide_ctx)
Definition elog.c:1464
#define FATAL
Definition elog.h:41
#define WARNING
Definition elog.h:36
#define DEBUG2
Definition elog.h:29
#define PANIC
Definition elog.h:42
#define DEBUG1
Definition elog.h:30
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
void err(int eval, const char *fmt,...)
Definition err.c:43
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_array(type, count)
Definition fe_memutils.h:77
void fmgr_symbol(Oid functionId, char **mod, char **fn)
Definition fmgr.c:282
#define PG_MODULE_MAGIC_EXT(...)
Definition fmgr.h:540
int MyProcPid
Definition globals.c:47
char pkglib_path[MAXPGPATH]
Definition globals.c:82
#define funcname
static struct @172 value
#define INSTR_TIME_SET_CURRENT(t)
Definition instr_time.h:122
#define INSTR_TIME_GET_DOUBLE(t)
Definition instr_time.h:190
#define INSTR_TIME_ACCUM_DIFF(x, y, z)
Definition instr_time.h:184
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:316
bool proc_exit_inprogress
Definition ipc.c:41
int i
Definition isn.c:77
bool jit_dump_bitcode
Definition jit.c:35
void jit_release_context(JitContext *context)
Definition jit.c:137
bool jit_profiling_support
Definition jit.c:37
bool jit_debugging_support
Definition jit.c:34
#define PGJIT_OPT3
Definition jit.h:21
#define PGJIT_INLINE
Definition jit.h:22
List * lappend(List *list, void *datum)
Definition list.c:339
void list_free(List *list)
Definition list.c:1546
LLVMTypeRef StructFunctionCallInfoData
Definition llvmjit.c:70
LLVMTypeRef StructMinimalTupleData
Definition llvmjit.c:63
LLVMTypeRef StructMinimalTupleTableSlot
Definition llvmjit.c:68
LLVMTypeRef StructPlanState
Definition llvmjit.c:77
static LLVMContextRef llvm_context
Definition llvmjit.c:95
LLVMJitContext * llvm_create_context(int jitFlags)
Definition llvmjit.c:224
LLVMTypeRef StructExprState
Definition llvmjit.c:73
static LLVMOrcLLJITRef llvm_opt3_orc
Definition llvmjit.c:101
static const char * llvm_triple
Definition llvmjit.c:93
LLVMTypeRef StructExprEvalStep
Definition llvmjit.c:72
LLVMValueRef llvm_pg_func(LLVMModuleRef mod, const char *funcname)
Definition llvmjit.c:465
static void llvm_recreate_llvm_context(void)
Definition llvmjit.c:174
LLVMTypeRef TypeParamBool
Definition llvmjit.c:58
LLVMTypeRef StructMemoryContextData
Definition llvmjit.c:69
static void llvm_set_target(void)
Definition llvmjit.c:977
static LLVMTargetRef llvm_targetref
Definition llvmjit.c:98
static bool llvm_session_initialized
Definition llvmjit.c:85
LLVMTypeRef StructAggStatePerGroupData
Definition llvmjit.c:75
static void llvm_create_types(void)
Definition llvmjit.c:996
LLVMTypeRef llvm_pg_var_type(const char *varname)
Definition llvmjit.c:423
static void ResourceOwnerRememberJIT(ResourceOwner owner, LLVMJitContext *handle)
Definition llvmjit.c:132
static void llvm_session_initialize(void)
Definition llvmjit.c:826
LLVMTypeRef TypeSizeT
Definition llvmjit.c:56
static size_t llvm_jit_context_in_use_count
Definition llvmjit.c:89
static const char * llvm_layout
Definition llvmjit.c:94
LLVMValueRef llvm_function_reference(LLVMJitContext *context, LLVMBuilderRef builder, LLVMModuleRef mod, FunctionCallInfo fcinfo)
Definition llvmjit.c:541
char * llvm_expand_funcname(struct LLVMJitContext *context, const char *basename)
Definition llvmjit.c:342
static void ResOwnerReleaseJitContext(Datum res)
Definition llvmjit.c:1276
void llvm_split_symbol_name(const char *name, char **modname, char **funcname)
Definition llvmjit.c:1051
LLVMTypeRef llvm_pg_var_func_type(const char *varname)
Definition llvmjit.c:443
LLVMTypeRef StructTupleTableSlot
Definition llvmjit.c:65
LLVMTypeRef TypeStorageBool
Definition llvmjit.c:59
static LLVMTypeRef load_return_type(LLVMModuleRef mod, const char *name)
Definition llvmjit.c:957
LLVMTypeRef TypeDatum
Definition llvmjit.c:57
static size_t llvm_generation
Definition llvmjit.c:86
static LLVMOrcLLJITRef llvm_opt0_orc
Definition llvmjit.c:100
static LLVMOrcObjectLayerRef llvm_create_object_layer(void *Ctx, LLVMOrcExecutionSessionRef ES, const char *Triple)
Definition llvmjit.c:1177
static void ResourceOwnerForgetJIT(ResourceOwner owner, LLVMJitContext *handle)
Definition llvmjit.c:137
static void llvm_compile_module(LLVMJitContext *context)
Definition llvmjit.c:710
LLVMTypeRef StructHeapTupleTableSlot
Definition llvmjit.c:67
static char * llvm_error_message(LLVMErrorRef error)
Definition llvmjit.c:1262
static LLVMOrcLLJITRef llvm_create_jit_instance(LLVMTargetMachineRef tm)
Definition llvmjit.c:1210
static LLVMModuleRef llvm_types_module
Definition llvmjit.c:83
static void llvm_shutdown(int code, Datum arg)
Definition llvmjit.c:916
static LLVMOrcThreadSafeContextRef llvm_ts_context
Definition llvmjit.c:99
static const ResourceOwnerDesc jit_resowner_desc
Definition llvmjit.c:121
#define LLVMJIT_LLVM_CONTEXT_REUSE_MAX
Definition llvmjit.c:45
static LLVMErrorRef llvm_resolve_symbols(LLVMOrcDefinitionGeneratorRef GeneratorObj, void *Ctx, LLVMOrcLookupStateRef *LookupState, LLVMOrcLookupKind Kind, LLVMOrcJITDylibRef JD, LLVMOrcJITDylibLookupFlags JDLookupFlags, LLVMOrcCLookupSet LookupSet, size_t LookupSetSize)
Definition llvmjit.c:1124
static void llvm_copy_attributes_at_index(LLVMValueRef v_from, LLVMValueRef v_to, uint32 index)
Definition llvmjit.c:493
LLVMModuleRef llvm_mutable_module(LLVMJitContext *context)
Definition llvmjit.c:317
LLVMTypeRef StructAggState
Definition llvmjit.c:74
LLVMTypeRef TypePGFunction
Definition llvmjit.c:60
LLVMTypeRef StructTupleDescData
Definition llvmjit.c:64
LLVMValueRef AttributeTemplate
Definition llvmjit.c:79
static size_t llvm_llvm_context_reuse_count
Definition llvmjit.c:92
LLVMTypeRef StructExprContext
Definition llvmjit.c:71
static void llvm_optimize_module(LLVMJitContext *context, LLVMModuleRef module)
Definition llvmjit.c:604
static uint64_t llvm_resolve_symbol(const char *name, void *ctx)
Definition llvmjit.c:1085
LLVMTypeRef StructHeapTupleHeaderData
Definition llvmjit.c:66
static void llvm_log_jit_error(void *ctx, LLVMErrorRef error)
Definition llvmjit.c:1167
LLVMTypeRef StructHeapTupleData
Definition llvmjit.c:62
static void llvm_release_context(JitContext *context)
Definition llvmjit.c:253
void * llvm_get_function(LLVMJitContext *context, const char *funcname)
Definition llvmjit.c:363
LLVMTypeRef StructNullableDatum
Definition llvmjit.c:61
LLVMValueRef ExecEvalSubroutineTemplate
Definition llvmjit.c:80
LLVMValueRef ExecEvalBoolSubroutineTemplate
Definition llvmjit.c:81
void _PG_jit_provider_init(JitProviderCallbacks *cb)
Definition llvmjit.c:152
LLVMTypeRef StructAggStatePerTransData
Definition llvmjit.c:76
void llvm_copy_attributes(LLVMValueRef v_from, LLVMValueRef v_to)
Definition llvmjit.c:517
void llvm_enter_fatal_on_oom(void)
bool llvm_in_fatal_on_oom(void)
void llvm_assert_in_fatal_section(void)
void llvm_reset_after_error(void)
void llvm_leave_fatal_on_oom(void)
bool llvm_compile_expr(ExprState *state)
void llvm_inline(LLVMModuleRef M)
void llvm_inline_reset_caches(void)
LLVMTypeRef LLVMGetFunctionReturnType(LLVMValueRef r)
LLVMTypeRef LLVMGetFunctionType(LLVMValueRef r)
static struct pg_tm tm
Definition localtime.c:104
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1266
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
MemoryContext TopMemoryContext
Definition mcxt.c:166
char * pnstrdup(const char *in, Size len)
Definition mcxt.c:1792
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
void * arg
#define MAXPGPATH
static char * filename
Definition pg_dumpall.c:120
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define snprintf
Definition port.h:260
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
static int fb(int x)
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
void ResourceOwnerForget(ResourceOwner owner, Datum value, const ResourceOwnerDesc *kind)
Definition resowner.c:561
void ResourceOwnerRemember(ResourceOwner owner, Datum value, const ResourceOwnerDesc *kind)
Definition resowner.c:521
void ResourceOwnerEnlarge(ResourceOwner owner)
Definition resowner.c:449
#define RELEASE_PRIO_JIT_CONTEXTS
Definition resowner.h:66
@ RESOURCE_RELEASE_BEFORE_LOCKS
Definition resowner.h:54
static void error(void)
PGFunction fn_addr
Definition fmgr.h:58
Oid fn_oid
Definition fmgr.h:59
FmgrInfo * flinfo
Definition fmgr.h:87
JitProviderCompileExprCB compile_expr
Definition jit.h:78
JitProviderResetAfterErrorCB reset_after_error
Definition jit.h:76
JitProviderReleaseContextCB release_context
Definition jit.h:77
LLVMOrcLLJITRef lljit
Definition llvmjit.c:50
LLVMOrcResourceTrackerRef resource_tracker
Definition llvmjit.c:51
const char * name
Definition resowner.h:93
Definition type.h:96
Definition c.h:760
const char * name