forked from nextgres/uplpgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupl_compile_expr.c
More file actions
4859 lines (4250 loc) · 151 KB
/
Copy pathupl_compile_expr.c
File metadata and controls
4859 lines (4250 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* uplpgsql_expr.c
* Expression-level compilation: walk PG Expr trees and emit native
* LLVM IR, bypassing the ExprEvalStep interpreter entirely.
*
* This is the heart of uplpgsql's performance optimization. It
* implements a three-tier compilation strategy for PL/pgSQL expressions:
*
* Tier 1 — Native LLVM instructions (zero function call overhead):
* int4: add, sub, mul (overflow-checked via llvm.sadd.with.overflow),
* sdiv, srem (with division-by-zero and MIN/-1 checks), abs, neg
* int8: same as int4 but with 64-bit variants
* int4/int8 cross-type: operands widened via sext, result is int8
* float8: fadd, fsub, fmul, fdiv, fneg, fabs (via select on fcmp)
* bool: and, or, not via i1 logic ops
* casts: int→float (sitofp), float4→float8 (fpext), numeric const
* (compile-time evaluation)
*
* Variable access is via GEP chains:
* estate → plstate → datums[dno] → var.value
* Record fields use RT_GET_RECFIELD runtime helper.
*
* Tier 2 — Direct PG function pointer call (fmgr bypass):
* At compile time, resolves function OID via fmgr_info() to get
* the C function pointer. In IR, allocates FunctionCallInfoBaseData
* on the LLVM stack (in entry block to prevent loop stack growth),
* fills in arguments, and calls the function directly.
*
* Pass-by-value results: stored directly via GEP.
* Pass-by-reference results: stored via RT_ASSIGN_VAR_DATUM which
* handles freeval cleanup, or RT_COPY_ASSIGN_VAR_DATUM for constants
* and variable references that need datumCopy() first.
*
* Safety: only built-in (system catalog) functions are eligible.
* User-defined functions are excluded because their pointers can
* change via CREATE OR REPLACE.
*
* Strict functions: emit null-check branch chain with PHI merge.
*
* Tier 3 — Runtime helper fallback:
* uplpgsql_rt_assign_expr, uplpgsql_rt_eval_bool, etc.
* When compile-time SPI_prepare succeeds but the expression can't
* be inlined, the plan is freed so the runtime path can re-prepare
* with exec_simple_check_plan (avoiding 30x+ SPI overhead).
*
* Public API (called from uplpgsql_compile.c):
* uplpgsql_try_compile_assign() — try to inline an assignment
* uplpgsql_try_compile_bool() — try to inline a boolean condition
*
*
* Copyright (c) 2003-2014, Jonah H. Harris <[email protected]>
* Copyright (c) 2014-2026, NEXTGRES, LLC. <[email protected]>
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain a
* copy of the License in LICENSE or at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
*-------------------------------------------------------------------------
*/
#include "upl_common.h"
#include <math.h> /* INFINITY */
#include "utils/datum.h" /* datumCopy */
/*
* Convenience macros for accessing PL/pgSQL-specific lang_data fields.
*/
#define ctx_lang(ctx) UPLPGSQL_LANG_DATA(ctx)
#define ctx_plstate(ctx) (ctx_lang(ctx)->plstate_ref)
#define ctx_func(ctx) (ctx_lang(ctx)->uplpgsql_func)
#define ctx_native_arrays(ctx) (ctx_lang(ctx)->native_arrays)
#define ctx_num_native_arrays(ctx) (ctx_lang(ctx)->num_native_arrays)
#include "access/transam.h"
#include "catalog/pg_type_d.h"
#include "utils/memutils.h"
#include "executor/spi_priv.h"
#include "nodes/nodeFuncs.h"
#include "nodes/primnodes.h"
#include "nodes/parsenodes.h"
#include "utils/builtins.h"
#include "utils/expandedrecord.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
/*
* Struct offsets for GEP-based variable access.
*
* These are computed at C compile time via offsetof() and embedded as
* LLVM i64 constants in the generated IR. They allow the JIT'd code to
* navigate the PL/pgSQL execution state structs without needing LLVM
* struct type definitions — we treat everything as byte arrays and use
* offset-based GEPs (similar to the pattern used by NVC's LLVM JIT).
*
* This approach is fragile to struct layout changes, which is why
* PGXS header dependency tracking is important (see CLAUDE.md build notes).
*/
#define OFF_ESTATE_PLSTATE offsetof(UPLpgSQL_exec_state, uplpgsql_estate)
#define OFF_EXECSTATE_DATUMS offsetof(UPLpgSQL_execstate, datums)
#define OFF_VAR_VALUE offsetof(UPLpgSQL_var, value)
#define OFF_VAR_ISNULL offsetof(UPLpgSQL_var, isnull)
#define OFF_VAR_FREEVAL offsetof(UPLpgSQL_var, freeval)
/* FunctionCallInfoBaseData offsets for fmgr bypass */
#define OFF_FCI_FLINFO offsetof(FunctionCallInfoBaseData, flinfo)
#define OFF_FCI_CONTEXT offsetof(FunctionCallInfoBaseData, context)
#define OFF_FCI_RESULTINFO offsetof(FunctionCallInfoBaseData, resultinfo)
#define OFF_FCI_COLLATION offsetof(FunctionCallInfoBaseData, fncollation)
#define OFF_FCI_ISNULL offsetof(FunctionCallInfoBaseData, isnull)
#define OFF_FCI_NARGS offsetof(FunctionCallInfoBaseData, nargs)
#define OFF_FCI_ARGS offsetof(FunctionCallInfoBaseData, args)
#define SIZE_NULLABLE_DATUM sizeof(NullableDatum)
#define OFF_ND_VALUE offsetof(NullableDatum, value)
#define OFF_ND_ISNULL offsetof(NullableDatum, isnull)
/* ExpandedRecordHeader offsets for inline record field access (Phase 5d) */
#define OFF_REC_ERH offsetof(UPLpgSQL_rec, erh)
#define OFF_ERH_FLAGS offsetof(ExpandedRecordHeader, flags)
#define OFF_ERH_DVALUES offsetof(ExpandedRecordHeader, dvalues)
#define OFF_ERH_DNULLS offsetof(ExpandedRecordHeader, dnulls)
/*
* Type classification for the expression compiler.
*
* Used by uplpgsql_classify_expr() to recursively determine whether an
* entire expression tree can be compiled to Tier 1 native instructions.
* Only expressions where ALL nodes classify to a known type (not UNKNOWN)
* are eligible for Tier 1 compilation. UNKNOWN falls through to Tier 2
* or Tier 3.
*/
typedef enum ExprTypeClass
{
EXPR_TYPE_INT4,
EXPR_TYPE_INT8,
EXPR_TYPE_FLOAT8,
EXPR_TYPE_BOOL,
EXPR_TYPE_UNKNOWN /* not natively inlineable */
} ExprTypeClass;
/* Forward declarations */
static Expr *uplpgsql_prepare_and_get_expr(UPLpgSQL_compile_ctx *ctx,
UPLpgSQL_expr *expr);
static ExprTypeClass uplpgsql_classify_expr(Expr *expr);
static LLVMValueRef uplpgsql_compile_expr_datum(UPLpgSQL_compile_ctx *ctx,
Expr *expr,
LLVMValueRef estate_ref,
ExprTypeClass *result_type);
static LLVMValueRef uplpgsql_compile_expr_bool(UPLpgSQL_compile_ctx *ctx,
Expr *expr,
LLVMValueRef estate_ref);
/* Tier 2: fmgr bypass */
static bool uplpgsql_can_fmgr_compile(Expr *expr);
static LLVMValueRef uplpgsql_compile_expr_fmgr(UPLpgSQL_compile_ctx *ctx,
Expr *expr,
LLVMValueRef estate_ref);
static LLVMValueRef uplpgsql_compile_expr_fmgr_full(UPLpgSQL_compile_ctx *ctx,
Expr *expr,
LLVMValueRef estate_ref,
LLVMValueRef *isnull_out);
/* Helpers */
static inline LLVMBasicBlockRef
expr_append_block(UPLpgSQL_compile_ctx *ctx, const char *name)
{
return LLVMAppendBasicBlockInContext(ctx->context, ctx->function, name);
}
/*
* Look up whether a datum number corresponds to a native local array
* (one that passed escape analysis in Phase 7).
* Returns the UPLpgSQL_native_array metadata if found, NULL otherwise.
* When NULL, the caller should use the standard PG array path
* (RT_ARRAY_GET_ELEMENT / RT_ARRAY_SET_ELEMENT).
*/
static UPLpgSQL_native_array *
find_native_array(UPLpgSQL_compile_ctx *ctx, int dno)
{
int i;
for (i = 0; i < ctx_num_native_arrays(ctx); i++)
{
if (ctx_native_arrays(ctx)[i].dno == dno)
return &ctx_native_arrays(ctx)[i];
}
return NULL;
}
/*
* Resolve array element type info at compile time and emit LLVM constants.
* Avoids repeated get_element_type()/get_typlenbyvalalign() at runtime.
*/
typedef struct ArrayTypeInfo
{
LLVMValueRef typlen_val; /* i32: array type length (-1 for varlena) */
LLVMValueRef elemtype_val; /* i32: element type OID */
LLVMValueRef elmlen_val; /* i16: element length */
LLVMValueRef elmbyval_val; /* i1: element pass-by-value */
LLVMValueRef elmalign_val; /* i8: element alignment */
} ArrayTypeInfo;
static void
resolve_array_type_info(UPLpgSQL_compile_ctx *ctx, int array_dno,
ArrayTypeInfo *info)
{
UPLpgSQL_var *arrayvar;
Oid elemtype;
int16 elmlen;
bool elmbyval;
char elmalign;
arrayvar = (UPLpgSQL_var *) ctx_func(ctx)->datums[array_dno];
elemtype = get_element_type(arrayvar->datatype->typoid);
get_typlenbyvalalign(elemtype, &elmlen, &elmbyval, &elmalign);
info->typlen_val = LLVMConstInt(ctx->types[UPLPGSQL_INT32],
arrayvar->datatype->typlen, true);
info->elemtype_val = LLVMConstInt(ctx->types[UPLPGSQL_INT32],
elemtype, false);
info->elmlen_val = LLVMConstInt(ctx->types[UPLPGSQL_INT16],
elmlen, true);
info->elmbyval_val = LLVMConstInt(ctx->types[UPLPGSQL_INT1],
elmbyval ? 1 : 0, false);
info->elmalign_val = LLVMConstInt(ctx->types[UPLPGSQL_INT8],
elmalign, false);
}
/* ================================================================
* Variable access via GEP
* ================================================================
*/
/*
* Emit IR to load a variable's Datum (i64) via struct offset GEPs.
*/
static LLVMValueRef
uplpgsql_emit_load_var_datum(UPLpgSQL_compile_ctx *ctx,
LLVMValueRef estate_ref, int dno)
{
LLVMBuilderRef builder = ctx->builder;
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i64 = ctx->types[UPLPGSQL_INT64];
LLVMTypeRef ptr = ctx->types[UPLPGSQL_PTR];
LLVMValueRef off, gep, plstate, datums, datum;
/* estate->uplpgsql_estate */
off = LLVMConstInt(i64, OFF_ESTATE_PLSTATE, false);
gep = LLVMBuildGEP2(builder, i8, estate_ref, &off, 1, "plstate.ptr");
plstate = LLVMBuildLoad2(builder, ptr, gep, "plstate");
/* plstate->datums */
off = LLVMConstInt(i64, OFF_EXECSTATE_DATUMS, false);
gep = LLVMBuildGEP2(builder, i8, plstate, &off, 1, "datums.ptr");
datums = LLVMBuildLoad2(builder, ptr, gep, "datums");
/* datums[dno] */
off = LLVMConstInt(i64, dno, false);
gep = LLVMBuildGEP2(builder, ptr, datums, &off, 1, "datum.slot");
datum = LLVMBuildLoad2(builder, ptr, gep, "datum");
/* datum->value */
off = LLVMConstInt(i64, OFF_VAR_VALUE, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "value.ptr");
return LLVMBuildLoad2(builder, i64, gep, "var.datum");
}
/*
* Emit IR to load a Datum from a param, handling both simple variables
* and RECFIELD datums. For RECFIELD, emits a call to RT_GET_RECFIELD;
* for plain vars, uses the fast GEP path.
*
* Phase 5d optimization: when the parent record has a compile-time erh
* (installed by uplpgsql_compile_fors), we resolve the field number at
* compile time and emit inline LLVM IR to GEP directly into
* erh->dvalues[fnumber-1], with a slow-path fallback to RT_GET_RECFIELD.
*/
static LLVMValueRef
uplpgsql_emit_load_param_datum(UPLpgSQL_compile_ctx *ctx,
LLVMValueRef estate_ref, int dno)
{
UPLpgSQL_datum *d = ctx_func(ctx)->datums[dno];
UPLpgSQL_native_array *na;
/*
* Whole-datum read of a native array (y := x, f(x), ...). The live
* contents are in flat memory and the variable's Datum is stale, so
* marshal it back before the load. This is the only path by which a
* native array is read as a whole Datum — subscript reads never reach
* here, they GEP into data_ptr via the T_SubscriptingRef case — so the
* cost falls only on genuine escapes.
*/
na = find_native_array(ctx, dno);
if (na != NULL)
{
elog(DEBUG1, "uplpgsql: native array to_datum dno %d (whole-datum read)",
dno);
uplpgsql_emit_sync_native_array(ctx, na);
}
/*
* Promise datums (TG_OP, TG_WHEN, etc.) need runtime resolution via
* exec_eval_datum → uplpgsql_fulfill_promise. We can't load them
* with a direct GEP because the value isn't populated until first access.
*/
if (d->dtype == UPLPGSQL_DTYPE_PROMISE)
{
LLVMValueRef args[] = {
estate_ref,
LLVMConstInt(ctx->types[UPLPGSQL_INT32], dno, false)
};
return LLVMBuildCall2(ctx->builder,
ctx->rt_fntypes[RT_GET_RECFIELD],
ctx->rt_funcs[RT_GET_RECFIELD],
args, 2, "promise.datum");
}
if (d->dtype == UPLPGSQL_DTYPE_RECFIELD)
{
UPLpgSQL_recfield *recfield = (UPLpgSQL_recfield *) d;
UPLpgSQL_rec *rec;
rec = (UPLpgSQL_rec *) ctx_func(ctx)->datums[recfield->recparentno];
/*
* Fast path: parent record has a compile-time erh (Phase 5d).
* Resolve the field number now and inline the expanded record
* field access directly as LLVM IR.
*
* Inlines: load rec → load erh → check erh != NULL &&
* (flags & ER_FLAG_DVALUES_VALID) → GEP erh->dvalues[fnumber-1].
* Falls back to RT_GET_RECFIELD for the slow path.
*/
if (rec->erh != NULL)
{
ExpandedRecordFieldInfo finfo;
if (expanded_record_lookup_field(rec->erh,
recfield->fieldname,
&finfo))
{
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i32 = ctx->types[UPLPGSQL_INT32];
LLVMTypeRef i64 = ctx->types[UPLPGSQL_INT64];
LLVMTypeRef ptr = ctx->types[UPLPGSQL_PTR];
LLVMBuilderRef builder = ctx->builder;
LLVMValueRef off, gep, plstate, datums, datum;
LLVMValueRef erh_ptr, flags_val, dvalues_ptr, field_datum;
LLVMValueRef cond_erh, cond_flags, cond;
LLVMBasicBlockRef bb_fast, bb_slow, bb_merge;
LLVMValueRef phi;
int field_idx = finfo.fnumber - 1; /* 0-based array index */
/* Navigate: estate → plstate → datums[rec_dno] → rec */
off = LLVMConstInt(i64, OFF_ESTATE_PLSTATE, false);
gep = LLVMBuildGEP2(builder, i8, estate_ref, &off, 1, "rf.plstate.ptr");
plstate = LLVMBuildLoad2(builder, ptr, gep, "rf.plstate");
off = LLVMConstInt(i64, OFF_EXECSTATE_DATUMS, false);
gep = LLVMBuildGEP2(builder, i8, plstate, &off, 1, "rf.datums.ptr");
datums = LLVMBuildLoad2(builder, ptr, gep, "rf.datums");
off = LLVMConstInt(i64, recfield->recparentno, false);
gep = LLVMBuildGEP2(builder, ptr, datums, &off, 1, "rf.rec.slot");
datum = LLVMBuildLoad2(builder, ptr, gep, "rf.rec");
/* Load erh = rec->erh */
off = LLVMConstInt(i64, OFF_REC_ERH, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "rf.erh.ptr");
erh_ptr = LLVMBuildLoad2(builder, ptr, gep, "rf.erh");
/* Check erh != NULL */
cond_erh = LLVMBuildICmp(builder, LLVMIntNE, erh_ptr,
LLVMConstNull(ptr), "rf.erh.notnull");
/* Check erh->flags & ER_FLAG_DVALUES_VALID (0x0004) */
off = LLVMConstInt(i64, OFF_ERH_FLAGS, false);
gep = LLVMBuildGEP2(builder, i8, erh_ptr, &off, 1, "rf.flags.ptr");
flags_val = LLVMBuildLoad2(builder, i32, gep, "rf.flags");
cond_flags = LLVMBuildICmp(builder, LLVMIntNE,
LLVMBuildAnd(builder, flags_val,
LLVMConstInt(i32, 0x0004, false), "rf.flags.masked"),
LLVMConstInt(i32, 0, false), "rf.dvalues.valid");
cond = LLVMBuildAnd(builder, cond_erh, cond_flags, "rf.fast.ok");
/* Branch: fast inline path vs slow runtime call */
bb_fast = LLVMAppendBasicBlockInContext(ctx->context,
ctx->function, "rf.fast");
bb_slow = LLVMAppendBasicBlockInContext(ctx->context,
ctx->function, "rf.slow");
bb_merge = LLVMAppendBasicBlockInContext(ctx->context,
ctx->function, "rf.merge");
LLVMBuildCondBr(builder, cond, bb_fast, bb_slow);
/* Fast path: erh->dvalues[fnumber-1] */
LLVMPositionBuilderAtEnd(builder, bb_fast);
off = LLVMConstInt(i64, OFF_ERH_DVALUES, false);
gep = LLVMBuildGEP2(builder, i8, erh_ptr, &off, 1, "rf.dvalues.ptr");
dvalues_ptr = LLVMBuildLoad2(builder, ptr, gep, "rf.dvalues");
off = LLVMConstInt(i64, field_idx, false);
gep = LLVMBuildGEP2(builder, i64, dvalues_ptr, &off, 1, "rf.field.ptr");
field_datum = LLVMBuildLoad2(builder, i64, gep, "rf.field.datum");
LLVMBuildBr(builder, bb_merge);
/* Slow path: call RT_GET_RECFIELD */
LLVMPositionBuilderAtEnd(builder, bb_slow);
{
LLVMValueRef slow_args[] = {
estate_ref,
LLVMConstInt(i32, dno, false)
};
LLVMValueRef slow_result = LLVMBuildCall2(builder,
ctx->rt_fntypes[RT_GET_RECFIELD],
ctx->rt_funcs[RT_GET_RECFIELD],
slow_args, 2, "rf.slow.datum");
LLVMBuildBr(builder, bb_merge);
/* Merge with PHI */
LLVMPositionBuilderAtEnd(builder, bb_merge);
phi = LLVMBuildPhi(builder, i64, "rf.datum");
{
LLVMValueRef vals[] = { field_datum, slow_result };
LLVMBasicBlockRef bbs[] = { bb_fast, bb_slow };
LLVMAddIncoming(phi, vals, bbs, 2);
}
return phi;
}
}
}
/* Slow path: call exec_eval_datum via RT_GET_RECFIELD */
{
LLVMValueRef args[] = {
estate_ref,
LLVMConstInt(ctx->types[UPLPGSQL_INT32], dno, false)
};
return LLVMBuildCall2(ctx->builder,
ctx->rt_fntypes[RT_GET_RECFIELD],
ctx->rt_funcs[RT_GET_RECFIELD],
args, 2, "recfield.datum");
}
}
return uplpgsql_emit_load_var_datum(ctx, estate_ref, dno);
}
/*
* Emit IR to check if a param is NULL. For RECFIELD datums we
* conservatively return false (not-null) — matching the existing Tier 1
* behavior of not null-checking variable loads.
*/
static LLVMValueRef
uplpgsql_emit_load_param_isnull(UPLpgSQL_compile_ctx *ctx,
LLVMValueRef estate_ref, int dno)
{
UPLpgSQL_datum *d = ctx_func(ctx)->datums[dno];
LLVMBuilderRef builder = ctx->builder;
LLVMTypeRef i1 = ctx->types[UPLPGSQL_INT1];
UPLpgSQL_native_array *na;
if (d->dtype == UPLPGSQL_DTYPE_RECFIELD ||
d->dtype == UPLPGSQL_DTYPE_PROMISE)
return LLVMConstInt(i1, 0, false);
/*
* A native array's variable carries a stale isnull — it is still the
* declared-NULL initial value if the array was only ever populated in
* flat memory. Callers load isnull and the datum separately (and
* isnull first), so sync here as well as in the datum load; otherwise
* a live array reads back as NULL.
*/
na = find_native_array(ctx, dno);
if (na != NULL)
uplpgsql_emit_sync_native_array(ctx, na);
/* For plain vars: load datum->isnull */
{
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i64 = ctx->types[UPLPGSQL_INT64];
LLVMTypeRef ptr = ctx->types[UPLPGSQL_PTR];
LLVMValueRef off, gep, plstate, datums, datum, isnull_raw;
off = LLVMConstInt(i64, OFF_ESTATE_PLSTATE, false);
gep = LLVMBuildGEP2(builder, i8, estate_ref, &off, 1, "plstate.ptr");
plstate = LLVMBuildLoad2(builder, ptr, gep, "plstate");
off = LLVMConstInt(i64, OFF_EXECSTATE_DATUMS, false);
gep = LLVMBuildGEP2(builder, i8, plstate, &off, 1, "datums.ptr");
datums = LLVMBuildLoad2(builder, ptr, gep, "datums");
off = LLVMConstInt(i64, dno, false);
gep = LLVMBuildGEP2(builder, ptr, datums, &off, 1, "datum.slot");
datum = LLVMBuildLoad2(builder, ptr, gep, "datum");
off = LLVMConstInt(i64, OFF_VAR_ISNULL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "isnull.ptr");
isnull_raw = LLVMBuildLoad2(builder, i8, gep, "isnull.raw");
return LLVMBuildTrunc(builder, isnull_raw, i1, "isnull");
}
}
/*
* Emit a test for "element idx of this native array is NULL".
*
* nulls_ptr holds either a per-element bool array or NULL when no element is
* null, so the flags load has to be guarded. Returns an i1.
*/
static LLVMValueRef
emit_native_array_elem_isnull(UPLpgSQL_compile_ctx *ctx,
UPLpgSQL_native_array *na, LLVMValueRef idx0)
{
LLVMBuilderRef builder = ctx->builder;
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i1 = ctx->types[UPLPGSQL_INT1];
LLVMValueRef nulls, has_nulls, gep, flag, phi;
LLVMValueRef vals[2];
LLVMBasicBlockRef blocks[2];
LLVMBasicBlockRef load_bb, done_bb, from_bb;
nulls = LLVMBuildLoad2(builder, ctx->types[UPLPGSQL_PTR],
na->nulls_ptr, "na.nulls");
has_nulls = LLVMBuildICmp(builder, LLVMIntNE, nulls,
LLVMConstNull(ctx->types[UPLPGSQL_PTR]),
"na.has.nulls");
load_bb = expr_append_block(ctx, "na.nulls.load");
done_bb = expr_append_block(ctx, "na.nulls.done");
from_bb = LLVMGetInsertBlock(builder);
LLVMBuildCondBr(builder, has_nulls, load_bb, done_bb);
LLVMPositionBuilderAtEnd(builder, load_bb);
gep = LLVMBuildGEP2(builder, i8, nulls, &idx0, 1, "na.null.ptr");
flag = LLVMBuildLoad2(builder, i8, gep, "na.null.raw");
flag = LLVMBuildTrunc(builder, flag, i1, "na.null.flag");
LLVMBuildBr(builder, done_bb);
LLVMPositionBuilderAtEnd(builder, done_bb);
phi = LLVMBuildPhi(builder, i1, "na.elem.isnull");
vals[0] = LLVMConstInt(i1, 0, false);
blocks[0] = from_bb;
vals[1] = flag;
blocks[1] = load_bb;
LLVMAddIncoming(phi, vals, blocks, 2);
return phi;
}
/*
* OR together the isnull flags of every leaf of a Tier 1 expression.
*
* Every operator Tier 1 accepts is strict — int4/int8 arithmetic, the
* comparison operators, and the numeric casts all return NULL if any input is
* NULL — so an expression is NULL exactly when some leaf is. That lets the
* caller decide nullness once, up front, instead of threading an isnull flag
* through each node. uplpgsql_classify_expr() keeps the non-strict operators
* (AND/OR/NOT) out of Tier 1 precisely so this holds.
*
* Constants are never null here: classify_expr() rejects a null Const.
*
* Returns an i1, or NULL if the expression has no nullable leaf at all (a
* constant expression), letting the caller skip the check entirely.
*/
static LLVMValueRef
tier1_expr_any_null(UPLpgSQL_compile_ctx *ctx, Expr *expr,
LLVMValueRef estate_ref)
{
LLVMBuilderRef builder = ctx->builder;
if (expr == NULL)
return NULL;
switch (nodeTag(expr))
{
case T_Const:
/* classify_expr() rejects null Consts, so this is never null */
return NULL;
case T_Param:
{
Param *p = (Param *) expr;
return uplpgsql_emit_load_param_isnull(ctx, estate_ref,
p->paramid - 1);
}
case T_RelabelType:
return tier1_expr_any_null(ctx, ((RelabelType *) expr)->arg,
estate_ref);
case T_SubscriptingRef:
{
/*
* A native array read is NULL when the array or the subscript
* is NULL — and also whenever the subscript is out of range.
*
* PostgreSQL returns NULL for a[i] outside the array's bounds,
* for a[i] on a NULL or empty array, and for a single-subscript
* read of a multi-dimensional array. All three are runtime
* facts, and this function already returns a runtime i1, so
* folding them in here is what makes them come out as SQL NULL:
* the caller stores NULL whenever this is true.
*
* It also means the value path below is reached only for a
* subscript that is definitely in range, so it needs no bounds
* check of its own.
*
* len < 0 -> not a 1-D array (from_datum's marker)
* i < lb -> below the lower bound
* i > lb+len-1-> past the end (len 0 catches NULL/empty)
*/
SubscriptingRef *s = (SubscriptingRef *) expr;
LLVMValueRef acc = NULL;
ListCell *lc;
UPLpgSQL_native_array *na = NULL;
if (IsA(s->refexpr, Param) &&
list_length(s->refupperindexpr) == 1)
na = find_native_array(ctx,
((Param *) s->refexpr)->paramid - 1);
/*
* Do NOT ask whether the array variable itself is NULL when it
* is native.
*
* That question goes through uplpgsql_emit_load_param_isnull(),
* which treats reading a native array's variable as a
* whole-datum escape and marshals the entire array back out to
* its Datum first. In a loop over a[i] that is a full array
* rebuild *per iteration* — it made a 1000-element read loop
* ~100x slower than the interpreter.
*
* It is also unnecessary: from_datum reports len 0 for a NULL
* array, so the range test below already answers NULL for it.
*/
if (na == NULL)
acc = tier1_expr_any_null(ctx, s->refexpr, estate_ref);
foreach(lc, s->refupperindexpr)
{
LLVMValueRef v = tier1_expr_any_null(ctx,
(Expr *) lfirst(lc),
estate_ref);
if (v == NULL)
continue;
acc = (acc == NULL) ? v
: LLVMBuildOr(builder, acc, v, "anynull");
}
if (na != NULL)
{
LLVMTypeRef i32 = ctx->types[UPLPGSQL_INT32];
ExprTypeClass idx_class;
LLVMValueRef idx, len, lb, oob;
idx = uplpgsql_compile_expr_datum(ctx,
(Expr *) linitial(s->refupperindexpr), estate_ref,
&idx_class);
if (idx_class == EXPR_TYPE_INT8)
idx = LLVMBuildTrunc(builder, idx, i32, "na.idx32");
len = LLVMBuildLoad2(builder, i32, na->len_ptr, "na.len");
lb = LLVMBuildLoad2(builder, i32, na->lb_ptr, "na.lb");
/* len < 0: not a 1-D array, so a[i] is NULL */
oob = LLVMBuildICmp(builder, LLVMIntSLT, len,
LLVMConstInt(i32, 0, true),
"na.notflat");
/* i < lb */
oob = LLVMBuildOr(builder, oob,
LLVMBuildICmp(builder, LLVMIntSLT, idx, lb,
"na.below"),
"na.oob");
/* i > lb + len - 1 */
oob = LLVMBuildOr(builder, oob,
LLVMBuildICmp(builder, LLVMIntSGT, idx,
LLVMBuildSub(builder,
LLVMBuildAdd(builder, lb, len, "na.end"),
LLVMConstInt(i32, 1, false), "na.last"),
"na.above"),
"na.oob2");
/*
* ...and, when in range, the element may itself be NULL —
* PostgreSQL leaves NULLs behind when an assignment
* extends an array past its end. Only meaningful for an
* in-range subscript, but idx0 is harmless otherwise
* because the flags load is guarded and the result is
* OR-ed with oob anyway.
*/
{
LLVMValueRef idx0, elem_null;
idx0 = LLVMBuildSub(builder, idx, lb, "na.idx0");
elem_null = emit_native_array_elem_isnull(ctx, na,
idx0);
oob = LLVMBuildOr(builder, oob, elem_null,
"na.oob.or.null");
}
acc = (acc == NULL) ? oob
: LLVMBuildOr(builder, acc, oob, "anynull");
}
return acc;
}
case T_OpExpr:
case T_FuncExpr:
{
List *args = IsA(expr, OpExpr) ? ((OpExpr *) expr)->args
: ((FuncExpr *) expr)->args;
LLVMValueRef acc = NULL;
ListCell *lc;
foreach(lc, args)
{
LLVMValueRef v = tier1_expr_any_null(ctx,
(Expr *) lfirst(lc),
estate_ref);
if (v == NULL)
continue;
acc = (acc == NULL) ? v
: LLVMBuildOr(builder, acc, v, "anynull");
}
return acc;
}
default:
/*
* Unreachable: classify_expr() admits nothing else into Tier 1.
* Be conservative anyway and claim it might be null, which costs
* only the fallback path.
*/
return LLVMConstInt(ctx->types[UPLPGSQL_INT1], 1, false);
}
}
/*
* Emit IR to store a Datum (i64) into a variable.
* Sets value, isnull=false, freeval=false.
*/
static void
uplpgsql_emit_store_var_datum(UPLpgSQL_compile_ctx *ctx,
LLVMValueRef estate_ref, int dno,
LLVMValueRef datum_val)
{
LLVMBuilderRef builder = ctx->builder;
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i64 = ctx->types[UPLPGSQL_INT64];
LLVMTypeRef ptr = ctx->types[UPLPGSQL_PTR];
LLVMValueRef off, gep, plstate, datums, datum;
off = LLVMConstInt(i64, OFF_ESTATE_PLSTATE, false);
gep = LLVMBuildGEP2(builder, i8, estate_ref, &off, 1, "st.plstate.ptr");
plstate = LLVMBuildLoad2(builder, ptr, gep, "st.plstate");
off = LLVMConstInt(i64, OFF_EXECSTATE_DATUMS, false);
gep = LLVMBuildGEP2(builder, i8, plstate, &off, 1, "st.datums.ptr");
datums = LLVMBuildLoad2(builder, ptr, gep, "st.datums");
off = LLVMConstInt(i64, dno, false);
gep = LLVMBuildGEP2(builder, ptr, datums, &off, 1, "st.datum.slot");
datum = LLVMBuildLoad2(builder, ptr, gep, "st.datum");
/* datum->value = datum_val */
off = LLVMConstInt(i64, OFF_VAR_VALUE, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "st.value.ptr");
LLVMBuildStore(builder, datum_val, gep);
/* datum->isnull = false */
off = LLVMConstInt(i64, OFF_VAR_ISNULL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "st.isnull.ptr");
LLVMBuildStore(builder, LLVMConstInt(i8, 0, false), gep);
/* datum->freeval = false */
off = LLVMConstInt(i64, OFF_VAR_FREEVAL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "st.freeval.ptr");
LLVMBuildStore(builder, LLVMConstInt(i8, 0, false), gep);
}
/*
* Emit IR to store a Datum plus a computed isnull (i1) into a variable.
*
* Like uplpgsql_emit_store_var_datum(), but takes nullness from a value
* rather than assuming not-null. Pass-by-value targets only.
*/
static void
uplpgsql_emit_store_var_datum_isnull(UPLpgSQL_compile_ctx *ctx,
LLVMValueRef estate_ref, int dno,
LLVMValueRef datum_val,
LLVMValueRef isnull_val)
{
LLVMBuilderRef builder = ctx->builder;
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i64 = ctx->types[UPLPGSQL_INT64];
LLVMTypeRef ptr = ctx->types[UPLPGSQL_PTR];
LLVMValueRef off, gep, plstate, datums, datum;
off = LLVMConstInt(i64, OFF_ESTATE_PLSTATE, false);
gep = LLVMBuildGEP2(builder, i8, estate_ref, &off, 1, "si.plstate.ptr");
plstate = LLVMBuildLoad2(builder, ptr, gep, "si.plstate");
off = LLVMConstInt(i64, OFF_EXECSTATE_DATUMS, false);
gep = LLVMBuildGEP2(builder, i8, plstate, &off, 1, "si.datums.ptr");
datums = LLVMBuildLoad2(builder, ptr, gep, "si.datums");
off = LLVMConstInt(i64, dno, false);
gep = LLVMBuildGEP2(builder, ptr, datums, &off, 1, "si.datum.slot");
datum = LLVMBuildLoad2(builder, ptr, gep, "si.datum");
off = LLVMConstInt(i64, OFF_VAR_VALUE, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "si.value.ptr");
LLVMBuildStore(builder, datum_val, gep);
off = LLVMConstInt(i64, OFF_VAR_ISNULL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "si.isnull.ptr");
LLVMBuildStore(builder,
LLVMBuildZExt(builder, isnull_val, i8, "si.isnull.i8"),
gep);
off = LLVMConstInt(i64, OFF_VAR_FREEVAL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "si.freeval.ptr");
LLVMBuildStore(builder, LLVMConstInt(i8, 0, false), gep);
}
/*
* Emit IR to set a variable to NULL: value = 0, isnull = true.
*
* The pass-by-value counterpart of uplpgsql_emit_store_var_datum(), which
* always clears isnull. Only valid for pass-by-value targets — a
* pass-by-reference variable would need assign_simple_var() to release its
* old value, which is why Tier 1 only ever assigns scalars.
*/
static void
uplpgsql_emit_store_var_null(UPLpgSQL_compile_ctx *ctx,
LLVMValueRef estate_ref, int dno)
{
LLVMBuilderRef builder = ctx->builder;
LLVMTypeRef i8 = ctx->types[UPLPGSQL_INT8];
LLVMTypeRef i64 = ctx->types[UPLPGSQL_INT64];
LLVMTypeRef ptr = ctx->types[UPLPGSQL_PTR];
LLVMValueRef off, gep, plstate, datums, datum;
off = LLVMConstInt(i64, OFF_ESTATE_PLSTATE, false);
gep = LLVMBuildGEP2(builder, i8, estate_ref, &off, 1, "sn.plstate.ptr");
plstate = LLVMBuildLoad2(builder, ptr, gep, "sn.plstate");
off = LLVMConstInt(i64, OFF_EXECSTATE_DATUMS, false);
gep = LLVMBuildGEP2(builder, i8, plstate, &off, 1, "sn.datums.ptr");
datums = LLVMBuildLoad2(builder, ptr, gep, "sn.datums");
off = LLVMConstInt(i64, dno, false);
gep = LLVMBuildGEP2(builder, ptr, datums, &off, 1, "sn.datum.slot");
datum = LLVMBuildLoad2(builder, ptr, gep, "sn.datum");
/* datum->value = 0 */
off = LLVMConstInt(i64, OFF_VAR_VALUE, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "sn.value.ptr");
LLVMBuildStore(builder, LLVMConstInt(i64, 0, false), gep);
/* datum->isnull = true */
off = LLVMConstInt(i64, OFF_VAR_ISNULL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "sn.isnull.ptr");
LLVMBuildStore(builder, LLVMConstInt(i8, 1, false), gep);
/* datum->freeval = false */
off = LLVMConstInt(i64, OFF_VAR_FREEVAL, false);
gep = LLVMBuildGEP2(builder, i8, datum, &off, 1, "sn.freeval.ptr");
LLVMBuildStore(builder, LLVMConstInt(i8, 0, false), gep);
}
/* ================================================================
* Expression preparation and analysis
* ================================================================
*/
/*
* Prepare a PL/pgSQL expression via SPI and extract the Expr tree.
* Returns NULL if the expression is not simple.
*
* The PL/pgSQL parser callbacks (uplpgsql_parser_setup) require
* expr->func->cur_estate to be set for variable type resolution.
* At JIT compile time, no execution state exists yet, so we create a
* minimal temporary execstate backed by the function's datums array.
*/
static Expr *
uplpgsql_prepare_and_get_expr(UPLpgSQL_compile_ctx *ctx, UPLpgSQL_expr *expr)
{
SPIPlanPtr plan;
SPIPrepareOptions options;
List *plansources;
CachedPlanSource *plansource;
Query *query;
TargetEntry *tle;
UPLpgSQL_function *func = ctx_func(ctx);
if (expr->plan == NULL)
{
UPLpgSQL_execstate fake_estate;
UPLpgSQL_execstate *saved_estate;
MemoryContext oldcxt;
/*
* The parser callbacks in upl_comp.c access expr->func->cur_estate
* to resolve variable names and types. At compile time cur_estate
* is NULL, so we provide a minimal fake estate with the function's
* datums array — that's all resolve_column_ref/make_datum_param need
* for scalar variables.
*
* For record fields or other complex datums, SPI_prepare_extended
* may throw an error (e.g. "record not assigned yet"). We catch
* that and return NULL to fall back to the runtime helper.
*/
memset(&fake_estate, 0, sizeof(fake_estate));
fake_estate.ndatums = func->ndatums;
fake_estate.datums = func->datums;
saved_estate = func->cur_estate;
func->cur_estate = &fake_estate;
memset(&options, 0, sizeof(options));
options.parserSetup = (ParserSetupHook) uplpgsql_parser_setup;
options.parserSetupArg = expr;
options.parseMode = expr->parseMode;
options.cursorOptions = CURSOR_OPT_PARALLEL_OK;
oldcxt = CurrentMemoryContext;
PG_TRY();
{
plan = SPI_prepare_extended(expr->query, &options);
}
PG_CATCH();
{
/* Swallow the error and fall back to runtime helper */
MemoryContextSwitchTo(oldcxt);
FlushErrorState();
func->cur_estate = saved_estate;
return NULL;
}
PG_END_TRY();
func->cur_estate = saved_estate;
if (plan == NULL)
return NULL;
SPI_keepplan(plan);
expr->plan = plan;
}
plansources = SPI_plan_get_plan_sources(expr->plan);
if (list_length(plansources) != 1)
return NULL;
plansource = (CachedPlanSource *) linitial(plansources);
if (list_length(plansource->query_list) != 1)
return NULL;
query = (Query *) linitial(plansource->query_list);
if (!IsA(query, Query) ||
query->commandType != CMD_SELECT ||
query->rtable != NIL ||
query->hasAggs ||
query->hasWindowFuncs ||
query->hasTargetSRFs ||
query->hasSubLinks ||
query->cteList ||
query->jointree->fromlist ||
query->jointree->quals ||
query->groupClause ||
query->havingQual)
return NULL;
if (list_length(query->targetList) != 1)
return NULL;
tle = (TargetEntry *) linitial(query->targetList);
return tle->expr;
}
/*
* Classify an expression's result type for native compilation.
* Returns EXPR_TYPE_UNKNOWN if the expression cannot be natively compiled.
*/