LCOV - code coverage report
Current view: top level - monetdb5/optimizer - opt_commonTerms.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 124 137 90.5 %
Date: 2024-04-25 20:03:45 Functions: 2 2 100.0 %

          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 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             : static inline bool __attribute__((__pure__))
      30      161721 : isProjectConst(const InstrRecord *p)
      31             : {
      32      161721 :         return (getModuleId(p) == algebraRef && getFunctionId(p) == projectRef);
      33             : }
      34             : 
      35             : static int __attribute__((__pure__))
      36     7193399 : hashInstruction(const MalBlkRecord *mb, const InstrRecord *p)
      37             : {
      38     7193399 :         int i;
      39    19244837 :         for (i = p->argc - 1; i >= p->retc; i--)
      40    18927420 :                 if (!isVarConstant(mb, getArg(p, i)))
      41     6875982 :                         return getArg(p, i);
      42      317417 :         if (isVarConstant(mb, getArg(p, p->retc)))
      43      317417 :                 return p->retc;
      44             :         return -1;
      45             : }
      46             : 
      47             : str
      48      467672 : OPTcommonTermsImplementation(Client cntxt, MalBlkPtr mb, MalStkPtr stk,
      49             :                                                          InstrPtr pci)
      50             : {
      51      467672 :         int i, j, k, barrier = 0, bailout = 0;
      52      467672 :         InstrPtr p, q;
      53      467672 :         int actions = 0;
      54      467672 :         int limit, slimit;
      55      467672 :         int duplicate;
      56      467672 :         int *alias = NULL;
      57      467672 :         int *hash = NULL, h;
      58      467672 :         int *list = NULL;
      59      467672 :         str msg = MAL_SUCCEED;
      60             : 
      61      467672 :         InstrPtr *old = NULL;
      62             : 
      63             :         /* catch simple insert operations */
      64      467672 :         if (isSimpleSQL(mb)) {
      65      266907 :                 goto wrapup;
      66             :         }
      67             : 
      68      200765 :         (void) cntxt;
      69      200765 :         (void) stk;
      70      200765 :         alias = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      71      200764 :         list = (int *) GDKzalloc(sizeof(int) * mb->stop);
      72      200764 :         hash = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      73      200763 :         if (alias == NULL || list == NULL || hash == NULL) {
      74           0 :                 msg = createException(MAL, "optimizer.commonTerms",
      75             :                                                           SQLSTATE(HY013) MAL_MALLOC_FAIL);
      76           0 :                 goto wrapup;
      77             :         }
      78             : 
      79      200763 :         old = mb->stmt;
      80      200763 :         limit = mb->stop;
      81      200763 :         slimit = mb->ssize;
      82      200763 :         if (newMalBlkStmt(mb, mb->ssize) < 0) {
      83           0 :                 msg = createException(MAL, "optimizer.commonTerms",
      84             :                                                           SQLSTATE(HY013) MAL_MALLOC_FAIL);
      85           0 :                 old = NULL;
      86           0 :                 goto wrapup;
      87             :         }
      88             : 
      89     9728451 :         for (i = 0; mb->errors == NULL && i < limit; i++) {
      90     9728451 :                 p = old[i];
      91     9728451 :                 duplicate = 0;
      92             : 
      93    52817512 :                 for (k = 0; k < p->argc; k++)
      94    43089061 :                         if (alias[getArg(p, k)])
      95      193796 :                                 getArg(p, k) = alias[getArg(p, k)];
      96             : 
      97     9728451 :                 if (p->token == ENDsymbol) {
      98      200759 :                         pushInstruction(mb, p);
      99      200756 :                         old[i] = NULL;
     100      200756 :                         break;
     101             :                 }
     102             :                 /*
     103             :                  * Any barrier block signals the end of this optimizer,
     104             :                  * because the impact of the block can affect the common code eliminated.
     105             :                  */
     106    19055384 :                 barrier |= (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     107     9527692 :                                         || p->barrier == RETURNsymbol);
     108             :                 /*
     109             :                  * Also block further optimization when you have seen an assert().
     110             :                  * This works particularly for SQL, because it is not easy to track
     111             :                  * the BAT identifier aliases to look for updates. The sql.assert
     112             :                  * at least tells us that an update is planned.
     113             :                  * Like all optimizer decisions, it is safe to stop.
     114             :                  */
     115     9527692 :                 barrier |= getFunctionId(p) == assertRef;
     116     9527692 :                 if (barrier || p->token == ASSIGNsymbol) {
     117      244072 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d]: %d %d\n", i, barrier,
     118             :                                           p->retc == p->argc);
     119      244072 :                         pushInstruction(mb, p);
     120      244072 :                         old[i] = NULL;
     121      244072 :                         continue;
     122             :                 }
     123             : 
     124             :                 /* when we enter a barrier block, we should ditch all previous instructions from consideration */
     125     9283620 :                 if (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     126     9283620 :                         || p->barrier == RETURNsymbol) {
     127           0 :                         memset(list, 0, sizeof(int) * mb->stop);
     128           0 :                         memset(hash, 0, sizeof(int) * mb->vtop);
     129             :                 }
     130             :                 /* side-effect producing operators can never be replaced */
     131             :                 /* the same holds for function calls without an argument, it is
     132             :                  * unclear where the results comes from (e.g. clock()) */
     133     9283620 :                 if (mayhaveSideEffects(cntxt, mb, p, TRUE) || p->argc == p->retc) {
     134     1591977 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d] side-effect: %d\n", i,
     135             :                                           p->retc == p->argc);
     136     1591977 :                         pushInstruction(mb, p);
     137     1591959 :                         old[i] = NULL;
     138     1591959 :                         continue;
     139             :                 }
     140             :                 /* simple SQL bind operations need not be merged, they are cheap
     141             :                  * and/or can be duplicated eliminated elsewhere cheaper */
     142     7691836 :                 if (getModuleId(p) == sqlRef && (getFunctionId(p) != tidRef && getFunctionId(p) != bindRef)) {
     143      498599 :                         pushInstruction(mb, p);
     144      498599 :                         old[i] = NULL;
     145      498599 :                         continue;
     146             :                 }
     147             : 
     148             :                 /* from here we have a candidate to look for a match */
     149             : 
     150     7193237 :                 h = hashInstruction(mb, p);
     151             : 
     152     7193237 :                 TRC_DEBUG(MAL_OPTIMIZER, "Candidate[%d] look at list[%d] => %d\n", i, h,
     153             :                                   hash[h]);
     154     7193237 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     155             : 
     156     7193246 :                 if (h < 0) {
     157           0 :                         pushInstruction(mb, p);
     158           0 :                         old[i] = NULL;
     159           0 :                         continue;
     160             :                 }
     161             : 
     162     7193246 :                 bailout = 1024;                 // don't run over long collision list
     163             :                 /* Look into the hash structure for matching instructions */
     164    42053920 :                 for (j = hash[h]; j > 0 && bailout-- > 0; j = list[j]) {
     165    35008897 :                         if ((q = getInstrPtr(mb, j))
     166    35008897 :                                 && getFunctionId(q) == getFunctionId(p)
     167    25855011 :                                 && getModuleId(q) == getModuleId(p)) {
     168    25854996 :                                 TRC_DEBUG(MAL_OPTIMIZER,
     169             :                                                   "Candidate[%d->%d] %d %d :%d %d %d=%d %d %d %d\n", j,
     170             :                                                   list[j], hasSameSignature(mb, p, q),
     171             :                                                   hasSameArguments(mb, p, q), q->token != ASSIGNsymbol,
     172             :                                                   list[getArg(q, q->argc - 1)], i, !hasCommonResults(p,
     173             :                                                                                                                                                          q),
     174             :                                                   !isUnsafeFunction(q), !isUpdateInstruction(q),
     175             :                                                   isLinearFlow(q));
     176    25854996 :                                 traceInstruction(MAL_OPTIMIZER, mb, 0, q, LIST_MAL_ALL);
     177             : 
     178             :                                 /*
     179             :                                  * Simple assignments are not replaced either. They should be
     180             :                                  * handled by the alias removal part. All arguments should
     181             :                                  * be assigned their value before instruction p.
     182             :                                  */
     183    25854738 :                                 if (hasSameArguments(mb, p, q)
     184      161721 :                                         && hasSameSignature(mb, p, q)
     185      161721 :                                         && !hasCommonResults(p, q)
     186      161721 :                                         && !isUnsafeFunction(q)
     187      161721 :                                         && !isUpdateInstruction(q)
     188      161721 :                                         && !isProjectConst(q) &&        /* disable project(x,val), as its used for the result of case statements */
     189      148253 :                                         isLinearFlow(q)) {
     190      148253 :                                         if (safetyBarrier(p, q)) {
     191           0 :                                                 TRC_DEBUG(MAL_OPTIMIZER, "Safety barrier reached\n");
     192             :                                                 break;
     193             :                                         }
     194      148253 :                                         duplicate = 1;
     195      148253 :                                         clrFunction(p);
     196      148253 :                                         p->argc = p->retc;
     197      304264 :                                         for (k = 0; k < q->retc; k++) {
     198      156011 :                                                 alias[getArg(p, k)] = getArg(q, k);
     199             :                                                 /* we know the arguments fit so the instruction can safely be patched */
     200      156011 :                                                 p = pushArgument(mb, p, getArg(q, k));
     201             :                                         }
     202             : 
     203      148253 :                                         TRC_DEBUG(MAL_OPTIMIZER, "Modified expression %d -> %d ",
     204             :                                                           getArg(p, 0), getArg(p, 1));
     205      148253 :                                         traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     206             : 
     207      148253 :                                         actions++;
     208      148253 :                                         break;          /* end of search */
     209             :                                 }
     210     9153901 :                         } else if (isUpdateInstruction(p)) {
     211           0 :                                 TRC_DEBUG(MAL_OPTIMIZER, "Skipped: %d %d\n",
     212             :                                                   mayhaveSideEffects(cntxt, mb, q, TRUE),
     213             :                                                   isUpdateInstruction(p));
     214           0 :                                 traceInstruction(MAL_OPTIMIZER, mb, 0, q, LIST_MAL_ALL);
     215             :                         }
     216             :                 }
     217             : 
     218     7193276 :                 if (duplicate) {
     219      148253 :                         pushInstruction(mb, p);
     220      148253 :                         old[i] = NULL;
     221      148253 :                         continue;
     222             :                 }
     223             :                 /* update the hash structure with another candidate for re-use */
     224     7045023 :                 TRC_DEBUG(MAL_OPTIMIZER,
     225             :                                   "Update hash[%d] - look at arg '%d' hash '%d' list '%d'\n", i,
     226             :                                   getArg(p, p->argc - 1), h, hash[h]);
     227     7045023 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     228             : 
     229     7044992 :                 if (!mayhaveSideEffects(cntxt, mb, p, TRUE) && p->argc != p->retc
     230    14089925 :                         && isLinearFlow(p) && !isUnsafeFunction(p)
     231     7044958 :                         && !isUpdateInstruction(p)) {
     232     7044843 :                         list[i] = hash[h];
     233     7044843 :                         hash[h] = i;
     234     7044843 :                         pushInstruction(mb, p);
     235     7044805 :                         old[i] = NULL;
     236             :                 }
     237             :         }
     238    46573634 :         for (; i < slimit; i++)
     239    46372869 :                 if (old[i])
     240     5090565 :                         pushInstruction(mb, old[i]);
     241             :         /* Defense line against incorrect plans */
     242      200765 :         if (actions > 0) {
     243        9935 :                 msg = chkTypes(cntxt->usermodule, mb, FALSE);
     244        9935 :                 if (!msg)
     245        9935 :                         msg = chkFlow(mb);
     246        9935 :                 if (!msg)
     247        9935 :                         msg = chkDeclarations(mb);
     248             :         }
     249      190830 :   wrapup:
     250             :         /* keep actions taken as a fake argument */
     251      467672 :         (void) pushInt(mb, pci, actions);
     252             : 
     253      467672 :         if (alias)
     254      200765 :                 GDKfree(alias);
     255      467672 :         if (list)
     256      200765 :                 GDKfree(list);
     257      467672 :         if (hash)
     258      200765 :                 GDKfree(hash);
     259      467672 :         if (old)
     260      200765 :                 GDKfree(old);
     261      467672 :         return msg;
     262             : }

Generated by: LCOV version 1.14