Line data Source code
1 : /*
2 : * SPDX-License-Identifier: MPL-2.0
3 : *
4 : * This Source Code Form is subject to the terms of the Mozilla Public
5 : * License, v. 2.0. If a copy of the MPL was not distributed with this
6 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 : *
8 : * Copyright 2024, 2025 MonetDB Foundation;
9 : * Copyright August 2008 - 2023 MonetDB B.V.;
10 : * Copyright 1997 - July 2008 CWI.
11 : */
12 :
13 : #include "monetdb_config.h"
14 : #include "opt_commonTerms.h"
15 : #include "mal_exception.h"
16 : /*
17 : * Caveat. A lot of time was lost due to constants that are indistinguisable
18 : * at the surface level. It requires the constant optimizer to be ran first.
19 : */
20 :
21 : /* The key for finding common terms is that they share variables.
22 : * Therefore we skip all constants, except for a constant only situation.
23 : */
24 :
25 : /*
26 : * Speed up simple insert operations by skipping the common terms.
27 : */
28 :
29 : __attribute__((__pure__))
30 : static inline bool
31 316599 : isProjectConst(const InstrRecord *p)
32 : {
33 316599 : return (getModuleId(p) == algebraRef && getFunctionId(p) == projectRef);
34 : }
35 :
36 : __attribute__((__pure__))
37 : static int
38 13521380 : hashInstruction(const MalBlkRecord *mb, const InstrRecord *p)
39 : {
40 13521380 : int i;
41 36148969 : for (i = p->argc - 1; i >= p->retc; i--)
42 35713326 : if (!isVarConstant(mb, getArg(p, i)))
43 13085737 : return getArg(p, i);
44 435643 : if (isVarConstant(mb, getArg(p, p->retc)))
45 435643 : return p->retc;
46 : return -1;
47 : }
48 :
49 : str
50 539384 : OPTcommonTermsImplementation(Client cntxt, MalBlkPtr mb, MalStkPtr stk,
51 : InstrPtr pci)
52 : {
53 539384 : int i, j, k, barrier = 0, bailout = 0;
54 539384 : InstrPtr p, q;
55 539384 : int actions = 0;
56 539384 : int limit, slimit;
57 539384 : int duplicate;
58 539384 : int *alias = NULL;
59 539384 : int *hash = NULL, h;
60 539384 : int *list = NULL;
61 539384 : str msg = MAL_SUCCEED;
62 :
63 539384 : InstrPtr *old = NULL;
64 :
65 : /* catch simple insert operations */
66 539384 : if (isSimpleSQL(mb)) {
67 291766 : goto wrapup;
68 : }
69 :
70 247694 : (void) cntxt;
71 247694 : (void) stk;
72 247694 : alias = (int *) GDKzalloc(sizeof(int) * mb->vtop);
73 247712 : list = (int *) GDKzalloc(sizeof(int) * mb->stop);
74 247703 : hash = (int *) GDKzalloc(sizeof(int) * mb->vtop);
75 247708 : if (alias == NULL || list == NULL || hash == NULL) {
76 0 : msg = createException(MAL, "optimizer.commonTerms",
77 : SQLSTATE(HY013) MAL_MALLOC_FAIL);
78 0 : goto wrapup;
79 : }
80 :
81 247708 : old = mb->stmt;
82 247708 : limit = mb->stop;
83 247708 : slimit = mb->ssize;
84 247708 : if (newMalBlkStmt(mb, mb->ssize) < 0) {
85 0 : msg = createException(MAL, "optimizer.commonTerms",
86 : SQLSTATE(HY013) MAL_MALLOC_FAIL);
87 0 : old = NULL;
88 0 : goto wrapup;
89 : }
90 :
91 16901967 : for (i = 0; mb->errors == NULL && i < limit; i++) {
92 16901967 : p = old[i];
93 16901967 : duplicate = 0;
94 :
95 93099720 : for (k = 0; k < p->argc; k++)
96 76197753 : if (alias[getArg(p, k)])
97 377712 : getArg(p, k) = alias[getArg(p, k)];
98 :
99 16901967 : if (p->token == ENDsymbol) {
100 236274 : pushInstruction(mb, p);
101 236302 : old[i] = NULL;
102 236302 : break;
103 : }
104 : /*
105 : * Any barrier block signals the end of this optimizer,
106 : * because the impact of the block can affect the common code eliminated.
107 : */
108 33331386 : barrier |= (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
109 16665693 : || p->barrier == RETURNsymbol);
110 : /*
111 : * Also block further optimization when you have seen an assert().
112 : * This works particularly for SQL, because it is not easy to track
113 : * the BAT identifier aliases to look for updates. The sql.assert
114 : * at least tells us that an update is planned.
115 : * Like all optimizer decisions, it is safe to stop.
116 : */
117 16665693 : barrier |= getFunctionId(p) == assertRef;
118 16665693 : if (barrier || p->token == ASSIGNsymbol) {
119 11351 : TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d]: %d %d\n", i, barrier,
120 : p->retc == p->argc);
121 11351 : pushInstruction(mb, p);
122 11365 : old[i] = NULL;
123 11365 : break;
124 : }
125 :
126 : /* when we enter a barrier block, we should ditch all previous instructions from consideration */
127 16654342 : if (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
128 16654342 : || p->barrier == RETURNsymbol) {
129 0 : memset(list, 0, sizeof(int) * mb->stop);
130 0 : memset(hash, 0, sizeof(int) * mb->vtop);
131 : }
132 : /* side-effect producing operators can never be replaced */
133 : /* the same holds for function calls without an argument, it is
134 : * unclear where the results comes from (e.g. clock()) */
135 16654342 : if (mayhaveSideEffects(cntxt, mb, p, TRUE) || p->argc == p->retc) {
136 1978076 : TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d] side-effect: %d\n", i,
137 : p->retc == p->argc);
138 1978076 : pushInstruction(mb, p);
139 1978092 : old[i] = NULL;
140 1978092 : continue;
141 : }
142 : /* simple SQL bind operations need not be merged, they are cheap
143 : * and/or can be duplicated eliminated elsewhere cheaper */
144 14676636 : if (getModuleId(p) == sqlRef && (getFunctionId(p) != tidRef && getFunctionId(p) != bindRef)) {
145 947280 : pushInstruction(mb, p);
146 947280 : old[i] = NULL;
147 947280 : continue;
148 : }
149 13729356 : if (getModuleId(p) == matRef) { /* mat.packIncrement has requirement on number of instructions (or that needs an update */
150 208663 : pushInstruction(mb, p);
151 208663 : old[i] = NULL;
152 208663 : continue;
153 : }
154 :
155 : /* from here we have a candidate to look for a match */
156 :
157 13520693 : h = hashInstruction(mb, p);
158 :
159 13520693 : TRC_DEBUG(MAL_OPTIMIZER, "Candidate[%d] look at list[%d] => %d\n", i, h,
160 : hash[h]);
161 13520693 : traceInstruction(mb, 0, p, LIST_MAL_ALL);
162 :
163 13520961 : if (h < 0) {
164 0 : pushInstruction(mb, p);
165 0 : old[i] = NULL;
166 0 : continue;
167 : }
168 :
169 13520961 : bailout = 1024; // don't run over long collision list
170 : /* Look into the hash structure for matching instructions */
171 117043941 : for (j = hash[h]; j > 0 && bailout-- > 0; j = list[j]) {
172 103820220 : if ((q = getInstrPtr(mb, j))
173 103820220 : && getFunctionId(q) == getFunctionId(p)
174 77805490 : && getModuleId(q) == getModuleId(p)) {
175 77809141 : TRC_DEBUG(MAL_OPTIMIZER,
176 : "Candidate[%d->%d] %d %d :%d %d %d=%d %d %d %d\n", j,
177 : list[j], hasSameSignature(mb, p, q),
178 : hasSameArguments(mb, p, q), q->token != ASSIGNsymbol,
179 : list[getArg(q, q->argc - 1)], i, !hasCommonResults(p,
180 : q),
181 : !isUnsafeFunction(q), !isUpdateInstruction(q),
182 : isLinearFlow(q));
183 77809141 : traceInstruction(mb, 0, q, LIST_MAL_ALL);
184 :
185 : /*
186 : * Simple assignments are not replaced either. They should be
187 : * handled by the alias removal part. All arguments should
188 : * be assigned their value before instruction p.
189 : */
190 77815868 : if (hasSameArguments(mb, p, q)
191 316617 : && hasSameSignature(mb, p, q)
192 316595 : && !hasCommonResults(p, q)
193 316598 : && !isUnsafeFunction(q)
194 316594 : && !isUpdateInstruction(q)
195 316599 : && !isProjectConst(q) && /* disable project(x,val), as its used for the result of case statements */
196 295400 : isLinearFlow(q)) {
197 295401 : if (safetyBarrier(p, q)) {
198 0 : TRC_DEBUG(MAL_OPTIMIZER, "Safety barrier reached\n");
199 : break;
200 : }
201 295399 : duplicate = 1;
202 295399 : clrFunction(p);
203 295396 : p->argc = p->retc;
204 603290 : for (k = 0; k < q->retc; k++) {
205 307906 : alias[getArg(p, k)] = getArg(q, k);
206 : /* we know the arguments fit so the instruction can safely be patched */
207 307906 : p = pushArgument(mb, p, getArg(q, k));
208 : }
209 :
210 295384 : TRC_DEBUG(MAL_OPTIMIZER, "Modified expression %d -> %d ",
211 : getArg(p, 0), getArg(p, 1));
212 295384 : traceInstruction(mb, 0, p, LIST_MAL_ALL);
213 :
214 295393 : actions++;
215 295393 : break; /* end of search */
216 : }
217 26011079 : } else if (isUpdateInstruction(p)) {
218 0 : TRC_DEBUG(MAL_OPTIMIZER, "Skipped: %d %d\n",
219 : mayhaveSideEffects(cntxt, mb, q, TRUE),
220 : isUpdateInstruction(p));
221 0 : traceInstruction(mb, 0, q, LIST_MAL_ALL);
222 : }
223 : }
224 :
225 13519114 : if (duplicate) {
226 295393 : pushInstruction(mb, p);
227 295392 : old[i] = NULL;
228 295392 : continue;
229 : }
230 : /* update the hash structure with another candidate for reuse */
231 13223721 : TRC_DEBUG(MAL_OPTIMIZER,
232 : "Update hash[%d] - look at arg '%d' hash '%d' list '%d'\n", i,
233 : getArg(p, p->argc - 1), h, hash[h]);
234 13223721 : traceInstruction(mb, 0, p, LIST_MAL_ALL);
235 :
236 13224306 : if (!mayhaveSideEffects(cntxt, mb, p, TRUE) && p->argc != p->retc
237 26449818 : && isLinearFlow(p) && !isUnsafeFunction(p)
238 13224787 : && !isUpdateInstruction(p)) {
239 13224790 : list[i] = hash[h];
240 13224790 : hash[h] = i;
241 13224790 : pushInstruction(mb, p);
242 13225081 : old[i] = NULL;
243 : }
244 : }
245 58368953 : for (; i < slimit; i++)
246 58121253 : if (old[i])
247 6758620 : pushInstruction(mb, old[i]);
248 : /* Defense line against incorrect plans */
249 247700 : if (actions > 0) {
250 68537 : msg = chkTypes(cntxt->usermodule, mb, FALSE);
251 68536 : if (!msg)
252 68537 : msg = chkFlow(mb);
253 68540 : if (!msg)
254 68540 : msg = chkDeclarations(mb);
255 : }
256 179163 : wrapup:
257 : /* keep actions taken as a fake argument */
258 539465 : (void) pushInt(mb, pci, actions);
259 :
260 539450 : if (alias)
261 247684 : GDKfree(alias);
262 539481 : if (list)
263 247715 : GDKfree(list);
264 539478 : if (hash)
265 247712 : GDKfree(hash);
266 539483 : if (old)
267 247717 : GDKfree(old);
268 539480 : return msg;
269 : }
|