hqlcse.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jlib.hpp"
  16. #include "jmisc.hpp"
  17. #include "jstream.ipp"
  18. #include "hql.hpp"
  19. #include "hqlcse.ipp"
  20. #include "hqlutil.hpp"
  21. #include "hqlcpputil.hpp"
  22. #include "hqlthql.hpp"
  23. #include "hqlcatom.hpp"
  24. #include "hqlfold.hpp"
  25. #include "hqlpmap.hpp"
  26. #include "hqlopt.hpp"
  27. #include "hqlcerrors.hpp"
  28. #include "hqlttcpp.ipp"
  29. #ifdef _DEBUG
  30. //#define TRACE_CSE
  31. #endif
  32. //The following allows x != y and x == y to be commoned up. It works, but currently disabled
  33. //because cse doesn't preserve short circuit of AND and OR, and some examples mean it will do more
  34. //work because the alias will always be evaluated. (e.g., salt1.xhql)
  35. //Really aliases need to be functional and executed on demand or something similar.
  36. //#define OPTIMIZE_INVERSE
  37. //---------------------------------------------------------------------------
  38. inline bool canWrapWithCSE(IHqlExpression * expr)
  39. {
  40. switch (expr->getOperator())
  41. {
  42. case no_mapto:
  43. return false;
  44. }
  45. return true;
  46. }
  47. bool canCreateTemporary(IHqlExpression * expr)
  48. {
  49. switch (expr->getOperator())
  50. {
  51. case no_range:
  52. case no_rangefrom:
  53. case no_rangeto:
  54. case no_rangecommon:
  55. case no_constant:
  56. case no_all:
  57. case no_mapto:
  58. case no_record:
  59. case no_attr:
  60. case no_attr_expr:
  61. case no_attr_link:
  62. case no_joined:
  63. case no_sizeof:
  64. case no_offsetof:
  65. case no_newtransform:
  66. case no_transform:
  67. case no_assign:
  68. case no_assignall:
  69. case no_left:
  70. case no_right:
  71. case no_self:
  72. case no_top:
  73. case no_activetable:
  74. case no_alias:
  75. case no_skip:
  76. case no_assert:
  77. case no_counter:
  78. case no_sortlist:
  79. case no_matched:
  80. case no_matchtext:
  81. case no_matchunicode:
  82. case no_matchposition:
  83. case no_matchlength:
  84. case no_matchattr:
  85. case no_matchrow:
  86. case no_matchutf8:
  87. case no_recordlist:
  88. case no_transformlist:
  89. case no_rowvalue:
  90. case no_pipe:
  91. case no_colon:
  92. case no_globalscope:
  93. case no_subgraph:
  94. case no_forcelocal:
  95. case no_forcenolocal:
  96. case no_allnodes:
  97. case no_thisnode:
  98. case no_libraryscopeinstance:
  99. case no_loopbody:
  100. return false;
  101. }
  102. return !expr->isAction() && !expr->isTransform();
  103. }
  104. //---------------------------------------------------------------------------
  105. /*
  106. Cse spotting...
  107. * Don't remove named symbols from items that aren't transformed.
  108. * Common items up regardless of the named symbol used to reference it.
  109. */
  110. CseSpotterInfo::CseSpotterInfo(IHqlExpression * expr) : NewTransformInfo(expr)
  111. {
  112. numRefs = 0;
  113. numAssociatedRefs = 0;
  114. alreadyAliased = false;
  115. canAlias = false;
  116. dontTransform = false;
  117. dontTransformSelector = false;
  118. treatAsAliased = false;
  119. inverse = NULL;
  120. annotatedExpr = NULL;
  121. }
  122. //worth aliasing if referenced more than once, and used more than once in the expressions that are going to be evaluated now
  123. bool CseSpotterInfo::worthAliasingOnOwn()
  124. {
  125. return numRefs > 1 && (numRefs != numAssociatedRefs);
  126. }
  127. bool CseSpotterInfo::worthAliasing()
  128. {
  129. if (!inverse)
  130. return worthAliasingOnOwn();
  131. //no_not will always traverse the inverse (at least once), so don't sum the two counts - just use the non inverted count
  132. if (original->getOperator() == no_not)
  133. return worthAliasingOnOwn() || inverse->worthAliasingOnOwn();
  134. if (inverse->original->getOperator() == no_not)
  135. return worthAliasingOnOwn();
  136. unsigned totalRefs = numRefs + inverse->numRefs;
  137. unsigned totalAssociatedRefs = numAssociatedRefs + inverse->numAssociatedRefs;
  138. if ((totalRefs > 1) && (totalRefs != totalAssociatedRefs))
  139. return true;
  140. return false;
  141. }
  142. //Do we create an alias for this node, or the other one?
  143. bool CseSpotterInfo::useInverseForAlias()
  144. {
  145. if (!inverse)
  146. return false;
  147. if (numRefs == numAssociatedRefs)
  148. return true;
  149. node_operator op = original->getOperator();
  150. switch (op)
  151. {
  152. case no_not:
  153. case no_ne:
  154. case no_notin:
  155. case no_notbetween:
  156. case no_notexists:
  157. return inverse->worthAliasingOnOwn();
  158. }
  159. node_operator invOp = inverse->original->getOperator();
  160. switch (invOp)
  161. {
  162. case no_not: return false; //No otherwise we'll expand recursively!
  163. case no_ne:
  164. case no_notin:
  165. case no_notbetween:
  166. case no_notexists:
  167. return !worthAliasingOnOwn();
  168. }
  169. return op > invOp;
  170. }
  171. static HqlTransformerInfo cseSpotterInfo("CseSpotter");
  172. CseSpotter::CseSpotter()
  173. : NewHqlTransformer(cseSpotterInfo)
  174. {
  175. canAlias = true;
  176. isAssociated = false;
  177. spottedCandidate = false;
  178. invariantSelector = NULL;
  179. createLocalAliases = false;
  180. createdAlias = false;
  181. }
  182. void CseSpotter::analyseAssociated(IHqlExpression * expr, unsigned pass)
  183. {
  184. isAssociated = true;
  185. analyse(expr, pass);
  186. isAssociated = false;
  187. }
  188. void CseSpotter::analyseExpr(IHqlExpression * expr)
  189. {
  190. CseSpotterInfo * extra = queryBodyExtra(expr);
  191. if (!extra->annotatedExpr && expr->isAnnotation())
  192. extra->annotatedExpr = expr;
  193. if (isAssociated)
  194. extra->numAssociatedRefs++;
  195. node_operator op = expr->getOperator();
  196. #ifdef OPTIMIZE_INVERSE
  197. if (getInverseOp(op) != no_none)
  198. {
  199. OwnedHqlExpr inverse = getInverse(expr);
  200. CseSpotterInfo * inverseExtra = queryBodyExtra(inverse);
  201. extra->inverse = inverseExtra;
  202. inverseExtra->inverse = extra;
  203. }
  204. #endif
  205. if (op == no_alias)
  206. {
  207. queryBodyExtra(expr->queryChild(0))->alreadyAliased = true;
  208. extra->alreadyAliased = true;
  209. }
  210. if (extra->numRefs++ != 0)
  211. {
  212. if (!spottedCandidate && extra->worthAliasing() && (op != no_alias))
  213. spottedCandidate = true;
  214. //if (canCreateTemporary(expr))
  215. return;
  216. }
  217. if (!containsPotentialCSE(expr))
  218. return;
  219. if (canAlias && !expr->isDataset())
  220. extra->canAlias = true;
  221. bool savedCanAlias = canAlias;
  222. if (expr->isDataset() && (op != no_select))// && (op != no_if))
  223. {
  224. //There is little point looking for CSEs within dataset expressions, because only a very small
  225. //minority which would correctly cse, and it can cause lots of problems - e.g., join conditions.
  226. unsigned first = getFirstActivityArgument(expr);
  227. unsigned num = getNumActivityArguments(expr);
  228. HqlExprArray children;
  229. bool defaultCanAlias = canAlias;
  230. ForEachChild(i, expr)
  231. {
  232. IHqlExpression * cur = expr->queryChild(i);
  233. if (i >= first && i < first+num)
  234. canAlias = defaultCanAlias;
  235. else
  236. canAlias = false;
  237. analyseExpr(cur);
  238. }
  239. }
  240. else
  241. PARENT::analyseExpr(expr);
  242. canAlias = savedCanAlias;
  243. }
  244. IHqlExpression * CseSpotter::createAliasOwn(IHqlExpression * expr, CseSpotterInfo * extra)
  245. {
  246. #ifdef TRACE_CSE
  247. StringBuffer s;
  248. DBGLOG("Create alias for %s (%d refs)", getExprIdentifier(s, expr).str(), extra->numRefs);
  249. #endif
  250. extra->alreadyAliased = true;
  251. if (createLocalAliases)
  252. return ::createAliasOwn(expr, createLocalAttribute());
  253. return ::createAliasOwn(expr, NULL);
  254. }
  255. IHqlExpression * CseSpotter::createTransformed(IHqlExpression * expr)
  256. {
  257. node_operator op = expr->getOperator();
  258. switch (op)
  259. {
  260. case no_matched:
  261. case no_matchtext:
  262. case no_matchunicode:
  263. case no_matchposition:
  264. case no_matchlength:
  265. case no_matchrow:
  266. case no_matchutf8:
  267. //These actually go wrong if we remove the named symbols, so traverse under no circumstances.
  268. //others can be traversed to patch up references to datasets that have changed.
  269. case no_translated:
  270. return LINK(expr);
  271. }
  272. OwnedHqlExpr transformed = PARENT::createTransformed(expr);
  273. CseSpotterInfo * splitter = queryBodyExtra(expr);
  274. //MORE: Possibly add a unique number to the alias when this starts worrying about child scopes.
  275. if (splitter->canAlias && splitter->worthAliasing() && checkPotentialCSE(expr, splitter))
  276. {
  277. if (splitter->useInverseForAlias())
  278. {
  279. OwnedHqlExpr inverse = getInverse(expr);
  280. OwnedHqlExpr transformedInverse = transform(inverse);
  281. return getInverse(transformedInverse);
  282. }
  283. createdAlias = true;
  284. //Use the transformed body to ensure that any cses only create a single instance,
  285. //But annotate with first annotation spotted, try and retain the symbols to aid debugging.
  286. LinkedHqlExpr aliasValue = transformed->queryBody();
  287. // if (splitter->annotatedExpr)
  288. // aliasValue.setown(splitter->annotatedExpr->cloneAllAnnotations(aliasValue));
  289. OwnedHqlExpr alias = createAliasOwn(aliasValue.getClear(), splitter);
  290. return alias.getClear();
  291. return expr->cloneAllAnnotations(alias);
  292. }
  293. return transformed.getClear();
  294. }
  295. ANewTransformInfo * CseSpotter::createTransformInfo(IHqlExpression * expr)
  296. {
  297. return CREATE_NEWTRANSFORMINFO(CseSpotterInfo, expr);
  298. }
  299. bool CseSpotter::containsPotentialCSE(IHqlExpression * expr)
  300. {
  301. switch (expr->getOperator())
  302. {
  303. case no_record:
  304. case no_attr:
  305. case no_attr_expr:
  306. case no_attr_link:
  307. case no_joined:
  308. case no_sizeof:
  309. case no_offsetof:
  310. case no_field:
  311. case no_evaluate: // MORE: This is an example of introducing a new scope...
  312. case no_translated: // Causes recursion otherwise....
  313. case no_left:
  314. case no_right:
  315. case no_top:
  316. case no_self:
  317. case no_selfref:
  318. case no_activetable:
  319. case no_filepos:
  320. case no_file_logicalname:
  321. case no_countfile:
  322. case no_matched:
  323. case no_matchtext:
  324. case no_matchunicode:
  325. case no_matchposition:
  326. case no_matchrow:
  327. case no_matchlength:
  328. case no_matchutf8:
  329. case no_catch:
  330. case no_projectrow:
  331. // case no_evalonce:
  332. return false;
  333. case no_select:
  334. return false; //isNewSelector(expr);
  335. case NO_AGGREGATE:
  336. //There may possibly be cses, but we would need to do lots of scoping analysis to work out whether they were
  337. //really common.
  338. return false;
  339. case no_assign:
  340. case no_assignall:
  341. case no_transform:
  342. case no_newtransform:
  343. case no_range:
  344. case no_rangefrom:
  345. case no_rangeto:
  346. case no_rangecommon:
  347. case no_skip:
  348. return true;
  349. case no_compound_diskread:
  350. case no_compound_indexread:
  351. case no_compound_disknormalize:
  352. case no_compound_diskaggregate:
  353. case no_compound_diskcount:
  354. case no_compound_diskgroupaggregate:
  355. case no_compound_indexnormalize:
  356. case no_compound_indexaggregate:
  357. case no_compound_indexcount:
  358. case no_compound_indexgroupaggregate:
  359. case no_compound_childread:
  360. case no_compound_childnormalize:
  361. case no_compound_childaggregate:
  362. case no_compound_childcount:
  363. case no_compound_childgroupaggregate:
  364. case no_compound_selectnew:
  365. case no_compound_inline:
  366. return false;
  367. #if 0
  368. //Strictly speaking, we shouldn't common up conditional expressions, but it generally provides such a reduction in code
  369. //that it will stay enabled until I come up with a better scheme.
  370. case no_if:
  371. case no_rejected:
  372. case no_which:
  373. case no_case:
  374. case no_map:
  375. return false;
  376. #endif
  377. }
  378. ITypeInfo * type = expr->queryType();
  379. if (type && type->getTypeCode() == type_void)
  380. return false;
  381. return !expr->isConstant();// || expr->isDataset() || expr->isDatarow();
  382. }
  383. bool CseSpotter::checkPotentialCSE(IHqlExpression * expr, CseSpotterInfo * extra)
  384. {
  385. if (extra->alreadyAliased)
  386. return false;
  387. if (!expr->isPure() || !canCreateTemporary(expr))
  388. return false;
  389. if (invariantSelector && exprReferencesDataset(expr, invariantSelector))
  390. return false;
  391. switch (expr->getOperator())
  392. {
  393. case no_eq:
  394. case no_ne:
  395. case no_gt:
  396. case no_ge:
  397. case no_lt:
  398. case no_le:
  399. {
  400. //Don't combine integer comparisons into a CSE - not worth it...
  401. ITypeInfo * type = expr->queryChild(0)->queryType();
  402. switch (type->getTypeCode())
  403. {
  404. case type_boolean:
  405. case type_int:
  406. return false;
  407. }
  408. return true;
  409. }
  410. case no_not:
  411. {
  412. IHqlExpression * child = expr->queryChild(0);
  413. if (queryBodyExtra(child)->isAliased())
  414. return false;
  415. break;
  416. }
  417. case no_charlen:
  418. {
  419. IHqlExpression * child = expr->queryChild(0);
  420. if (queryBodyExtra(child)->isAliased() || child->getOperator() == no_select)
  421. {
  422. type_t tc = child->queryType()->getTypeCode();
  423. switch (tc)
  424. {
  425. case type_varstring:
  426. case type_varunicode:
  427. return true;
  428. }
  429. //prevent (trivial-cast)length(x) from being serialized etc.
  430. extra->treatAsAliased = true;
  431. return false;
  432. }
  433. break;
  434. }
  435. case no_field:
  436. throwUnexpected();
  437. case no_select:
  438. return false; //expr->hasProperty(newAtom);
  439. case no_list:
  440. case no_datasetlist:
  441. case no_getresult: // these are commoned up in the code generator, so don't do it twice.
  442. case no_getgraphresult:
  443. case no_getgraphloopresult:
  444. case no_translated: // Causes recursion otherwise....
  445. case no_random:
  446. return false;
  447. case no_call:
  448. case no_externalcall:
  449. case no_libraryinput:
  450. case no_counter:
  451. return true;
  452. case no_substring:
  453. {
  454. IHqlExpression * child = expr->queryChild(0);
  455. // if (queryBodyExtra(child)->isAliased())
  456. {
  457. SubStringHelper helper(expr);
  458. return !helper.canGenerateInline();
  459. }
  460. return true;
  461. }
  462. case no_cast:
  463. case no_implicitcast:
  464. {
  465. ITypeInfo * exprType = expr->queryType();
  466. if (exprType->getTypeCode() == type_set)
  467. return false;
  468. IHqlExpression * uncast = expr->queryChild(0);
  469. if (uncast->queryValue())
  470. return false;
  471. //Ignore integral casts of items that have already been aliased
  472. if (queryBodyExtra(uncast)->isAliased())
  473. {
  474. if (exprType->isInteger() && uncast->queryType()->isInteger())
  475. {
  476. if (extra->numRefs < 5)
  477. return false;
  478. }
  479. }
  480. break;
  481. }
  482. //Following are all source datasets - no point in commoning them up
  483. //although probably exceptions e.g., table(,pipe)
  484. case no_none:
  485. case no_null:
  486. case no_anon:
  487. case no_pseudods:
  488. case no_all:
  489. // case no_table: - normally work commoning up
  490. case no_temptable:
  491. case no_inlinetable:
  492. case no_xmlproject:
  493. case no_datasetfromrow:
  494. case no_preservemeta:
  495. case no_dataset_alias:
  496. case no_workunit_dataset:
  497. case no_left:
  498. case no_right:
  499. case no_top:
  500. case no_self:
  501. case no_selfref:
  502. case no_keyindex:
  503. case no_newkeyindex:
  504. case no_fail:
  505. case no_activetable:
  506. case no_soapcall:
  507. case no_newsoapcall:
  508. case no_id2blob:
  509. case no_cppbody:
  510. case no_rows:
  511. return false;
  512. }
  513. if (!expr->queryType())
  514. return false;
  515. return (expr->numChildren() > 0);
  516. }
  517. IHqlExpression * CseSpotter::transform(IHqlExpression * expr)
  518. {
  519. return PARENT::transform(expr);
  520. }
  521. IHqlExpression * CseSpotter::queryAlreadyTransformed(IHqlExpression * expr)
  522. {
  523. CseSpotterInfo * extra = queryBodyExtra(expr);
  524. if (extra->dontTransform)
  525. return expr;
  526. IHqlExpression * ret = PARENT::queryAlreadyTransformed(expr);
  527. if (!ret)
  528. {
  529. IHqlExpression * body = expr->queryBody();
  530. if (body != expr)
  531. {
  532. ret = PARENT::queryAlreadyTransformed(body);
  533. if (ret == body)
  534. return NULL;
  535. }
  536. }
  537. return ret;
  538. }
  539. IHqlExpression * CseSpotter::queryAlreadyTransformedSelector(IHqlExpression * expr)
  540. {
  541. CseSpotterInfo * extra = queryBodyExtra(expr);
  542. if (extra->dontTransformSelector)
  543. return expr;
  544. return PARENT::queryAlreadyTransformedSelector(expr);
  545. }
  546. void CseSpotter::stopTransformation(IHqlExpression * expr)
  547. {
  548. IHqlExpression * normalized = expr->queryNormalizedSelector();
  549. queryBodyExtra(expr)->dontTransform = true;
  550. queryBodyExtra(normalized)->dontTransformSelector = true;
  551. }
  552. //---------------------------------------------------------------------------
  553. static HqlTransformerInfo conjunctionTransformerInfo("ConjunctionTransformer");
  554. ConjunctionTransformer::ConjunctionTransformer() : NewHqlTransformer(conjunctionTransformerInfo)
  555. {
  556. }
  557. IHqlExpression * ConjunctionTransformer::createTransformed(IHqlExpression * expr)
  558. {
  559. node_operator op = expr->getOperator();
  560. OwnedHqlExpr transformed;
  561. switch (op)
  562. {
  563. case no_matched:
  564. case no_matchtext:
  565. case no_matchunicode:
  566. case no_matchlength:
  567. case no_matchposition:
  568. case no_matchrow:
  569. case no_matchutf8:
  570. return LINK(expr);
  571. //not so sure why the following causes problems - because the tables get changed I think.
  572. case no_filepos:
  573. case no_file_logicalname:
  574. case no_sizeof:
  575. case no_offsetof:
  576. return LINK(expr);
  577. case no_and:
  578. case no_or:
  579. {
  580. IHqlExpression * left = expr->queryChild(0);
  581. if (left->getOperator() == op)
  582. {
  583. HqlExprArray args, transformedArgs;
  584. left->unwindList(args, op);
  585. ForEachItemIn(i, args)
  586. transformedArgs.append(*transform(&args.item(i)));
  587. transformedArgs.append(*transform(expr->queryChild(1)));
  588. transformed.setown(createLeftBinaryList(op, transformedArgs));
  589. // return expr->cloneAllAnnotations(transformed);
  590. }
  591. break;
  592. }
  593. }
  594. if (!transformed)
  595. transformed.setown(NewHqlTransformer::createTransformed(expr));
  596. return transformed.getClear();
  597. }
  598. //---------------------------------------------------------------------------
  599. #ifdef NEW_CSE_PROCESSING
  600. inline bool canInsertCodeAlias(IHqlExpression * expr)
  601. {
  602. switch (expr->getOperator())
  603. {
  604. case no_range:
  605. case no_rangefrom:
  606. case no_rangeto:
  607. case no_rangecommon:
  608. case no_mapto:
  609. case no_recordlist:
  610. case no_transformlist:
  611. case no_rowvalue:
  612. case no_sortlist:
  613. return false;
  614. default:
  615. return true;
  616. }
  617. }
  618. static HqlTransformerInfo cseScopeTransformerInfo("CseScopeTransformer");
  619. CseScopeTransformer::CseScopeTransformer()
  620. : NewHqlTransformer(cseScopeTransformerInfo)
  621. {
  622. activeParent = NULL;
  623. seq = 0;
  624. conditionDepth = 0;
  625. }
  626. void CseScopeTransformer::analyseExpr(IHqlExpression * expr)
  627. {
  628. expr = expr->queryBody();
  629. if (!containsNonGlobalAlias(expr))
  630. return;
  631. node_operator op = expr->getOperator();
  632. CseScopeInfo * splitter = queryExtra(expr);
  633. if (splitter->seq)
  634. {
  635. splitter->hasSharedParent = true;
  636. splitter->addParent(activeParent);
  637. return;
  638. }
  639. splitter->firstParent = activeParent;
  640. splitter->seq = ++seq;
  641. splitter->isUnconditional = (conditionDepth == 0);
  642. {
  643. IHqlExpression * savedParent = activeParent;
  644. activeParent = expr;
  645. switch (op)
  646. {
  647. case no_if:
  648. case no_or:
  649. case no_and:
  650. case no_case:
  651. {
  652. analyseExpr(expr->queryChild(0));
  653. conditionDepth++;
  654. ForEachChildFrom(i, expr, 1)
  655. analyseExpr(expr->queryChild(i));
  656. conditionDepth--;
  657. break;
  658. }
  659. default:
  660. NewHqlTransformer::analyseExpr(expr);
  661. break;
  662. }
  663. activeParent = savedParent;
  664. }
  665. //Add here so the cse are in the correct order to cope with dependencies...
  666. if (op == no_alias)
  667. {
  668. assertex(!expr->hasProperty(globalAtom));
  669. allCSEs.append(*LINK(splitter));
  670. }
  671. }
  672. bool CseScopeTransformer::attachCSEs(IHqlExpression * root)
  673. {
  674. bool changed = false;
  675. ForEachItemIn(idx, allCSEs)
  676. {
  677. CseScopeInfo& cur = allCSEs.item(idx);
  678. IHqlExpression * aliasLocation = findAliasLocation(&cur);
  679. if (!aliasLocation && cur.isUnconditional)
  680. aliasLocation = root;
  681. if (aliasLocation && aliasLocation != cur.original)
  682. {
  683. queryExtra(aliasLocation)->aliasesToDefine.append(*LINK(cur.original));
  684. changed = true;
  685. }
  686. }
  687. return changed;
  688. }
  689. IHqlExpression * CseScopeTransformer::createTransformed(IHqlExpression * expr)
  690. {
  691. //Can't short-circuit transformation if (!containsAlias(expr)) because it means references to transformed datasets won't get patched up
  692. IHqlExpression * body = expr->queryBody(true);
  693. if (body != expr)
  694. {
  695. OwnedHqlExpr ret = transform(body);
  696. return expr->cloneAnnotation(ret);
  697. }
  698. //slight difference from before...
  699. IHqlExpression * transformed = NewHqlTransformer::createTransformed(expr);
  700. CseScopeInfo * splitter = queryExtra(expr);
  701. if (splitter->aliasesToDefine.ordinality())
  702. {
  703. HqlExprArray args;
  704. args.append(*transformed);
  705. ForEachItemIn(idx, splitter->aliasesToDefine)
  706. {
  707. IHqlExpression * value = &splitter->aliasesToDefine.item(idx);
  708. args.append(*transform(value));
  709. }
  710. if (expr->isDataset())
  711. transformed = createDataset(no_alias_scope, args);
  712. else if (expr->isDatarow())
  713. transformed = createRow(no_alias_scope, args);
  714. else
  715. transformed = createValue(no_alias_scope, transformed->getType(), args);
  716. }
  717. return transformed;
  718. }
  719. ANewTransformInfo * CseScopeTransformer::createTransformInfo(IHqlExpression * expr)
  720. {
  721. return CREATE_NEWTRANSFORMINFO(CseScopeInfo, expr);
  722. }
  723. //First find the highest shared parent node (or this if no parents are shared)
  724. CseScopeInfo * CseScopeTransformer::calcCommonLocation(CseScopeInfo * extra)
  725. {
  726. if (extra->calcedCommonLocation)
  727. return extra->commonLocation;
  728. CseScopeInfo * commonLocation = extra;
  729. if (extra->firstParent)
  730. {
  731. CseScopeInfo * firstParentExtra = queryExtra(extra->firstParent);
  732. CseScopeInfo * commonParent = calcCommonLocation(firstParentExtra);
  733. if ((extra->parents.ordinality() == 0) && (!firstParentExtra->hasSharedParent || extra->firstParent->getOperator() == no_alias))
  734. // if ((extra->parents.ordinality() == 0) && !firstParentExtra->hasSharedParent)
  735. {
  736. //assertex(commonParent == firstParentExtra);
  737. //commonParent = extra;
  738. }
  739. else
  740. {
  741. extra->hasSharedParent = true;
  742. commonLocation = commonParent;
  743. ForEachItemIn(i, extra->parents)
  744. {
  745. CseScopeInfo * nextExtra = calcCommonLocation(queryExtra(extra->parents.item(i)));
  746. if (nextExtra->isUnconditional)
  747. extra->isUnconditional = true;
  748. commonLocation = findCommonPath(commonLocation, nextExtra);
  749. if (!commonLocation && extra->isUnconditional)
  750. break;
  751. }
  752. }
  753. }
  754. else
  755. {
  756. if (extra->hasSharedParent)
  757. commonLocation = NULL;
  758. }
  759. extra->calcedCommonLocation = true;
  760. extra->commonLocation = commonLocation;
  761. return commonLocation;
  762. }
  763. IHqlExpression * CseScopeTransformer::findAliasLocation(CseScopeInfo * extra)
  764. {
  765. CseScopeInfo * best = calcCommonLocation(extra);
  766. loop
  767. {
  768. if (!best)
  769. return NULL;
  770. IHqlExpression * bestLocation = best->original;
  771. if (canInsertCodeAlias(bestLocation))
  772. return bestLocation;
  773. best = selectParent(best);
  774. }
  775. }
  776. CseScopeInfo * CseScopeTransformer::selectParent(CseScopeInfo * info)
  777. {
  778. if (info->hasSharedParent)
  779. return info->commonLocation;
  780. if (!info->firstParent)
  781. return NULL;
  782. return queryExtra(info->firstParent);
  783. }
  784. CseScopeInfo * CseScopeTransformer::findCommonPath(CseScopeInfo * left, CseScopeInfo * right)
  785. {
  786. loop
  787. {
  788. if (!left || !right)
  789. return NULL;
  790. if (left == right)
  791. return left;
  792. if (left->seq > right->seq)
  793. left = selectParent(left);
  794. else
  795. right = selectParent(right);
  796. }
  797. }
  798. #else
  799. CSEentry::CSEentry(IHqlExpression * _value, PathArray & _path)
  800. {
  801. value.set(_value);
  802. unsigned depth=_path.ordinality();
  803. path.ensure(depth);
  804. ForEachItemIn(idx, _path)
  805. path.append(_path.item(idx));
  806. ensurePathValid();
  807. }
  808. void CSEentry::ensurePathValid()
  809. {
  810. //It is not valid to insert a no_code_alias at certain points....
  811. while (path.ordinality())
  812. {
  813. switch (path.tos().getOperator())
  814. {
  815. case no_range:
  816. case no_rangefrom:
  817. case no_rangeto:
  818. case no_rangecommon:
  819. case no_mapto:
  820. case no_recordlist:
  821. case no_transformlist:
  822. case no_rowvalue:
  823. case no_sortlist:
  824. path.pop();
  825. break;
  826. default:
  827. return;
  828. }
  829. }
  830. }
  831. void CSEentry::findCommonPath(PathArray & otherPath)
  832. {
  833. unsigned prevPath = path.ordinality();
  834. unsigned maxPath = path.ordinality();
  835. if (maxPath > otherPath.ordinality())
  836. maxPath = otherPath.ordinality();
  837. unsigned idx;
  838. for (idx = 0; idx < maxPath; idx++)
  839. {
  840. IHqlExpression * l = &path.item(idx);
  841. IHqlExpression * r = &otherPath.item(idx);
  842. if (l != r)
  843. break;
  844. }
  845. //Ensure the new location is valid for receiving the CSE
  846. while (idx != 0)
  847. {
  848. if (canWrapWithCSE(&path.item(idx-1)))
  849. break;
  850. idx--;
  851. }
  852. path.trunc(idx);
  853. if (prevPath != path.ordinality())
  854. {
  855. ForEachItemIn(idx2, dependsOn)
  856. dependsOn.item(idx2).findCommonPath(path);
  857. }
  858. ensurePathValid();
  859. }
  860. static HqlTransformerInfo cseScopeTransformerInfo("CseScopeTransformer");
  861. CseScopeTransformer::CseScopeTransformer()
  862. : NewHqlTransformer(cseScopeTransformerInfo)
  863. {
  864. }
  865. void CseScopeTransformer::analyseExpr(IHqlExpression * expr)
  866. {
  867. expr = expr->queryBody();
  868. if (!containsNonGlobalAlias(expr))
  869. return;
  870. CSEentry * cse = NULL;
  871. node_operator op = expr->getOperator();
  872. if (op == no_alias)
  873. {
  874. assertex(!expr->hasProperty(globalAtom));
  875. CseScopeInfo * splitter = queryExtra(expr);
  876. //PrintLog("splitter: %s", expr->toString(StringBuffer()).str());
  877. if (splitter->cseUse)
  878. {
  879. //Find the common path, and map the alias.
  880. CSEentry * cse = splitter->cseUse;
  881. cse->findCommonPath(path);
  882. if (activeCSE.ordinality())
  883. activeCSE.tos().dependsOn.append(*LINK(cse));
  884. return;
  885. }
  886. cse = new CSEentry(expr, path);
  887. splitter->cseUse.setown(cse);
  888. if (activeCSE.ordinality())
  889. activeCSE.tos().dependsOn.append(*LINK(cse));
  890. activeCSE.append(*LINK(cse));
  891. }
  892. #if 0
  893. if ((op == no_transform) || (op == no_newtransform))
  894. {
  895. //For a transform add each assignment as a path point - so the aliases for assignments don't end up
  896. //before aliases for skip attributes.
  897. path.append(*expr);
  898. ForEachChild(i, expr)
  899. {
  900. IHqlExpression * cur = expr->queryChild(i);
  901. analyseExpr(cur);
  902. path.append(*cur);
  903. }
  904. ForEachChild(i2, expr)
  905. path.pop();
  906. path.pop();
  907. }
  908. else
  909. #endif
  910. {
  911. path.append(*expr);
  912. NewHqlTransformer::analyseExpr(expr);
  913. path.pop();
  914. }
  915. //Add here so the cse are in the correct order to cope with dependencies...
  916. if (cse)
  917. {
  918. allCSEs.append(*LINK(cse));
  919. activeCSE.pop();
  920. }
  921. }
  922. bool CseScopeTransformer::attachCSEs(IHqlExpression * /*root*/)
  923. {
  924. bool changed = false;
  925. ForEachItemIn(idx, allCSEs)
  926. {
  927. CSEentry & cur = allCSEs.item(idx);
  928. if (cur.path.ordinality())
  929. {
  930. IHqlExpression & location = cur.path.tos();
  931. queryExtra(&location)->cseDefine.append(OLINK(cur));
  932. changed = true;
  933. }
  934. }
  935. return changed;
  936. }
  937. IHqlExpression * CseScopeTransformer::createTransformed(IHqlExpression * expr)
  938. {
  939. //Can't short-circuit transformation if (!containsAlias(expr)) because it means references to transformed datasets won't get patched up
  940. IHqlExpression * body = expr->queryBody(true);
  941. if (body != expr)
  942. {
  943. OwnedHqlExpr ret = transform(body);
  944. return expr->cloneAnnotation(ret);
  945. }
  946. //slight difference from before...
  947. IHqlExpression * transformed = NewHqlTransformer::createTransformed(expr);
  948. CseScopeInfo * splitter = queryExtra(expr);
  949. if (splitter->cseDefine.ordinality())
  950. {
  951. HqlExprArray args;
  952. args.append(*transformed);
  953. ForEachItemIn(idx, splitter->cseDefine)
  954. {
  955. CSEentry & cur = splitter->cseDefine.item(idx);
  956. args.append(*transform(cur.value));
  957. }
  958. if (expr->isDataset())
  959. transformed = createDataset(no_alias_scope, args);
  960. else if (expr->isDatarow())
  961. transformed = createRow(no_alias_scope, args);
  962. else
  963. transformed = createValue(no_alias_scope, transformed->getType(), args);
  964. }
  965. return transformed;
  966. }
  967. ANewTransformInfo * CseScopeTransformer::createTransformInfo(IHqlExpression * expr)
  968. {
  969. return CREATE_NEWTRANSFORMINFO(CseScopeInfo, expr);
  970. }
  971. #endif
  972. IHqlExpression * spotScalarCSE(IHqlExpression * expr, IHqlExpression * limit)
  973. {
  974. if (expr->isConstant())
  975. return LINK(expr);
  976. switch (expr->getOperator())
  977. {
  978. case no_select:
  979. if (!expr->hasProperty(newAtom))
  980. return LINK(expr);
  981. break;
  982. }
  983. OwnedHqlExpr transformed = LINK(expr); //removeNamedSymbols(expr);
  984. bool addedAliases = false;
  985. //First spot the aliases - so that restructuring the ands doesn't lose any existing aliases.
  986. {
  987. CseSpotter spotter;
  988. spotter.analyse(transformed, 0);
  989. if (spotter.foundCandidates())
  990. {
  991. if (limit)
  992. spotter.stopTransformation(limit);
  993. transformed.setown(spotter.transformRoot(transformed));
  994. addedAliases = spotter.createdNewAliases();
  995. }
  996. }
  997. if (!containsAlias(transformed))
  998. return transformed.getClear();
  999. //Transform conjunctions so they are (a AND (b AND (c AND d))) not (((a AND b) AND c) AND d)
  1000. //so that alias scope can be introduced in a better place.
  1001. {
  1002. ConjunctionTransformer tr;
  1003. transformed.setown(tr.transformRoot(transformed));
  1004. }
  1005. if (!addedAliases)
  1006. return transformed.getClear();
  1007. //Now work out where in the tree the aliases should be evaluated.
  1008. {
  1009. CseScopeTransformer scoper;
  1010. scoper.analyse(transformed, 0);
  1011. if (scoper.attachCSEs(transformed))
  1012. transformed.setown(scoper.transformRoot(transformed));
  1013. }
  1014. return transformed.getClear();
  1015. }
  1016. void spotScalarCSE(SharedHqlExpr & expr, SharedHqlExpr & associated, IHqlExpression * limit, IHqlExpression * invariantSelector)
  1017. {
  1018. CseSpotter spotter;
  1019. spotter.analyse(expr, 0);
  1020. if (associated)
  1021. spotter.analyseAssociated(associated, 0);
  1022. if (!spotter.foundCandidates())
  1023. return;
  1024. if (limit)
  1025. spotter.stopTransformation(limit);
  1026. if (invariantSelector)
  1027. spotter.setInvariantSelector(invariantSelector);
  1028. expr.setown(spotter.transformRoot(expr));
  1029. associated.setown(spotter.transformRoot(associated));
  1030. }
  1031. void spotScalarCSE(HqlExprArray & exprs, HqlExprArray & associated, IHqlExpression * limit, IHqlExpression * invariantSelector)
  1032. {
  1033. CseSpotter spotter;
  1034. spotter.analyseArray(exprs, 0);
  1035. ForEachItemIn(ia, associated)
  1036. spotter.analyseAssociated(&associated.item(ia), 0);
  1037. if (!spotter.foundCandidates())
  1038. return;
  1039. if (limit)
  1040. spotter.stopTransformation(limit);
  1041. if (invariantSelector)
  1042. spotter.setInvariantSelector(invariantSelector);
  1043. HqlExprArray newExprs;
  1044. HqlExprArray newAssociated;
  1045. spotter.transformRoot(exprs, newExprs);
  1046. spotter.transformRoot(associated, newAssociated);
  1047. replaceArray(exprs, newExprs);
  1048. replaceArray(associated, newAssociated);
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. //The TableInvariantTransformer is important for ensuring that getResultXXX code is executed in the code context, amongst other things
  1052. //It must ensure that any global aliases couldn't contain some other global aliases inside a child query, otherwise when the child query is
  1053. //evaluated the result won't be in the correct place.
  1054. //
  1055. //MORE: This could be improved to work out whether it is worth creating an alias (which will then be serialized...)
  1056. //e.g., don't alias i) <alias<n>> +- offset or ii) extension of an alias's size., iii) substring of a fixed size string. iv) length(string
  1057. //however it is pretty good as it stands.
  1058. //ideally it would need information about how many times the expression is likely to be evaluated (e.g., 1/many)
  1059. //so that could be taken into account (e.g, filenames which are 'string' + conditional)
  1060. static bool canHoistInvariant(IHqlExpression * expr)
  1061. {
  1062. if (!canCreateTemporary(expr))
  1063. {
  1064. if ((expr->getOperator() != no_alias) || expr->hasProperty(globalAtom))
  1065. return false;
  1066. }
  1067. if (!expr->isPure())
  1068. return false;
  1069. switch (expr->getOperator())
  1070. {
  1071. case no_list:
  1072. case no_datasetlist:
  1073. return false; // probably don't want to hoist these
  1074. }
  1075. return true;
  1076. }
  1077. static HqlTransformerInfo tableInvariantTransformerInfo("TableInvariantTransformer");
  1078. TableInvariantTransformer::TableInvariantTransformer() : NewHqlTransformer(tableInvariantTransformerInfo)
  1079. {
  1080. canAlias = true;
  1081. }
  1082. bool TableInvariantTransformer::isInvariant(IHqlExpression * expr)
  1083. {
  1084. TableInvariantInfo * extra = queryBodyExtra(expr);
  1085. if (extra->cachedInvariant)
  1086. return extra->isInvariant;
  1087. bool invariant = false;
  1088. node_operator op = expr->getOperator();
  1089. switch (op)
  1090. {
  1091. case no_record:
  1092. case no_null:
  1093. case no_activetable:
  1094. case no_activerow:
  1095. case no_left:
  1096. case no_right:
  1097. case no_self:
  1098. case no_top:
  1099. case no_selfref:
  1100. case no_filepos:
  1101. case no_file_logicalname:
  1102. case no_joined:
  1103. case no_offsetof:
  1104. case no_sizeof:
  1105. case NO_AGGREGATE:
  1106. break;
  1107. case no_preservemeta:
  1108. invariant = isInvariant(expr->queryChild(0));
  1109. break;
  1110. case no_constant:
  1111. case no_workunit_dataset:
  1112. case no_getresult:
  1113. case no_getgraphresult:
  1114. case no_countfile:
  1115. invariant = true;
  1116. break;
  1117. case no_select:
  1118. {
  1119. IHqlExpression * ds = expr->queryChild(0);
  1120. if ((expr->hasProperty(newAtom) || ds->isDatarow()) && !expr->isDataset())
  1121. invariant = isInvariant(ds);
  1122. break;
  1123. }
  1124. case no_newaggregate:
  1125. {
  1126. //Allow these on a very strict subset of the datasets - to ensure that no potential globals can be included in the dataset
  1127. if (!isInvariant(expr->queryChild(0)))
  1128. break;
  1129. switch (querySimpleAggregate(expr, false, true))
  1130. {
  1131. case no_existsgroup:
  1132. case no_countgroup:
  1133. invariant = true;
  1134. break;
  1135. }
  1136. break;
  1137. }
  1138. case no_selectnth:
  1139. switch (expr->queryChild(1)->getOperator())
  1140. {
  1141. case no_constant:
  1142. case no_counter:
  1143. invariant = isInvariant(expr->queryChild(0));
  1144. break;
  1145. }
  1146. break;
  1147. default:
  1148. if (!isContextDependent(expr))
  1149. {
  1150. if (!expr->isAction())// && !expr->isDataset() && !expr->isDatarow())
  1151. {
  1152. invariant = true;
  1153. ForEachChild(i, expr)
  1154. {
  1155. IHqlExpression * cur = expr->queryChild(i);
  1156. if (!isInvariant(cur))
  1157. {
  1158. invariant = false;
  1159. break;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. break;
  1165. }
  1166. extra->cachedInvariant = true;
  1167. extra->isInvariant = invariant;
  1168. return invariant;
  1169. }
  1170. #if 0
  1171. void TableInvariantTransformer::analyseExpr(IHqlExpression * expr)
  1172. {
  1173. expr = expr->queryBody();
  1174. if (alreadyVisited(expr))
  1175. return;
  1176. node_operator op = expr->getOperator();
  1177. switch (op)
  1178. {
  1179. case no_record:
  1180. case no_constant:
  1181. return;
  1182. }
  1183. if (isInvariant(expr) && !expr->isAttribute() && !expr->isConstant() && canHoistInvariant(expr))
  1184. {
  1185. TableInvariantInfo * extra = queryBodyExtra(expr);
  1186. if (op == no_alias)
  1187. {
  1188. if (!expr->hasProperty(globalAtom))
  1189. extra->createAlias = true;
  1190. }
  1191. else
  1192. extra->createAlias = true;
  1193. return;
  1194. }
  1195. if (op == no_attr_expr)
  1196. analyseChildren(expr);
  1197. else
  1198. NewHqlTransformer::analyseExpr(expr);
  1199. }
  1200. #else
  1201. void TableInvariantTransformer::analyseExpr(IHqlExpression * expr)
  1202. {
  1203. expr = expr->queryBody();
  1204. TableInvariantInfo * extra = queryBodyExtra(expr);
  1205. if (alreadyVisited(expr))
  1206. return;
  1207. //More - these need to be handled properly...
  1208. node_operator op = expr->getOperator();
  1209. switch (op)
  1210. {
  1211. case no_record:
  1212. case no_constant:
  1213. return;
  1214. }
  1215. //We are trying to ensure that any expressions that don't access fields that are dependent on the activeDatasets/context are only
  1216. //evaluated once => check for active dataset rather than any dataset
  1217. bool candidate = false;
  1218. if (!isContextDependent(expr) && !expr->isAttribute())
  1219. {
  1220. if (isInlineTrivialDataset(expr) && !expr->isConstant())
  1221. {
  1222. candidate = (op != no_null);
  1223. }
  1224. else
  1225. {
  1226. if (!containsActiveDataset(expr))
  1227. {
  1228. //MORE: We should be able to hoist constant datasets (e.g., temptables), but it causes problems
  1229. //e.g., stops items it contains from being aliased. So
  1230. if (!expr->isAction() && !expr->isDataset() && !expr->isDatarow())
  1231. {
  1232. switch (op)
  1233. {
  1234. case no_alias:
  1235. if (!expr->hasProperty(globalAtom))
  1236. extra->createAlias = true;
  1237. return;
  1238. default:
  1239. //MORE: We should be able to hoist constant datasets (e.g., temptables), but it causes problems
  1240. //e.g., stops items it contains from being aliased.
  1241. candidate = !expr->isConstant();
  1242. break;
  1243. }
  1244. }
  1245. }
  1246. }
  1247. if (candidate && canHoistInvariant(expr))
  1248. {
  1249. extra->createAlias = true;
  1250. return;
  1251. }
  1252. }
  1253. if (op == no_attr_expr)
  1254. analyseChildren(expr);
  1255. else
  1256. NewHqlTransformer::analyseExpr(expr);
  1257. }
  1258. #endif
  1259. bool TableInvariantTransformer::isTrivialAlias(IHqlExpression * expr)
  1260. {
  1261. switch (expr->getOperator())
  1262. {
  1263. case no_cast:
  1264. case no_implicitcast:
  1265. //Don't create aliases for items that are simply integral casts of other aliases.
  1266. {
  1267. ITypeInfo * type = expr->queryType();
  1268. if (type->isInteger())
  1269. {
  1270. IHqlExpression * cast = expr->queryChild(0);
  1271. ITypeInfo * castType = cast->queryType();
  1272. if (castType->isInteger() && (queryBodyExtra(cast)->createAlias || cast->getOperator() == no_alias))
  1273. {
  1274. switch (type->getSize())
  1275. {
  1276. case 1: case 2: case 4: case 8:
  1277. return true;
  1278. }
  1279. }
  1280. }
  1281. break;
  1282. }
  1283. case no_not:
  1284. {
  1285. IHqlExpression * child = expr->queryChild(0);
  1286. if (queryBodyExtra(child)->createAlias || child->getOperator() == no_alias)
  1287. return true;
  1288. break;
  1289. }
  1290. }
  1291. return false;
  1292. }
  1293. IHqlExpression * TableInvariantTransformer::createTransformed(IHqlExpression * expr)
  1294. {
  1295. if (expr->getOperator() == no_alias)
  1296. {
  1297. OwnedHqlExpr newChild = transform(expr->queryChild(0));
  1298. if (newChild->getOperator() == no_alias)
  1299. return newChild.getClear();
  1300. }
  1301. OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
  1302. if (queryBodyExtra(expr)->createAlias)
  1303. {
  1304. if (!isTrivialAlias(expr))
  1305. {
  1306. OwnedHqlExpr attr = createAttribute(globalAtom);
  1307. if (transformed->getOperator() == no_alias)
  1308. transformed.set(transformed->queryChild(0));
  1309. return createAlias(transformed->queryBody(), attr);
  1310. }
  1311. }
  1312. return transformed.getClear();
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. IHqlExpression * spotTableInvariant(IHqlExpression * expr)
  1316. {
  1317. TableInvariantTransformer transformer;
  1318. transformer.analyse(expr, 0);
  1319. return transformer.transformRoot(expr);
  1320. }
  1321. IHqlExpression * spotTableInvariantChildren(IHqlExpression * expr)
  1322. {
  1323. TableInvariantTransformer transformer;
  1324. ForEachChild(i1, expr)
  1325. transformer.analyse(expr->queryChild(i1), 0);
  1326. return transformer.transformRoot(expr);
  1327. }
  1328. //---------------------------------------------------------------------------
  1329. static HqlTransformerInfo globalAliasTransformerInfo("GlobalAliasTransformer");
  1330. GlobalAliasTransformer::GlobalAliasTransformer() : NewHqlTransformer(globalAliasTransformerInfo)
  1331. {
  1332. insideGlobal = false;
  1333. }
  1334. void GlobalAliasTransformer::analyseExpr(IHqlExpression * expr)
  1335. {
  1336. if (!containsAlias(expr))
  1337. return;
  1338. bool wasInsideGlobal = insideGlobal;
  1339. GlobalAliasInfo * extra = queryBodyExtra(expr);
  1340. extra->numUses++;
  1341. if (expr->getOperator() == no_alias)
  1342. {
  1343. if (expr->hasProperty(globalAtom))
  1344. {
  1345. // assertex(!containsActiveDataset(expr) || isInlineTrivialDataset(expr));
  1346. if (!insideGlobal)
  1347. extra->isOuter = true;
  1348. }
  1349. if (extra->numUses > 1)
  1350. return;
  1351. if (extra->isOuter)
  1352. insideGlobal = true;
  1353. }
  1354. else
  1355. {
  1356. //ugly, but we need to walk children more than once even if we've already been here.
  1357. //What is important is if visited >1 or occur globally, so can short circuit based on that condition.
  1358. //This currently links too many times because subsequent cse generation may common up multiple uses of the same item
  1359. //but it's not too bad.
  1360. //We could rerun this again if that was a major issue.
  1361. if (insideGlobal)
  1362. {
  1363. if (extra->numUses > 2)
  1364. return; // may need to visit children more than once so that alias is linked twice.
  1365. }
  1366. else
  1367. {
  1368. if (extra->isOuter && (extra->numUses > 2))
  1369. return;
  1370. extra->isOuter = true;
  1371. }
  1372. }
  1373. if (expr->getOperator() == no_attr_expr)
  1374. analyseChildren(expr);
  1375. else
  1376. NewHqlTransformer::analyseExpr(expr);
  1377. insideGlobal = wasInsideGlobal;
  1378. }
  1379. IHqlExpression * GlobalAliasTransformer::createTransformed(IHqlExpression * expr)
  1380. {
  1381. OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
  1382. if ((expr->getOperator() == no_alias))
  1383. {
  1384. GlobalAliasInfo * extra = queryBodyExtra(expr);
  1385. if (expr->hasProperty(globalAtom))
  1386. {
  1387. if (!extra->isOuter)
  1388. {
  1389. if (extra->numUses == 1)
  1390. return LINK(transformed->queryChild(0));
  1391. if (!expr->hasProperty(localAtom))
  1392. return appendLocalAttribute(transformed);
  1393. }
  1394. else if (expr->hasProperty(localAtom))
  1395. {
  1396. //Should never occur - but just about conceivable that some kind of constant folding
  1397. //might cause a surrounding global alias to be removed.
  1398. return removeLocalAttribute(transformed);
  1399. }
  1400. }
  1401. else
  1402. {
  1403. if ((extra->numUses == 1) && !expr->hasProperty(internalAtom))
  1404. return LINK(transformed->queryChild(0));
  1405. }
  1406. }
  1407. return transformed.getClear();
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. IHqlExpression * optimizeActivityAliasReferences(IHqlExpression * expr)
  1411. {
  1412. if (!containsAlias(expr))
  1413. return LINK(expr);
  1414. unsigned first = getFirstActivityArgument(expr);
  1415. unsigned last = first + getNumActivityArguments(expr);
  1416. bool foundAlias = false;
  1417. ForEachChild(i1, expr)
  1418. {
  1419. IHqlExpression * cur = expr->queryChild(i1);
  1420. if (((i1 < first) || (i1 >= last)) && containsAlias(cur))
  1421. {
  1422. foundAlias = true;
  1423. break;
  1424. }
  1425. }
  1426. if (!foundAlias)
  1427. return LINK(expr);
  1428. GlobalAliasTransformer transformer;
  1429. ForEachChild(i2, expr)
  1430. {
  1431. IHqlExpression * cur = expr->queryChild(i2);
  1432. if (((i2 < first) || (i2 >= last)) && containsAlias(cur))
  1433. transformer.analyse(cur, 0);
  1434. }
  1435. HqlExprArray args;
  1436. ForEachChild(i3, expr)
  1437. {
  1438. IHqlExpression * cur = expr->queryChild(i3);
  1439. if ((i3 < first) || (i3 >= last))
  1440. args.append(*transformer.transformRoot(cur));
  1441. else
  1442. args.append(*LINK(cur));
  1443. }
  1444. return cloneOrLink(expr, args);
  1445. }