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 21:43:30 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      136337 : isProjectConst(const InstrRecord *p)
      31             : {
      32      136337 :         return (getModuleId(p) == algebraRef && getFunctionId(p) == projectRef);
      33             : }
      34             : 
      35             : static int __attribute__((__pure__))
      36     7192424 : hashInstruction(const MalBlkRecord *mb, const InstrRecord *p)
      37             : {
      38     7192424 :         int i;
      39    19431971 :         for (i = p->argc - 1; i >= p->retc; i--)
      40    19107486 :                 if (!isVarConstant(mb, getArg(p, i)))
      41     6867939 :                         return getArg(p, i);
      42      324485 :         if (isVarConstant(mb, getArg(p, p->retc)))
      43      324485 :                 return p->retc;
      44             :         return -1;
      45             : }
      46             : 
      47             : str
      48      487585 : OPTcommonTermsImplementation(Client cntxt, MalBlkPtr mb, MalStkPtr stk,
      49             :                                                          InstrPtr pci)
      50             : {
      51      487585 :         int i, j, k, barrier = 0, bailout = 0;
      52      487585 :         InstrPtr p, q;
      53      487585 :         int actions = 0;
      54      487585 :         int limit, slimit;
      55      487585 :         int duplicate;
      56      487585 :         int *alias = NULL;
      57      487585 :         int *hash = NULL, h;
      58      487585 :         int *list = NULL;
      59      487585 :         str msg = MAL_SUCCEED;
      60             : 
      61      487585 :         InstrPtr *old = NULL;
      62             : 
      63             :         /* catch simple insert operations */
      64      487585 :         if (isSimpleSQL(mb)) {
      65      279618 :                 goto wrapup;
      66             :         }
      67             : 
      68      207968 :         (void) cntxt;
      69      207968 :         (void) stk;
      70      207968 :         alias = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      71      207968 :         list = (int *) GDKzalloc(sizeof(int) * mb->stop);
      72      207969 :         hash = (int *) GDKzalloc(sizeof(int) * mb->vtop);
      73      207968 :         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      207968 :         old = mb->stmt;
      80      207968 :         limit = mb->stop;
      81      207968 :         slimit = mb->ssize;
      82      207968 :         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     9860505 :         for (i = 0; mb->errors == NULL && i < limit; i++) {
      90     9860505 :                 p = old[i];
      91     9860505 :                 duplicate = 0;
      92             : 
      93    53929248 :                 for (k = 0; k < p->argc; k++)
      94    44068743 :                         if (alias[getArg(p, k)])
      95      167394 :                                 getArg(p, k) = alias[getArg(p, k)];
      96             : 
      97     9860505 :                 if (p->token == ENDsymbol) {
      98      207963 :                         pushInstruction(mb, p);
      99      207960 :                         old[i] = NULL;
     100      207960 :                         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    19305084 :                 barrier |= (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     107     9652542 :                                         || 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     9652542 :                 barrier |= getFunctionId(p) == assertRef;
     116     9652542 :                 if (barrier || p->token == ASSIGNsymbol) {
     117      254948 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d]: %d %d\n", i, barrier,
     118             :                                           p->retc == p->argc);
     119      254948 :                         pushInstruction(mb, p);
     120      254944 :                         old[i] = NULL;
     121      254944 :                         continue;
     122             :                 }
     123             : 
     124             :                 /* when we enter a barrier block, we should ditch all previous instructions from consideration */
     125     9397594 :                 if (p->barrier == BARRIERsymbol || p->barrier == CATCHsymbol
     126     9397594 :                         || 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     9397594 :                 if (mayhaveSideEffects(cntxt, mb, p, TRUE) || p->argc == p->retc) {
     134     1676077 :                         TRC_DEBUG(MAL_OPTIMIZER, "Skipped[%d] side-effect: %d\n", i,
     135             :                                           p->retc == p->argc);
     136     1676077 :                         pushInstruction(mb, p);
     137     1676056 :                         old[i] = NULL;
     138     1676056 :                         continue;
     139             :                 }
     140             :                 /* simple SQL bind operations need not be merged, they are cheap
     141             :                  * and/or can be duplicated eliminated elsewhere cheaper */
     142     7721724 :                 if (getModuleId(p) == sqlRef && (getFunctionId(p) != tidRef && getFunctionId(p) != bindRef)) {
     143      529420 :                         pushInstruction(mb, p);
     144      529420 :                         old[i] = NULL;
     145      529420 :                         continue;
     146             :                 }
     147             : 
     148             :                 /* from here we have a candidate to look for a match */
     149             : 
     150     7192304 :                 h = hashInstruction(mb, p);
     151             : 
     152     7192304 :                 TRC_DEBUG(MAL_OPTIMIZER, "Candidate[%d] look at list[%d] => %d\n", i, h,
     153             :                                   hash[h]);
     154     7192304 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     155             : 
     156     7192314 :                 if (h < 0) {
     157           0 :                         pushInstruction(mb, p);
     158           0 :                         old[i] = NULL;
     159           0 :                         continue;
     160             :                 }
     161             : 
     162     7192314 :                 bailout = 1024;                 // don't run over long collision list
     163             :                 /* Look into the hash structure for matching instructions */
     164    43149243 :                 for (j = hash[h]; j > 0 && bailout-- > 0; j = list[j]) {
     165    36079439 :                         if ((q = getInstrPtr(mb, j))
     166    36079439 :                                 && getFunctionId(q) == getFunctionId(p)
     167    26679294 :                                 && getModuleId(q) == getModuleId(p)) {
     168    26679297 :                                 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    26679297 :                                 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    26677912 :                                 if (hasSameArguments(mb, p, q)
     184      136355 :                                         && hasSameSignature(mb, p, q)
     185      136337 :                                         && !hasCommonResults(p, q)
     186      136337 :                                         && !isUnsafeFunction(q)
     187      136337 :                                         && !isUpdateInstruction(q)
     188      136337 :                                         && !isProjectConst(q) &&        /* disable project(x,val), as its used for the result of case statements */
     189      122548 :                                         isLinearFlow(q)) {
     190      122548 :                                         if (safetyBarrier(p, q)) {
     191           0 :                                                 TRC_DEBUG(MAL_OPTIMIZER, "Safety barrier reached\n");
     192             :                                                 break;
     193             :                                         }
     194      122548 :                                         duplicate = 1;
     195      122548 :                                         clrFunction(p);
     196      122548 :                                         p->argc = p->retc;
     197      252896 :                                         for (k = 0; k < q->retc; k++) {
     198      130348 :                                                 alias[getArg(p, k)] = getArg(q, k);
     199             :                                                 /* we know the arguments fit so the instruction can safely be patched */
     200      130348 :                                                 p = pushArgument(mb, p, getArg(q, k));
     201             :                                         }
     202             : 
     203      122548 :                                         TRC_DEBUG(MAL_OPTIMIZER, "Modified expression %d -> %d ",
     204             :                                                           getArg(p, 0), getArg(p, 1));
     205      122548 :                                         traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     206             : 
     207      122548 :                                         actions++;
     208      122548 :                                         break;          /* end of search */
     209             :                                 }
     210     9400142 :                         } 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     7192352 :                 if (duplicate) {
     219      122548 :                         pushInstruction(mb, p);
     220      122548 :                         old[i] = NULL;
     221      122548 :                         continue;
     222             :                 }
     223             :                 /* update the hash structure with another candidate for re-use */
     224     7069804 :                 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     7069804 :                 traceInstruction(MAL_OPTIMIZER, mb, 0, p, LIST_MAL_ALL);
     228             : 
     229     7069764 :                 if (!mayhaveSideEffects(cntxt, mb, p, TRUE) && p->argc != p->retc
     230    14139427 :                         && isLinearFlow(p) && !isUnsafeFunction(p)
     231     7069685 :                         && !isUpdateInstruction(p)) {
     232     7069584 :                         list[i] = hash[h];
     233     7069584 :                         hash[h] = i;
     234     7069584 :                         pushInstruction(mb, p);
     235     7069568 :                         old[i] = NULL;
     236             :                 }
     237             :         }
     238    48258228 :         for (; i < slimit; i++)
     239    48050260 :                 if (old[i])
     240     5306381 :                         pushInstruction(mb, old[i]);
     241             :         /* Defense line against incorrect plans */
     242      207968 :         if (actions > 0) {
     243        8771 :                 msg = chkTypes(cntxt->usermodule, mb, FALSE);
     244        8771 :                 if (!msg)
     245        8771 :                         msg = chkFlow(mb);
     246        8771 :                 if (!msg)
     247        8771 :                         msg = chkDeclarations(mb);
     248             :         }
     249      199197 :   wrapup:
     250             :         /* keep actions taken as a fake argument */
     251      487586 :         (void) pushInt(mb, pci, actions);
     252             : 
     253      487583 :         if (alias)
     254      207965 :                 GDKfree(alias);
     255      487587 :         if (list)
     256      207969 :                 GDKfree(list);
     257      487587 :         if (hash)
     258      207969 :                 GDKfree(hash);
     259      487587 :         if (old)
     260      207969 :                 GDKfree(old);
     261      487587 :         return msg;
     262             : }

Generated by: LCOV version 1.14