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-26 00:35:57 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      219428 : isProjectConst(const InstrRecord *p)
      31             : {
      32      219428 :         return (getModuleId(p) == algebraRef && getFunctionId(p) == projectRef);
      33             : }
      34             : 
      35             : static int __attribute__((__pure__))
      36    11786084 : hashInstruction(const MalBlkRecord *mb, const InstrRecord *p)
      37             : {
      38    11786084 :         int i;
      39    30723003 :         for (i = p->argc - 1; i >= p->retc; i--)
      40    30408981 :                 if (!isVarConstant(mb, getArg(p, i)))
      41    11472062 :                         return getArg(p, i);
      42      314022 :         if (isVarConstant(mb, getArg(p, p->retc)))
      43      314022 :                 return p->retc;
      44             :         return -1;
      45             : }
      46             : 
      47             : str
      48      477403 : OPTcommonTermsImplementation(Client cntxt, MalBlkPtr mb, MalStkPtr stk,
      49             :                                                          InstrPtr pci)
      50             : {
      51      477403 :         int i, j, k, barrier = 0, bailout = 0;
      52      477403 :         InstrPtr p, q;
      53      477403 :         int actions = 0;
      54      477403 :         int limit, slimit;
      55      477403 :         int duplicate;
      56      477403 :         int *alias = NULL;
      57      477403 :         int *hash = NULL, h;
      58      477403 :         int *list = NULL;
      59      477403 :         str msg = MAL_SUCCEED;
      60             : 
      61      477403 :         InstrPtr *old = NULL;
      62             : 
      63             :         /* catch simple insert operations */
      64      477403 :         if (isSimpleSQL(mb)) {
      65      272871 :                 goto wrapup;
      66             :         }
      67             : 
      68      204574 :         (void) cntxt;
      69      204574 :         (void) stk;
      70      204574 :         alias = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      71      204595 :         list = (int *) GDKzalloc(sizeof(int) * mb->stop);
      72      204585 :         hash = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      73      204596 :         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      204596 :         old = mb->stmt;
      80      204596 :         limit = mb->stop;
      81      204596 :         slimit = mb->ssize;
      82      204596 :         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    14684225 :         for (i = 0; mb->errors == NULL && i < limit; i++) {
      90    14684225 :                 p = old[i];
      91    14684225 :                 duplicate = 0;
      92             : 
      93    80745190 :                 for (k = 0; k < p->argc; k++)
      94    66060965 :                         if (alias[getArg(p, k)])
      95      275346 :                                 getArg(p, k) = alias[getArg(p, k)];
      96             : 
      97    14684225 :                 if (p->token == ENDsymbol) {
      98      204531 :                         pushInstruction(mb, p);
      99      204559 :                         old[i] = NULL;
     100      204559 :                         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    28959388 :                 barrier |= (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     107    14479694 :                                         || 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    14479694 :                 barrier |= getFunctionId(p) == assertRef;
     116    14479694 :                 if (barrier || p->token == ASSIGNsymbol) {
     117      241320 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d]: %d %d\n", i, barrier,
     118             :                                           p->retc == p->argc);
     119      241320 :                         pushInstruction(mb, p);
     120      241325 :                         old[i] = NULL;
     121      241325 :                         continue;
     122             :                 }
     123             : 
     124             :                 /* when we enter a barrier block, we should ditch all previous instructions from consideration */
     125    14238374 :                 if (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     126    14238374 :                         || 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    14238374 :                 if (mayhaveSideEffects(cntxt, mb, p, TRUE) || p->argc == p->retc) {
     134     1664270 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d] side-effect: %d\n", i,
     135             :                                           p->retc == p->argc);
     136     1664270 :                         pushInstruction(mb, p);
     137     1664255 :                         old[i] = NULL;
     138     1664255 :                         continue;
     139             :                 }
     140             :                 /* simple SQL bind operations need not be merged, they are cheap
     141             :                  * and/or can be duplicated eliminated elsewhere cheaper */
     142    12575046 :                 if (getModuleId(p) == sqlRef && (getFunctionId(p) != tidRef && getFunctionId(p) != bindRef)) {
     143      789281 :                         pushInstruction(mb, p);
     144      789281 :                         old[i] = NULL;
     145      789281 :                         continue;
     146             :                 }
     147             : 
     148             :                 /* from here we have a candidate to look for a match */
     149             : 
     150    11785765 :                 h = hashInstruction(mb, p);
     151             : 
     152    11785765 :                 TRC_DEBUG(MAL_OPTIMIZER, "Candidate[%d] look at list[%d] => %d\n", i, h,
     153             :                                   hash[h]);
     154    11785765 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     155             : 
     156    11785761 :                 if (h < 0) {
     157           0 :                         pushInstruction(mb, p);
     158           0 :                         old[i] = NULL;
     159           0 :                         continue;
     160             :                 }
     161             : 
     162    11785761 :                 bailout = 1024;                 // don't run over long collision list
     163             :                 /* Look into the hash structure for matching instructions */
     164    96481026 :                 for (j = hash[h]; j > 0 && bailout-- > 0; j = list[j]) {
     165    84898512 :                         if ((q = getInstrPtr(mb, j))
     166    84898512 :                                 && getFunctionId(q) == getFunctionId(p)
     167    67105739 :                                 && getModuleId(q) == getModuleId(p)) {
     168    67110811 :                                 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    67110811 :                                 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    67116144 :                                 if (hasSameArguments(mb, p, q)
     184      219446 :                                         && hasSameSignature(mb, p, q)
     185      219428 :                                         && !hasCommonResults(p, q)
     186      219428 :                                         && !isUnsafeFunction(q)
     187      219428 :                                         && !isUpdateInstruction(q)
     188      219428 :                                         && !isProjectConst(q) &&        /* disable project(x,val), as its used for the result of case statements */
     189      201561 :                                         isLinearFlow(q)) {
     190      201561 :                                         if (safetyBarrier(p, q)) {
     191           0 :                                                 TRC_DEBUG(MAL_OPTIMIZER, "Safety barrier reached\n");
     192             :                                                 break;
     193             :                                         }
     194      201561 :                                         duplicate = 1;
     195      201561 :                                         clrFunction(p);
     196      201561 :                                         p->argc = p->retc;
     197      411819 :                                         for (k = 0; k < q->retc; k++) {
     198      210258 :                                                 alias[getArg(p, k)] = getArg(q, k);
     199             :                                                 /* we know the arguments fit so the instruction can safely be patched */
     200      210258 :                                                 p = pushArgument(mb, p, getArg(q, k));
     201             :                                         }
     202             : 
     203      201561 :                                         TRC_DEBUG(MAL_OPTIMIZER, "Modified expression %d -> %d ",
     204             :                                                           getArg(p, 0), getArg(p, 1));
     205      201561 :                                         traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     206             : 
     207      201561 :                                         actions++;
     208      201561 :                                         break;          /* end of search */
     209             :                                 }
     210    17787701 :                         } 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    11784075 :                 if (duplicate) {
     219      201561 :                         pushInstruction(mb, p);
     220      201561 :                         old[i] = NULL;
     221      201561 :                         continue;
     222             :                 }
     223             :                 /* update the hash structure with another candidate for re-use */
     224    11582514 :                 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    11582514 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     228             : 
     229    11582922 :                 if (!mayhaveSideEffects(cntxt, mb, p, TRUE) && p->argc != p->retc
     230    23166635 :                         && isLinearFlow(p) && !isUnsafeFunction(p)
     231    11583322 :                         && !isUpdateInstruction(p)) {
     232    11583301 :                         list[i] = hash[h];
     233    11583301 :                         hash[h] = i;
     234    11583301 :                         pushInstruction(mb, p);
     235    11583502 :                         old[i] = NULL;
     236             :                 }
     237             :         }
     238    47055417 :         for (; i < slimit; i++)
     239    46850827 :                 if (old[i])
     240     5202519 :                         pushInstruction(mb, old[i]);
     241             :         /* Defense line against incorrect plans */
     242      204590 :         if (actions > 0) {
     243        8654 :                 msg = chkTypes(cntxt->usermodule, mb, FALSE);
     244        8654 :                 if (!msg)
     245        8654 :                         msg = chkFlow(mb);
     246        8654 :                 if (!msg)
     247        8654 :                         msg = chkDeclarations(mb);
     248             :         }
     249      195936 :   wrapup:
     250             :         /* keep actions taken as a fake argument */
     251      477461 :         (void) pushInt(mb, pci, actions);
     252             : 
     253      477444 :         if (alias)
     254      204573 :                 GDKfree(alias);
     255      477467 :         if (list)
     256      204596 :                 GDKfree(list);
     257      477463 :         if (hash)
     258      204592 :                 GDKfree(hash);
     259      477446 :         if (old)
     260      204575 :                 GDKfree(old);
     261      477465 :         return msg;
     262             : }

Generated by: LCOV version 1.14