hqlstmt.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904
  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 "jliball.hpp"
  15. #include "hql.hpp"
  16. #include "platform.h"
  17. #include "jlib.hpp"
  18. #include "jexcept.hpp"
  19. #include "jmisc.hpp"
  20. #include "hqlexpr.hpp"
  21. #include "hqlstmt.hpp"
  22. #include "hqlstmt.ipp"
  23. #include "hqlfunc.hpp"
  24. #include "hqlcpp.ipp"
  25. #include "hqlcatom.hpp"
  26. #include "hqlcpputil.hpp"
  27. #include "hqlutil.hpp"
  28. #define CLEAR_COPY_THRESHOLD 100
  29. //---------------------------------------------------------------------------
  30. struct HQLCPP_API HqlBoundDefinedValue : public HqlDefinedValue
  31. {
  32. public:
  33. HqlBoundDefinedValue(IHqlExpression * _original, const CHqlBoundExpr & _bound) : HqlDefinedValue(_original)
  34. { bound.set(_bound); }
  35. virtual IHqlExpression * queryExpr() const { return bound.expr; }
  36. virtual void getBound(CHqlBoundExpr & result) { result.set(bound); }
  37. public:
  38. CHqlBoundExpr bound;
  39. };
  40. void HqlExprAssociation::getBound(CHqlBoundExpr & result)
  41. {
  42. result.expr.set(queryExpr());
  43. }
  44. //---------------------------------------------------------------------------
  45. BuildCtx::BuildCtx(HqlCppInstance & _state, _ATOM section) : state(_state)
  46. {
  47. init(state.ensureSection(section));
  48. }
  49. BuildCtx::BuildCtx(HqlCppInstance & _state) : state(_state)
  50. {
  51. init(NULL);
  52. }
  53. BuildCtx::BuildCtx(BuildCtx & _owner) : state(_owner.state)
  54. {
  55. init(_owner.curStmts);
  56. ignoreInput = _owner.ignoreInput;
  57. curPriority = _owner.curPriority;
  58. nextPriority = _owner.nextPriority;
  59. ignoreInput = false;
  60. }
  61. BuildCtx::BuildCtx(BuildCtx & _owner, HqlStmts * _root) : state(_owner.state)
  62. {
  63. init(_root);
  64. }
  65. BuildCtx::~BuildCtx()
  66. {
  67. }
  68. void BuildCtx::set(_ATOM section)
  69. {
  70. init(state.ensureSection(section));
  71. }
  72. void BuildCtx::set(BuildCtx & _owner)
  73. {
  74. init(_owner.curStmts);
  75. ignoreInput = _owner.ignoreInput;
  76. curPriority = _owner.curPriority;
  77. nextPriority = _owner.nextPriority;
  78. ignoreInput = false;
  79. }
  80. IHqlStmt * BuildCtx::addAlias(IHqlStmt * aliased)
  81. {
  82. if (ignoreInput)
  83. return NULL;
  84. HqlCompoundStmt * next = new HqlCompoundStmt(alias_stmt, curStmts);
  85. HqlStmt * cast = dynamic_cast<HqlStmt *>(aliased);
  86. assertex(cast);
  87. next->code.append(*LINK(cast));
  88. return appendSimple(next);
  89. }
  90. IHqlStmt * BuildCtx::addAssign(IHqlExpression * target, IHqlExpression * value)
  91. {
  92. if (ignoreInput)
  93. return NULL;
  94. HqlStmt * next = new HqlStmt(assign_stmt, curStmts);
  95. next->addExpr(LINK(target));
  96. next->addExpr(LINK(value));
  97. return appendSimple(next);
  98. }
  99. IHqlStmt * BuildCtx::addAssignIncrement(IHqlExpression * target, IHqlExpression * value)
  100. {
  101. if (ignoreInput)
  102. return NULL;
  103. if (value && !matchesConstantValue(value, 1))
  104. {
  105. HqlStmt * next = new HqlStmt(assigninc_stmt, curStmts);
  106. next->addExpr(LINK(target));
  107. next->addExpr(LINK(value));
  108. return appendSimple(next);
  109. }
  110. else
  111. {
  112. OwnedHqlExpr inc = createValue(no_postinc, target->getType(), LINK(target));
  113. return addExprOwn(inc.getClear());
  114. }
  115. }
  116. IHqlStmt * BuildCtx::addAssignDecrement(IHqlExpression * target, IHqlExpression * value)
  117. {
  118. if (ignoreInput)
  119. return NULL;
  120. if (value && !matchesConstantValue(value, 1))
  121. {
  122. HqlStmt * next = new HqlStmt(assigndec_stmt, curStmts);
  123. next->addExpr(LINK(target));
  124. next->addExpr(LINK(value));
  125. return appendSimple(next);
  126. }
  127. else
  128. {
  129. OwnedHqlExpr inc = createValue(no_postdec, LINK(target->getType()), LINK(target));
  130. return addExprOwn(inc.getClear());
  131. }
  132. }
  133. IHqlStmt * BuildCtx::addBlock()
  134. {
  135. if (ignoreInput)
  136. return NULL;
  137. HqlCompoundStmt * next = new HqlCompoundStmt(block_stmt, curStmts);
  138. return appendCompound(next);
  139. }
  140. IHqlStmt * BuildCtx::addBreak()
  141. {
  142. if (ignoreInput)
  143. return NULL;
  144. HqlStmt * next = new HqlStmt(break_stmt, curStmts);
  145. return appendSimple(next);
  146. }
  147. IHqlStmt * BuildCtx::addCase(IHqlStmt * _owner, IHqlExpression * source)
  148. {
  149. if (ignoreInput)
  150. return NULL;
  151. assertThrow(_owner->getStmt() == switch_stmt);
  152. HqlCompoundStmt & owner = (HqlCompoundStmt &)*_owner;
  153. curStmts = &owner.code;
  154. HqlCompoundStmt * next = new HqlCompoundStmt(case_stmt, curStmts);
  155. next->addExpr(LINK(source));
  156. return appendCompound(next);
  157. }
  158. IHqlStmt * BuildCtx::addContinue()
  159. {
  160. if (ignoreInput)
  161. return NULL;
  162. HqlStmt * next = new HqlStmt(continue_stmt, curStmts);
  163. return appendSimple(next);
  164. }
  165. IHqlStmt * BuildCtx::addDeclare(IHqlExpression * name, IHqlExpression * value)
  166. {
  167. assertex(name->getOperator() == no_variable);
  168. if (ignoreInput)
  169. return NULL;
  170. HqlStmt * next = new HqlStmt(declare_stmt, curStmts);
  171. next->addExpr(LINK(name));
  172. if (value)
  173. next->addExpr(LINK(value));
  174. appendSimple(next);
  175. return next;
  176. }
  177. IHqlStmt * BuildCtx::addDeclareExternal(IHqlExpression * name)
  178. {
  179. assertex(name->getOperator() == no_variable);
  180. if (ignoreInput)
  181. return NULL;
  182. HqlStmt * next = new HqlStmt(external_stmt, curStmts);
  183. next->addExpr(LINK(name));
  184. appendSimple(next);
  185. return next;
  186. }
  187. IHqlStmt * BuildCtx::addDeclareAssign(IHqlExpression * name, IHqlExpression * value)
  188. {
  189. addDeclare(name);
  190. return addAssign(name, value);
  191. }
  192. IHqlStmt * BuildCtx::addDefault(IHqlStmt * _owner)
  193. {
  194. if (ignoreInput)
  195. return NULL;
  196. assertThrow(_owner->getStmt() == switch_stmt);
  197. selectCompound(_owner);
  198. HqlCompoundStmt * next = new HqlCompoundStmt(default_stmt, curStmts);
  199. return appendCompound(next);
  200. }
  201. IHqlStmt * BuildCtx::addExpr(IHqlExpression * value)
  202. {
  203. if (ignoreInput)
  204. return NULL;
  205. HqlStmt * next = new HqlStmt(expr_stmt, curStmts);
  206. next->addExpr(LINK(value));
  207. return appendSimple(next);
  208. }
  209. IHqlStmt * BuildCtx::addExprOwn(IHqlExpression * value)
  210. {
  211. if (ignoreInput)
  212. {
  213. value->Release();
  214. return NULL;
  215. }
  216. HqlStmt * next = new HqlStmt(expr_stmt, curStmts);
  217. next->addExpr(value);
  218. return appendSimple(next);
  219. }
  220. IHqlStmt * BuildCtx::addReturn(IHqlExpression * value)
  221. {
  222. if (ignoreInput)
  223. return NULL;
  224. HqlStmt * next = new HqlStmt(return_stmt, curStmts);
  225. if (value)
  226. next->addExpr( LINK(value));
  227. return appendSimple(next);
  228. }
  229. IHqlStmt * BuildCtx::addFilter(IHqlExpression * condition)
  230. {
  231. HqlCompoundStmt * next = new HqlCompoundStmt(filter_stmt, curStmts);
  232. next->addExpr(LINK(condition));
  233. appendCompound(next);
  234. addBlock();
  235. return next;
  236. }
  237. IHqlStmt * BuildCtx::addFunction(IHqlExpression * funcdef)
  238. {
  239. if (ignoreInput)
  240. return NULL;
  241. HqlCompoundStmt * next = new HqlCompoundStmt(function_stmt, curStmts);
  242. next->addExpr(LINK(funcdef));
  243. return appendCompound(next);
  244. }
  245. IHqlStmt * BuildCtx::addIndirection(const BuildCtx & _parent)
  246. {
  247. HqlCompoundStmt * next = new HqlCompoundStmt(indirect_stmt, _parent.curStmts);
  248. return appendCompound(next);
  249. }
  250. IHqlStmt * BuildCtx::addLoop(IHqlExpression * cond, IHqlExpression * inc, bool atEnd)
  251. {
  252. if (ignoreInput)
  253. return NULL;
  254. HqlCompoundStmt * next = new HqlCompoundStmt(loop_stmt, curStmts);
  255. if (cond)
  256. next->addExpr(LINK(cond));
  257. if (inc)
  258. next->addExpr(LINK(inc));
  259. if (atEnd)
  260. next->addExpr(createAttribute(endAtom));
  261. return appendCompound(next);
  262. }
  263. IHqlStmt * BuildCtx::addGoto(const char * labelText)
  264. {
  265. if (ignoreInput)
  266. return NULL;
  267. HqlStmt * next = new HqlStmt(goto_stmt, curStmts);
  268. IHqlExpression * label= createVariable(labelText, makeBoolType());
  269. next->addExpr(label);
  270. return appendSimple(next);
  271. }
  272. IHqlStmt * BuildCtx::addGroup()
  273. {
  274. if (ignoreInput)
  275. return NULL;
  276. HqlCompoundStmt * next = new HqlCompoundStmt(group_stmt, curStmts);
  277. return appendCompound(next);
  278. }
  279. IHqlStmt * BuildCtx::addGroupPass(IHqlExpression * pass)
  280. {
  281. if (ignoreInput)
  282. return NULL;
  283. HqlCompoundStmt * next = new HqlCompoundStmt(pass_stmt, curStmts);
  284. next->addExpr(LINK(pass));
  285. return appendCompound(next);
  286. }
  287. IHqlStmt * BuildCtx::addLabel(const char * labelText)
  288. {
  289. if (ignoreInput)
  290. return NULL;
  291. HqlStmt * next = new HqlStmt(label_stmt, curStmts);
  292. IHqlExpression * label= createVariable(labelText, makeBoolType());
  293. next->addExpr(label);
  294. return appendSimple(next);
  295. }
  296. IHqlStmt * BuildCtx::addLine(const char * filename, unsigned lineNum)
  297. {
  298. if (ignoreInput)
  299. return NULL;
  300. HqlStmt * next = new HqlStmt(line_stmt, curStmts);
  301. if (filename)
  302. {
  303. next->addExpr(createConstant(filename));
  304. next->addExpr(createConstant(createIntValue(lineNum, sizeof(int), true)));
  305. }
  306. return appendSimple(next);
  307. }
  308. IHqlStmt * BuildCtx::addQuoted(const char * text)
  309. {
  310. if (ignoreInput)
  311. return NULL;
  312. HqlStmt * next = new HqlQuoteStmt(quote_stmt, curStmts, text);
  313. return appendSimple(next);
  314. }
  315. IHqlStmt * BuildCtx::addQuotedF(const char * format, ...)
  316. {
  317. if (ignoreInput)
  318. return NULL;
  319. StringBuffer text;
  320. va_list args;
  321. va_start(args, format);
  322. text.valist_appendf(format, args);
  323. va_end(args);
  324. HqlStmt * next = new HqlQuoteStmt(quote_stmt, curStmts, text.str());
  325. return appendSimple(next);
  326. }
  327. IHqlStmt * BuildCtx::addQuotedCompound(const char * text, const char * extra)
  328. {
  329. if (ignoreInput)
  330. return NULL;
  331. HqlCompoundStmt * next = new HqlQuoteStmt(quote_compound_stmt, curStmts, text);
  332. if (extra)
  333. next->addExpr(createQuoted(extra, makeVoidType()));
  334. return appendCompound(next);
  335. }
  336. IHqlStmt * BuildCtx::addQuotedCompoundOpt(const char * text, const char * extra)
  337. {
  338. if (ignoreInput)
  339. return NULL;
  340. HqlCompoundStmt * next = new HqlQuoteStmt(quote_compoundopt_stmt, curStmts, text);
  341. if (extra)
  342. next->addExpr(createQuoted(extra, makeVoidType()));
  343. return appendCompound(next);
  344. }
  345. IHqlStmt * BuildCtx::addSwitch(IHqlExpression * source)
  346. {
  347. if (ignoreInput)
  348. return NULL;
  349. HqlCompoundStmt * next = new HqlCompoundStmt(switch_stmt, curStmts);
  350. next->addExpr(LINK(source));
  351. return appendCompound(next);
  352. }
  353. HqlStmt * BuildCtx::appendCompound(HqlCompoundStmt * next)
  354. {
  355. assertThrow(!ignoreInput);
  356. appendSimple(next);
  357. curStmts = &next->code;
  358. return next;
  359. }
  360. HqlStmt * BuildCtx::appendSimple(HqlStmt * next)
  361. {
  362. assertThrow(!ignoreInput);
  363. if (nextPriority == OutermostScopePrio)
  364. {
  365. appendToOutermostScope(next);
  366. }
  367. else
  368. {
  369. next->setPriority(nextPriority);
  370. curStmts->appendStmt(*next);
  371. }
  372. nextPriority = curPriority;
  373. return next;
  374. }
  375. void BuildCtx::appendToOutermostScope(HqlStmt * next)
  376. {
  377. HqlStmts * searchStmts = curStmts;
  378. HqlStmts * insertStmts = NULL;
  379. HqlStmt * insertBefore = NULL;
  380. loop
  381. {
  382. HqlStmt * owner = searchStmts->owner;
  383. if (!owner)
  384. break;
  385. HqlStmts * ownerStmts = owner->queryContainer();
  386. switch (owner->getStmt())
  387. {
  388. case quote_compound_stmt:
  389. case quote_compoundopt_stmt:
  390. case indirect_stmt:
  391. goto found;
  392. case group_stmt:
  393. break;
  394. default:
  395. insertBefore = owner;
  396. insertStmts = ownerStmts;
  397. break;
  398. }
  399. searchStmts = ownerStmts;
  400. }
  401. found:
  402. if (insertBefore)
  403. {
  404. next->setPriority(insertBefore->queryPriority());
  405. insertStmts->add(*next, insertStmts->find(*insertBefore));
  406. }
  407. else
  408. {
  409. next->setPriority(curPriority);
  410. curStmts->appendStmt(*next);
  411. }
  412. }
  413. void BuildCtx::associate(HqlExprAssociation & next)
  414. {
  415. assertex(next.represents->queryBody() == next.represents);
  416. if (!ignoreInput)
  417. {
  418. curStmts->appendOwn(OLINK(next));
  419. }
  420. }
  421. void BuildCtx::associateOwn(HqlExprAssociation & next)
  422. {
  423. assertex(next.represents->queryBody() == next.represents);
  424. if (!ignoreInput)
  425. {
  426. curStmts->appendOwn(next);
  427. }
  428. else
  429. next.Release(); // can cause serious problems....
  430. }
  431. HqlExprAssociation *BuildCtx::associateExpr(IHqlExpression * represents, IHqlExpression * expr)
  432. {
  433. if (!ignoreInput)
  434. {
  435. HqlExprAssociation * assoc = new HqlSimpleDefinedValue(represents->queryBody(), expr);
  436. curStmts->appendOwn(*assoc);
  437. return assoc;
  438. }
  439. return NULL;
  440. }
  441. HqlExprAssociation * BuildCtx::associateExpr(IHqlExpression * represents, const CHqlBoundExpr & bound)
  442. {
  443. if (!ignoreInput)
  444. {
  445. HqlExprAssociation * assoc = new HqlBoundDefinedValue(represents->queryBody(), bound);
  446. curStmts->appendOwn(*assoc);
  447. return assoc;
  448. }
  449. return NULL;
  450. }
  451. IHqlExpression * BuildCtx::getTempDeclare(ITypeInfo * type, IHqlExpression * value)
  452. {
  453. IHqlExpression * temp = createVariable(LINK(type));
  454. addDeclare(temp, value);
  455. return temp;
  456. }
  457. bool BuildCtx::hasAssociation(HqlExprAssociation & search, bool unconditional)
  458. {
  459. HqlStmts * searchStmts = curStmts;
  460. loop
  461. {
  462. if (searchStmts->defs.contains(search))
  463. return true;
  464. HqlStmt * limitStmt = searchStmts->queryStmt();
  465. if (!limitStmt)
  466. return false;
  467. if (!unconditional)
  468. {
  469. switch (limitStmt->getStmt())
  470. {
  471. case filter_stmt:
  472. if (!matchesBoolean(limitStmt->queryExpr(0), true))
  473. return false;
  474. break;
  475. case quote_compound_stmt:
  476. case quote_compoundopt_stmt:
  477. case switch_stmt:
  478. case case_stmt:
  479. case default_stmt:
  480. case loop_stmt:
  481. return false;
  482. }
  483. }
  484. searchStmts = limitStmt->queryContainer();
  485. }
  486. }
  487. void BuildCtx::walkAssociations(IAssociationVisitor & visitor)
  488. {
  489. HqlStmts * searchStmts = curStmts;
  490. // walk all associations in the tree before this one
  491. loop
  492. {
  493. CIArrayOf<HqlExprAssociation> & defs = searchStmts->defs;
  494. ForEachItemInRev(idx, defs)
  495. {
  496. HqlExprAssociation & cur = defs.item(idx);
  497. if (visitor.visit(cur))
  498. return;
  499. }
  500. HqlStmt * limitStmt = searchStmts->queryStmt();
  501. if (!limitStmt)
  502. break;
  503. searchStmts = limitStmt->queryContainer();
  504. }
  505. }
  506. HqlExprAssociation * BuildCtx::queryAssociation(IHqlExpression * search, AssocKind kind, HqlExprCopyArray * selectors)
  507. {
  508. HqlStmts * searchStmts = curStmts;
  509. if (!search)
  510. return NULL;
  511. search = search->queryBody();
  512. // search all statements in the tree before this one, to see
  513. // if an expression already exists... If so return the target
  514. // of the assignment.
  515. loop
  516. {
  517. const CIArrayOf<HqlExprAssociation> & defs = searchStmts->defs;
  518. #ifdef CACHE_DEFINITION_HASHES
  519. if (!selectors)
  520. {
  521. unsigned searchHash = getSearchHash(search);
  522. const DefinitionHashArray & hashes = searchStmts->exprHashes;
  523. ForEachItemInRev(idx, hashes)
  524. {
  525. if (hashes.item(idx) == searchHash)
  526. {
  527. HqlExprAssociation & cur = defs.item(idx);
  528. if (cur.represents == search)
  529. {
  530. if ((kind == AssocAny) || (cur.getKind() == kind))
  531. return &cur;
  532. }
  533. }
  534. }
  535. }
  536. else
  537. #endif
  538. {
  539. ForEachItemInRev(idx, defs)
  540. {
  541. HqlExprAssociation & cur = defs.item(idx);
  542. IHqlExpression * represents = cur.represents.get();
  543. if (selectors && (cur.getKind() == AssocCursor))
  544. {
  545. if (selectors->contains(*represents))
  546. return NULL;
  547. }
  548. if (represents == search)
  549. if ((kind == AssocAny) || (cur.getKind() == kind))
  550. return &cur;
  551. }
  552. }
  553. HqlStmt * limitStmt = searchStmts->queryStmt();
  554. if (!limitStmt)
  555. break;
  556. searchStmts = limitStmt->queryContainer();
  557. }
  558. return NULL;
  559. }
  560. void BuildCtx::removeAssociation(HqlExprAssociation * search)
  561. {
  562. if (!search)
  563. return;
  564. HqlStmts * searchStmts = curStmts;
  565. loop
  566. {
  567. bool matched = searchStmts->zap(*search);
  568. if (matched)
  569. return;
  570. HqlStmt * limitStmt = searchStmts->queryStmt();
  571. if (!limitStmt)
  572. break;
  573. searchStmts = limitStmt->queryContainer();
  574. }
  575. assertex(!"Association not found");
  576. }
  577. HqlExprAssociation * BuildCtx::queryFirstAssociation(AssocKind searchKind)
  578. {
  579. HqlStmts * searchStmts = curStmts;
  580. // search all statements in the tree before this one, to see
  581. // if an expression already exists... If so return the target
  582. // of the assignment.
  583. loop
  584. {
  585. CIArray & defs = searchStmts->defs;
  586. ForEachItemInRev(idx, defs)
  587. {
  588. HqlExprAssociation & cur = (HqlExprAssociation &)defs.item(idx);
  589. if (cur.getKind() == searchKind)
  590. return &cur;
  591. }
  592. HqlStmt * limitStmt = searchStmts->queryStmt();
  593. if (!limitStmt)
  594. break;
  595. searchStmts = limitStmt->queryContainer();
  596. }
  597. return NULL;
  598. }
  599. //Search for an association, but don't allow it to be conditional, or be hidden by the definition of a cursor.
  600. HqlExprAssociation * BuildCtx::queryFirstCommonAssociation(AssocKind searchKind)
  601. {
  602. HqlStmts * searchStmts = curStmts;
  603. // search all statements in the tree before this one, to see
  604. // if an expression already exists... If so return the target
  605. // of the assignment.
  606. loop
  607. {
  608. CIArray & defs = searchStmts->defs;
  609. ForEachItemInRev(idx, defs)
  610. {
  611. HqlExprAssociation & cur = (HqlExprAssociation &)defs.item(idx);
  612. AssocKind kind = cur.getKind();
  613. if (kind == searchKind)
  614. return &cur;
  615. if (kind == AssocCursor)
  616. return NULL;
  617. }
  618. HqlStmt * limitStmt = searchStmts->queryStmt();
  619. if (!limitStmt)
  620. break;
  621. switch (limitStmt->getStmt())
  622. {
  623. //case quote_compound_stmt:
  624. //case quote_compoundopt_stmt,
  625. case filter_stmt:
  626. case label_stmt:
  627. case switch_stmt:
  628. case case_stmt:
  629. case default_stmt:
  630. case break_stmt:
  631. case continue_stmt:
  632. return NULL;
  633. }
  634. searchStmts = limitStmt->queryContainer();
  635. }
  636. return NULL;
  637. }
  638. HqlExprAssociation * BuildCtx::queryMatchExpr(IHqlExpression * search)
  639. {
  640. HqlExprCopyArray selectors;
  641. search->gatherTablesUsed(NULL, &selectors);
  642. return queryAssociation(search, AssocExpr, selectors.ordinality() ? &selectors : NULL);
  643. }
  644. bool BuildCtx::getMatchExpr(IHqlExpression * expr, CHqlBoundExpr & tgt)
  645. {
  646. HqlExprAssociation * match = queryMatchExpr(expr);
  647. if (match)
  648. {
  649. match->getBound(tgt);
  650. return true;
  651. }
  652. return false;
  653. }
  654. void BuildCtx::init(HqlStmts * _root)
  655. {
  656. root = _root;
  657. curStmts = root;
  658. curPriority = NormalPrio;
  659. nextPriority = curPriority;
  660. ignoreInput = false;
  661. }
  662. bool BuildCtx::isChildOf(HqlStmt * stmt, HqlStmts * stmts)
  663. {
  664. //MORE: Could improve by using depths
  665. do
  666. {
  667. if (stmts->find(*stmt) != NotFound)
  668. return true;
  669. stmt = stmt->queryContainer()->queryStmt();
  670. } while (stmt);
  671. return false;
  672. }
  673. void BuildCtx::selectCompound(IHqlStmt * stmt)
  674. {
  675. HqlCompoundStmt & owner = (HqlCompoundStmt &)*stmt;
  676. curStmts = &owner.code;
  677. }
  678. void BuildCtx::selectContainer()
  679. {
  680. HqlStmt * limitStmt = curStmts->queryStmt();
  681. assertex(limitStmt);
  682. curStmts = limitStmt->queryContainer();
  683. assertex(curStmts);
  684. }
  685. void BuildCtx::selectElse(IHqlStmt * stmt)
  686. {
  687. //Ignoring input does not work, because code expects associations to be kept
  688. assertex(stmt);
  689. switch (stmt->getStmt())
  690. {
  691. case filter_stmt:
  692. assertThrow(stmt->numChildren() == 1);
  693. selectCompound(stmt);
  694. addBlock();
  695. break;
  696. default:
  697. throwUnexpected();
  698. break;
  699. }
  700. }
  701. unsigned BuildCtx::setPriority(unsigned newPrio)
  702. {
  703. unsigned oldPriority = curPriority;
  704. if (!ignoreInput)
  705. {
  706. curPriority = newPrio;
  707. nextPriority = curPriority;
  708. }
  709. return oldPriority;
  710. }
  711. void BuildCtx::setNextPriority(unsigned newPrio)
  712. {
  713. if (!ignoreInput)
  714. nextPriority = newPrio;
  715. }
  716. IHqlStmt * BuildCtx::recursiveGetBestContext(HqlStmts * searchStmts, HqlExprCopyArray & required)
  717. {
  718. //Is it ok to move the expression before the owner statement?
  719. //First fail if any of the datasets that this expression is dependent on are defined in this scope.
  720. if (required.ordinality())
  721. {
  722. ForEachItemIn(i, searchStmts->defs)
  723. {
  724. HqlExprAssociation & cur = (HqlExprAssociation &)searchStmts->defs.item(i);
  725. if (required.contains(*cur.represents.get()))
  726. return NULL;
  727. }
  728. }
  729. HqlStmt * owner = searchStmts->owner;
  730. //Now check for poor places to hoist
  731. bool worthHoistingHere = false;
  732. switch (owner->getStmt())
  733. {
  734. case block_stmt:
  735. case group_stmt:
  736. break;
  737. case quote_compound_stmt:
  738. case quote_compoundopt_stmt:
  739. case indirect_stmt:
  740. return NULL;
  741. case filter_stmt:
  742. case switch_stmt:
  743. //MORE: Should make whether something ishoisted dependent on efficiency of the filter condition
  744. break;
  745. case loop_stmt:
  746. //MORE: Should make it dependent on the ordinality of the loop condition.
  747. worthHoistingHere = true;
  748. break;
  749. case case_stmt:
  750. case default_stmt:
  751. //Can't hoist here
  752. break;
  753. default:
  754. throwUnexpected();
  755. }
  756. HqlStmts * container = owner->queryContainer();
  757. if (container->owner)// && canHoistInParent)
  758. {
  759. IHqlStmt * match = recursiveGetBestContext(container, required);
  760. if (match)
  761. return match;
  762. }
  763. if (!worthHoistingHere)
  764. return NULL;
  765. //We've found somewhere we can insert the expression....
  766. unsigned existingPos = container->find(*owner);
  767. assertex(existingPos != NotFound);
  768. //insert a group just before the current statement
  769. HqlCompoundStmt * next = new HqlCompoundStmt(group_stmt, container);
  770. next->setPriority(owner->queryPriority());
  771. container->add(*next, existingPos);
  772. curStmts = &next->code;
  773. return next;
  774. }
  775. IHqlStmt * BuildCtx::replaceExpr(IHqlStmt * stmt, IHqlExpression * expr)
  776. {
  777. //Highly dangerous - use with utmost care!
  778. assertex(stmt->getStmt() == expr_stmt);
  779. HqlStmt * castStmt = static_cast<HqlStmt *>(stmt);
  780. castStmt->killExprs();
  781. castStmt->addExpr(LINK(expr));
  782. return castStmt;
  783. }
  784. IHqlStmt * BuildCtx::selectBestContext(IHqlExpression * expr)
  785. {
  786. if (containsTranslated(expr) || !curStmts->owner)
  787. return NULL;
  788. //MORE: Access to global context, context and other things...
  789. HqlExprCopyArray inScope;
  790. expr->gatherTablesUsed(NULL, &inScope);
  791. return recursiveGetBestContext(curStmts, inScope);
  792. }
  793. //---------------------------------------------------------------------------
  794. HqlStmts::HqlStmts(HqlStmt * _owner) : owner(_owner)
  795. {
  796. }
  797. void HqlStmts::appendStmt(HqlStmt & stmt)
  798. {
  799. unsigned newPrio = stmt.queryPriority();
  800. unsigned right = ordinality();
  801. if (right == 0)
  802. {
  803. append(stmt);
  804. }
  805. else if (newPrio >= item(right-1).queryPriority())
  806. {
  807. while (item(right-1).isIncomplete())
  808. {
  809. if (newPrio > item(right-1).queryPriority())
  810. break;
  811. right--;
  812. if (right == 0)
  813. break;
  814. }
  815. add(stmt, right);
  816. }
  817. else
  818. {
  819. unsigned left = 0;
  820. while (right - left >= 2)
  821. {
  822. unsigned mid = (left + right - 1) / 2;
  823. HqlStmt & cur = item(mid);
  824. if (newPrio >= cur.queryPriority())
  825. left = mid+1;
  826. else
  827. right = mid+1;
  828. }
  829. if (newPrio >= item(left).queryPriority())
  830. ++left;
  831. while (left && item(left-1).isIncomplete() && (newPrio == item(left-1).queryPriority()))
  832. --left;
  833. add(stmt, left);
  834. }
  835. }
  836. //---------------------------------------------------------------------------
  837. HqlStmt::HqlStmt(StmtKind _kind, HqlStmts * _container)
  838. {
  839. kind = _kind;
  840. container = _container;
  841. incomplete = false;
  842. included = true;
  843. }
  844. void HqlStmt::addExpr(IHqlExpression * expr)
  845. {
  846. exprs.append(*expr);
  847. }
  848. StmtKind HqlStmt::getStmt()
  849. {
  850. return (StmtKind)kind;
  851. }
  852. StringBuffer & HqlStmt::getTextExtra(StringBuffer & out)
  853. {
  854. return out;
  855. }
  856. static bool isEmptyGroup(IHqlStmt * stmt)
  857. {
  858. if (!stmt)
  859. return true;
  860. switch (stmt->getStmt())
  861. {
  862. case group_stmt:
  863. case block_stmt:
  864. return stmt->numChildren() == 0;
  865. }
  866. return false;
  867. }
  868. bool HqlStmt::hasChildren() const
  869. {
  870. if (numChildren() == 0)
  871. return false;
  872. unsigned count = numChildren();
  873. for (unsigned index = 0; index < count; index++)
  874. {
  875. IHqlStmt * cur = queryChild(index);
  876. if (cur->isIncluded())
  877. return true;
  878. }
  879. return false;
  880. }
  881. bool HqlStmt::isIncluded() const
  882. {
  883. if (!included)
  884. return false;
  885. switch (kind)
  886. {
  887. case quote_compoundopt_stmt:
  888. case group_stmt:
  889. return hasChildren();
  890. case filter_stmt:
  891. if (isEmptyGroup(queryChild(0)) && isEmptyGroup(queryChild(1)))
  892. return false;
  893. break;
  894. }
  895. return true;
  896. }
  897. unsigned HqlStmt::numChildren() const
  898. {
  899. return 0;
  900. }
  901. IHqlStmt * HqlStmt::queryChild(unsigned index) const
  902. {
  903. return NULL;
  904. }
  905. HqlStmts * HqlStmt::queryContainer()
  906. {
  907. return container;
  908. }
  909. IHqlExpression * HqlStmt::queryExpr(unsigned index)
  910. {
  911. if (exprs.isItem(index))
  912. return &exprs.item(index);
  913. return NULL;
  914. }
  915. void HqlStmts::inheritDefinitions(HqlStmts & other)
  916. {
  917. ForEachItemIn(i, other.defs)
  918. {
  919. defs.append(OLINK(other.defs.item(i)));
  920. #ifdef CACHE_DEFINITION_HASHES
  921. exprHashes.append(other.exprHashes.item(i));
  922. #endif
  923. }
  924. }
  925. //---------------------------------------------------------------------------
  926. #ifdef _MSC_VER
  927. #pragma warning(push)
  928. #pragma warning( disable : 4355 ) // 'this' : used in base member initializer list
  929. #endif
  930. HqlCompoundStmt::HqlCompoundStmt(StmtKind _kind, HqlStmts * _container) : HqlStmt(_kind, _container), code(this)
  931. {
  932. }
  933. #ifdef _MSC_VER
  934. #pragma warning(pop)
  935. #endif
  936. void HqlCompoundStmt::mergeScopeWithContainer()
  937. {
  938. container->inheritDefinitions(code);
  939. }
  940. unsigned HqlCompoundStmt::numChildren() const
  941. {
  942. return code.ordinality();
  943. }
  944. IHqlStmt * HqlCompoundStmt::queryChild(unsigned index) const
  945. {
  946. if (code.isItem(index))
  947. return &code.item(index);
  948. return NULL;
  949. }
  950. //---------------------------------------------------------------------------
  951. StringBuffer & HqlQuoteStmt::getTextExtra(StringBuffer & out)
  952. {
  953. return out.append(text);
  954. }
  955. //---------------------------------------------------------------------------
  956. int queryMemsetChar(IHqlExpression * expr)
  957. {
  958. if (expr->getOperator() != no_constant)
  959. return -1;
  960. unsigned size = expr->queryType()->getSize();
  961. if (size == 0)
  962. return -1;
  963. const byte * data = (const byte *)expr->queryValue()->queryValue();
  964. byte match = data[0];
  965. while (--size)
  966. if (*++data != match)
  967. return -1;
  968. return match;
  969. }
  970. static IHqlExpression * extractNonConstant(IHqlExpression * expr, unsigned & delta)
  971. {
  972. switch (expr->getOperator())
  973. {
  974. case no_constant:
  975. delta += (unsigned)getIntValue(expr);
  976. return NULL;
  977. case no_add:
  978. {
  979. IHqlExpression * left = expr->queryChild(0);
  980. OwnedHqlExpr newLeft = extractNonConstant(left, delta);
  981. IHqlExpression * right = expr->queryChild(1);
  982. OwnedHqlExpr newRight = extractNonConstant(right, delta);
  983. if (!newLeft) return newRight.getClear();
  984. if (!newRight) return newLeft.getClear();
  985. if ((left == newLeft) && (right == newRight))
  986. return LINK(expr);
  987. return createValue(no_add, expr->getType(), newLeft.getClear(), newRight.getClear());
  988. }
  989. }
  990. return LINK(expr);
  991. }
  992. IHqlExpression * peepholeAddExpr(IHqlExpression * left, IHqlExpression * right)
  993. {
  994. unsigned delta = 0;
  995. IHqlExpression * simpleLeft = extractNonConstant(left, delta);
  996. IHqlExpression * simpleRight = extractNonConstant(right, delta);
  997. IHqlExpression * ret;
  998. if (simpleLeft)
  999. {
  1000. if (simpleRight)
  1001. ret = createValue(no_add, left->getType(), simpleLeft, simpleRight);
  1002. else
  1003. ret = simpleLeft;
  1004. }
  1005. else
  1006. ret = simpleRight;
  1007. if (!delta && ret)
  1008. return ret;
  1009. IHqlExpression * value = getSizetConstant(delta);
  1010. if (!ret)
  1011. return value;
  1012. return createValue(no_add, left->getType(), ret, value);
  1013. if ((left->getOperator() == no_constant) && (right->getOperator() == no_constant))
  1014. return getSizetConstant((size32_t)left->queryValue()->getIntValue() + (size32_t)right->queryValue()->getIntValue());
  1015. return createValue(no_add, left->getType(), LINK(left), LINK(right));
  1016. }
  1017. bool rightFollowsLeft(IHqlExpression * left, IHqlExpression * leftLen, IHqlExpression * right)
  1018. {
  1019. OwnedHqlExpr sum = peepholeAddExpr(left, leftLen);
  1020. if (sum == right)
  1021. return true;
  1022. if (left->getOperator() != right->getOperator())
  1023. {
  1024. if (right->getOperator() == no_add)
  1025. {
  1026. if ((left == right->queryChild(0)) && (leftLen == right->queryChild(1)))
  1027. return true;
  1028. if ((left == right->queryChild(1)) && (leftLen == right->queryChild(0)))
  1029. return true;
  1030. }
  1031. return false;
  1032. }
  1033. switch (left->getOperator())
  1034. {
  1035. case no_constant:
  1036. {
  1037. ITypeInfo * leftType = left->queryType();
  1038. ITypeInfo * rightType = right->queryType();
  1039. if (leftType->getTypeCode() != rightType->getTypeCode())
  1040. return false;
  1041. switch (leftType->getTypeCode())
  1042. {
  1043. case type_int:
  1044. if (leftLen->getOperator() != no_constant)
  1045. return false;
  1046. if (left->queryValue()->getIntValue() + leftLen->queryValue()->getIntValue() == right->queryValue()->getIntValue())
  1047. return true;
  1048. return false;
  1049. }
  1050. return false;
  1051. }
  1052. case no_add:
  1053. if ((left == right->queryChild(0)) && (leftLen == right->queryChild(1)))
  1054. return true;
  1055. if (left->queryChild(1) == right->queryChild(1))
  1056. {
  1057. if (rightFollowsLeft(left->queryChild(0), leftLen, right->queryChild(0)))
  1058. return true;
  1059. }
  1060. //fall through
  1061. case no_index:
  1062. if (left->queryChild(0) != right->queryChild(0))
  1063. return false;
  1064. return rightFollowsLeft(left->queryChild(1), leftLen, right->queryChild(1));
  1065. }
  1066. unsigned numLeft = left->numChildren();
  1067. if (numLeft == 0 || (numLeft != right->numChildren()))
  1068. return false;
  1069. ForEachChild(idx, left)
  1070. {
  1071. if (!rightFollowsLeft(left->queryChild(idx), leftLen, right->queryChild(idx)))
  1072. return false;
  1073. }
  1074. return true;
  1075. }
  1076. static IHqlExpression * createDataForMemset(unsigned size, byte value)
  1077. {
  1078. if (size < 100)
  1079. {
  1080. void * temp = alloca(size);
  1081. memset(temp, value, size);
  1082. return createConstant(createDataValue((char *)temp, size));
  1083. }
  1084. void * temp = malloc(size);
  1085. memset(temp, value, size);
  1086. IHqlExpression * ret = createConstant(createDataValue((char *)temp, size));
  1087. free(temp);
  1088. return ret;
  1089. }
  1090. static IHqlExpression * createDataForIntegerZero(unsigned size)
  1091. {
  1092. return createDataForMemset(size, 0);
  1093. }
  1094. class SpecialFunction
  1095. {
  1096. public:
  1097. SpecialFunction() { wasAssign = false; name = NULL; }
  1098. HqlStmt * createStmt(HqlStmts & curStmts, HqlCppTranslator & translator);
  1099. bool canOptimize() const;
  1100. void expandValue(void * target) const;
  1101. bool extractIsSpecial(IHqlStmt & stmt, bool memsetOnly, unsigned peepholeOptions);
  1102. bool isBigClear() const;
  1103. int queryClearValue() const;
  1104. bool queryCombine(const SpecialFunction & next, bool memsetOnly, size32_t combineStringLimit);
  1105. private:
  1106. _ATOM name;
  1107. HqlExprAttr src;
  1108. HqlExprAttr tgt;
  1109. HqlExprAttr srcLen;
  1110. HqlExprAttr tgtLen;
  1111. bool wasAssign;
  1112. };
  1113. //Always convert rtlWriteInt(rtlReadInt()) the inline memcpy is going to be much better.
  1114. //It should probably be converted earlier....
  1115. bool isAwkwardIntSize(IHqlExpression * size)
  1116. {
  1117. IValue * value = size->queryValue();
  1118. if (value)
  1119. {
  1120. switch (value->getIntValue())
  1121. {
  1122. case 3:
  1123. case 5:
  1124. case 6:
  1125. case 7:
  1126. return true;
  1127. }
  1128. }
  1129. return false;
  1130. }
  1131. bool SpecialFunction::canOptimize() const
  1132. {
  1133. if ((name == memcpyAtom) && (queryMemsetChar(src) >= 0))
  1134. {
  1135. if ((getIntValue(srcLen, 0) > 1) || !wasAssign)
  1136. return true;
  1137. }
  1138. if ((name == memcpyAtom) && isAwkwardIntSize(srcLen))
  1139. return true;
  1140. return false;
  1141. }
  1142. HqlStmt * SpecialFunction::createStmt(HqlStmts & curStmts, HqlCppTranslator & translator)
  1143. {
  1144. HqlExprArray args;
  1145. _ATOM func = name;
  1146. if (name == memsetAtom)
  1147. {
  1148. func = memsetAtom;
  1149. args.append(*LINK(tgt));
  1150. args.append(*LINK(src));
  1151. args.append(*LINK(srcLen));
  1152. }
  1153. else if (name == memcpyAtom)
  1154. {
  1155. int clearByte = queryMemsetChar(src);
  1156. size32_t size = (size32_t)getIntValue(srcLen, 0);
  1157. if (clearByte == 0)
  1158. {
  1159. //if length is 1,2,4 then use an assignment instead.
  1160. switch (size)
  1161. {
  1162. case 1:
  1163. case 2:
  1164. case 4:
  1165. case 8:
  1166. {
  1167. OwnedITypeInfo type = makeIntType(size, false);
  1168. OwnedHqlExpr castTgt = createValue(no_cast, makePointerType(LINK(type)), LINK(tgt));
  1169. OwnedHqlExpr deref = createValue(no_deref, makeReferenceModifier(LINK(type)), LINK(castTgt));
  1170. OwnedHqlExpr src = createConstant(type->castFrom(true, (__int64)0));
  1171. HqlStmt * next = new HqlStmt(assign_stmt, &curStmts);
  1172. next->addExpr(LINK(deref));
  1173. next->addExpr(LINK(src));
  1174. return next;
  1175. }
  1176. }
  1177. }
  1178. //MORE: assignment of 1,2,4 bytes possibly better as an assign?
  1179. if (clearByte >= 0)
  1180. {
  1181. func = memsetAtom;
  1182. args.append(*LINK(tgt));
  1183. args.append(*createConstant(createIntValue(clearByte, sizeof(int), true)));
  1184. args.append(*LINK(srcLen));
  1185. }
  1186. else
  1187. {
  1188. args.append(*LINK(tgt));
  1189. args.append(*LINK(src));
  1190. args.append(*LINK(srcLen));
  1191. }
  1192. }
  1193. else if (name == deserializerReadNAtom || name == serializerPutAtom)
  1194. {
  1195. args.append(*LINK(src));
  1196. args.append(*LINK(tgtLen));
  1197. args.append(*LINK(tgt));
  1198. }
  1199. else if ((name == ebcdic2asciiAtom) || (name == ascii2ebcdicAtom))
  1200. {
  1201. args.append(*LINK(tgtLen));
  1202. args.append(*LINK(tgt));
  1203. args.append(*LINK(srcLen));
  1204. args.append(*LINK(src));
  1205. }
  1206. else if (name == deserializerSkipNAtom)
  1207. {
  1208. args.append(*LINK(src));
  1209. args.append(*LINK(srcLen));
  1210. }
  1211. else
  1212. UNIMPLEMENTED;
  1213. HqlStmt * next = new HqlStmt(expr_stmt, &curStmts);
  1214. next->addExpr(translator.bindTranslatedFunctionCall(func, args));
  1215. return next;
  1216. }
  1217. IHqlExpression * stripTranslatedCasts(IHqlExpression * e)
  1218. {
  1219. loop
  1220. {
  1221. switch (e->getOperator())
  1222. {
  1223. case no_cast:
  1224. case no_implicitcast:
  1225. case no_typetransfer:
  1226. {
  1227. IHqlExpression * child = e->queryChild(0);
  1228. if (hasWrapperModifier(child->queryType()))
  1229. return e;
  1230. e = child;
  1231. break;
  1232. }
  1233. default:
  1234. return e;
  1235. }
  1236. }
  1237. }
  1238. void SpecialFunction::expandValue(void * target) const
  1239. {
  1240. size32_t size = (size32_t)getIntValue(srcLen);
  1241. if (name == memsetAtom)
  1242. memset(target, (int)getIntValue(src), size);
  1243. else
  1244. memcpy(target, src->queryValue()->queryValue(), size);
  1245. }
  1246. bool SpecialFunction::extractIsSpecial(IHqlStmt & stmt, bool memsetOnly, unsigned peepholeOptions)
  1247. {
  1248. if (stmt.getStmt() == expr_stmt)
  1249. {
  1250. IHqlExpression * expr = stmt.queryExpr(0);
  1251. if (expr->getOperator() != no_externalcall)
  1252. return false;
  1253. name = expr->queryName();
  1254. if (name == memcpyAtom)
  1255. {
  1256. src.set(stripTranslatedCasts(expr->queryChild(1)));
  1257. if (memsetOnly && (queryMemsetChar(src) == -1))
  1258. return false;
  1259. tgt.set(stripTranslatedCasts(expr->queryChild(0)));
  1260. srcLen.set(expr->queryChild(2));
  1261. tgtLen.set(srcLen);
  1262. return true;
  1263. }
  1264. if (name == deserializerReadNAtom || name == serializerPutAtom)
  1265. {
  1266. if (memsetOnly)
  1267. return false;
  1268. src.set(expr->queryChild(0));
  1269. tgt.set(stripTranslatedCasts(expr->queryChild(2)));
  1270. tgtLen.set(expr->queryChild(1));
  1271. return true;
  1272. }
  1273. if ((name == ebcdic2asciiAtom) || (name == ascii2ebcdicAtom))
  1274. {
  1275. if (memsetOnly)
  1276. return false;
  1277. src.set(expr->queryChild(3));
  1278. tgt.set(expr->queryChild(1));
  1279. srcLen.set(expr->queryChild(2));
  1280. tgtLen.set(expr->queryChild(0));
  1281. return srcLen == tgtLen;
  1282. }
  1283. if (name == memsetAtom)
  1284. {
  1285. IHqlExpression * value = expr->queryChild(1);
  1286. IHqlExpression * len = expr->queryChild(2);
  1287. if (len->queryValue() && value->queryValue())
  1288. {
  1289. tgt.set(stripTranslatedCasts(expr->queryChild(0)));
  1290. src.set(value);
  1291. srcLen.set(len);
  1292. tgtLen.set(srcLen);
  1293. }
  1294. return true;
  1295. }
  1296. if (name == deserializerSkipNAtom)
  1297. {
  1298. src.set(expr->queryChild(0));
  1299. srcLen.set(expr->queryChild(1));
  1300. return true;
  1301. }
  1302. unsigned size = 0;
  1303. if (name == writeIntAtom[3])
  1304. size = 3;
  1305. else if (name == writeIntAtom[5])
  1306. size = 5;
  1307. else if (name == writeIntAtom[6])
  1308. size = 6;
  1309. else if (name == writeIntAtom[7])
  1310. size = 7;
  1311. if (size)
  1312. {
  1313. IHqlExpression * value = expr->queryChild(1);
  1314. if (isZero(value))
  1315. {
  1316. name = memcpyAtom;
  1317. src.setown(createDataForIntegerZero(size));
  1318. tgt.set(stripTranslatedCasts(expr->queryChild(0)));
  1319. srcLen.setown(getSizetConstant(size));
  1320. tgtLen.set(srcLen);
  1321. return true;
  1322. }
  1323. if (memsetOnly)
  1324. return false;
  1325. while (value->getOperator() == no_typetransfer)
  1326. value = value->queryChild(0);
  1327. if (value->getOperator() == no_externalcall)
  1328. {
  1329. if ((value->queryName() == readIntAtom[size][true]) ||
  1330. (value->queryName() == readIntAtom[size][false]))
  1331. {
  1332. name = memcpyAtom;
  1333. src.set(stripTranslatedCasts(value->queryChild(0)));
  1334. tgt.set(stripTranslatedCasts(expr->queryChild(0)));
  1335. srcLen.setown(getSizetConstant(size));
  1336. tgtLen.set(srcLen);
  1337. return true;
  1338. }
  1339. }
  1340. }
  1341. return false;
  1342. }
  1343. else if (stmt.getStmt() == assign_stmt)
  1344. {
  1345. wasAssign = true;
  1346. tgt.set(stmt.queryExpr(0));
  1347. src.set(stmt.queryExpr(1));
  1348. ITypeInfo * tgtType = tgt->queryType();
  1349. ITypeInfo * srcType = src->queryType();
  1350. if (!isSameBasicType(srcType, tgtType))
  1351. {
  1352. if (!isSameFullyUnqualifiedType(srcType, tgtType))
  1353. return false;
  1354. }
  1355. while (tgt->getOperator() == no_typetransfer)
  1356. tgt.set(tgt->queryChild(0));
  1357. if (tgt->getOperator() != no_deref)
  1358. return false;
  1359. while (src->getOperator() == no_typetransfer)
  1360. src.set(src->queryChild(0));
  1361. size32_t targetSize = tgtType->getSize();
  1362. if (src->getOperator() != no_deref)
  1363. {
  1364. type_t tc = tgtType->getTypeCode();
  1365. OwnedHqlExpr newSrcExpr;
  1366. switch (tc)
  1367. {
  1368. case type_pointer:
  1369. case type_table:
  1370. //case type_row:
  1371. if (src->getOperator() == no_nullptr)
  1372. {
  1373. void * ptr = NULL;
  1374. targetSize = sizeof(void *);
  1375. newSrcExpr.setown(createConstant(createDataValue((const char *)&ptr, targetSize)));
  1376. }
  1377. break;
  1378. }
  1379. if (!memsetOnly)
  1380. {
  1381. switch (tc)
  1382. {
  1383. case type_int:
  1384. case type_swapint:
  1385. case type_boolean:
  1386. if (src->getOperator() == no_constant)
  1387. {
  1388. OwnedHqlExpr cast = ensureExprType(src, tgtType);
  1389. IValue * castValue = cast->queryValue();
  1390. if (castValue)
  1391. {
  1392. void * temp = alloca(targetSize);
  1393. castValue->toMem(temp);
  1394. newSrcExpr.setown(createConstant(createDataValue((const char *)temp, targetSize)));
  1395. }
  1396. }
  1397. break;
  1398. case type_real:
  1399. if ((peepholeOptions & PHOconvertReal) && (src->getOperator() == no_constant))
  1400. {
  1401. OwnedHqlExpr cast = ensureExprType(src, tgtType);
  1402. IValue * castValue = cast->queryValue();
  1403. if (castValue)
  1404. {
  1405. void * temp = alloca(targetSize);
  1406. castValue->toMem(temp);
  1407. newSrcExpr.setown(createConstant(createDataValue((const char *)temp, targetSize)));
  1408. }
  1409. }
  1410. break;
  1411. }
  1412. }
  1413. if (!newSrcExpr && isZero(src))
  1414. newSrcExpr.setown(createDataForIntegerZero(targetSize));
  1415. if (!newSrcExpr)
  1416. return false;
  1417. src.set(newSrcExpr);
  1418. }
  1419. else
  1420. {
  1421. if (memsetOnly)
  1422. return false;
  1423. src.set(src->queryChild(0));
  1424. }
  1425. srcLen.setown(getSizetConstant(targetSize));
  1426. tgtLen.set(srcLen);
  1427. tgt.set(stripTranslatedCasts(tgt->queryChild(0)));
  1428. src.set(stripTranslatedCasts(src));
  1429. name = memcpyAtom;
  1430. return true;
  1431. }
  1432. return false;
  1433. }
  1434. bool SpecialFunction::isBigClear() const
  1435. {
  1436. if ((name == memsetAtom) || (name == memcpyAtom))
  1437. return getIntValue(srcLen, 0) > CLEAR_COPY_THRESHOLD;
  1438. return false;
  1439. }
  1440. int SpecialFunction::queryClearValue() const
  1441. {
  1442. if (name == memcpyAtom)
  1443. return queryMemsetChar(src);
  1444. if (name == memsetAtom)
  1445. return (int)getIntValue(src, -1);
  1446. return -1;
  1447. }
  1448. bool SpecialFunction::queryCombine(const SpecialFunction & next, bool memsetOnly, size32_t combineStringLimit)
  1449. {
  1450. if (name != next.name)
  1451. {
  1452. if (!((name == memsetAtom) && (next.name == memcpyAtom)) &&
  1453. !((name == memcpyAtom) && (next.name == memsetAtom)))
  1454. return false;
  1455. }
  1456. if (name == deserializerSkipNAtom)
  1457. {
  1458. if (src != next.src)
  1459. return false;
  1460. srcLen.setown(peepholeAddExpr(srcLen, next.srcLen));
  1461. return true;
  1462. }
  1463. if (rightFollowsLeft(tgt, tgtLen, next.tgt))
  1464. {
  1465. if ((name != memsetAtom) && (next.name != memsetAtom))
  1466. {
  1467. if (name == deserializerReadNAtom || name == serializerPutAtom)
  1468. {
  1469. tgtLen.setown(peepholeAddExpr(tgtLen, next.tgtLen));
  1470. return true;
  1471. }
  1472. if (rightFollowsLeft(src, srcLen, next.src))
  1473. {
  1474. srcLen.setown(peepholeAddExpr(srcLen, next.srcLen));
  1475. tgtLen.setown(peepholeAddExpr(tgtLen, next.tgtLen));
  1476. return true;
  1477. }
  1478. }
  1479. IValue * srcValue = src->queryValue();
  1480. IValue * nextValue = next.src->queryValue();
  1481. if (srcValue && nextValue)
  1482. {
  1483. //Don't combine things that can be converted to different memsets.
  1484. //This would work better if we first combined items that could be done as memsets and then combined strings
  1485. //processing in order we hit them doesn't work as well.
  1486. int clearValue = queryClearValue();
  1487. int nextClearValue = next.queryClearValue();
  1488. if (memsetOnly)
  1489. {
  1490. assertex((clearValue != -1) && (nextClearValue != -1));
  1491. if (clearValue != nextClearValue)
  1492. return false;
  1493. }
  1494. if ((isBigClear() && (clearValue != -1)) || (next.isBigClear() && (nextClearValue != -1)))
  1495. {
  1496. if (clearValue != nextClearValue)
  1497. return false;
  1498. }
  1499. size32_t curSize = (size32_t)getIntValue(srcLen);
  1500. size32_t nextSize = (size32_t)getIntValue(next.srcLen);
  1501. if (curSize + nextSize > combineStringLimit)
  1502. return false;
  1503. byte * temp = (byte *)malloc(curSize + nextSize);
  1504. expandValue(temp);
  1505. next.expandValue(temp+curSize);
  1506. src.setown(createConstant(createDataValue((const char *)temp, curSize + nextSize)));
  1507. free(temp);
  1508. srcLen.setown(getSizetConstant(curSize + nextSize));
  1509. tgtLen.set(srcLen);
  1510. if (name == memsetAtom)
  1511. name = memcpyAtom;
  1512. return true;
  1513. }
  1514. }
  1515. return false;
  1516. }
  1517. PeepHoleOptimizer::PeepHoleOptimizer(HqlCppTranslator & _translator) : translator(_translator)
  1518. {
  1519. combineStringLimit = -1;
  1520. peepholeOptions = 0;
  1521. if (translator.queryOptions().convertRealAssignToMemcpy)
  1522. peepholeOptions |= PHOconvertReal;
  1523. switch (translator.queryOptions().targetCompiler)
  1524. {
  1525. case Vs6CppCompiler:
  1526. combineStringLimit = 32000;
  1527. break;
  1528. }
  1529. }
  1530. void PeepHoleOptimizer::optimize(HqlStmts & stmts)
  1531. {
  1532. unsigned max = stmts.ordinality(); // can change as processing proceeds.
  1533. SpecialFunction prevMatch;
  1534. for (unsigned pass=0; pass < 2; pass++)
  1535. {
  1536. bool memsetOnly = (pass == 0);
  1537. for (unsigned i =0; i < max; i++)
  1538. {
  1539. IHqlStmt & cur = stmts.item(i);
  1540. if (prevMatch.extractIsSpecial(cur, memsetOnly, peepholeOptions))
  1541. {
  1542. unsigned j = i+1;
  1543. unsigned prevMax = max;
  1544. SpecialFunction nextMatch;
  1545. while (j < max)
  1546. {
  1547. IHqlStmt & next = stmts.item(j);
  1548. if (!nextMatch.extractIsSpecial(next, memsetOnly, peepholeOptions))
  1549. break;
  1550. if (!prevMatch.queryCombine(nextMatch, memsetOnly, combineStringLimit))
  1551. break;
  1552. stmts.remove(i);
  1553. max--;
  1554. }
  1555. if (max != prevMax || prevMatch.canOptimize())
  1556. {
  1557. stmts.remove(i);
  1558. stmts.add(*prevMatch.createStmt(stmts, translator), i);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. for (unsigned i2=0; i2 < max; i2++)
  1564. {
  1565. IHqlStmt & cur = stmts.item(i2);
  1566. if (cur.numChildren() != 0)
  1567. optimize(((HqlCompoundStmt&)cur).code);
  1568. }
  1569. }
  1570. void peepholeOptimize(HqlCppInstance & instance, HqlCppTranslator & translator)
  1571. {
  1572. PeepHoleOptimizer optimizer(translator);
  1573. ForEachItemIn(idx, instance.sections)
  1574. optimizer.optimize(((HqlCppSection&)instance.sections.item(idx)).stmts);
  1575. }
  1576. //---------------------------------------------------------------------------
  1577. AssociationIterator::AssociationIterator(BuildCtx & ctx)
  1578. {
  1579. rootStmts = ctx.curStmts;
  1580. curStmts = NULL;
  1581. curIdx = 0;
  1582. }
  1583. bool AssociationIterator::first()
  1584. {
  1585. curStmts = rootStmts;
  1586. curIdx = curStmts->defs.ordinality();
  1587. return doNext();
  1588. }
  1589. bool AssociationIterator::doNext()
  1590. {
  1591. loop
  1592. {
  1593. if (curIdx-- != 0)
  1594. return true;
  1595. HqlStmt * limitStmt = curStmts->queryStmt();
  1596. if (!limitStmt)
  1597. {
  1598. curStmts = NULL;
  1599. return false;
  1600. }
  1601. curStmts = limitStmt->queryContainer();
  1602. curIdx = curStmts->defs.ordinality();
  1603. }
  1604. }
  1605. HqlExprAssociation & AssociationIterator::get()
  1606. {
  1607. CIArray & defs = curStmts->defs;
  1608. return (HqlExprAssociation &)defs.item(curIdx);
  1609. }
  1610. //---------------------------------------------------------------------------
  1611. bool FilteredAssociationIterator::doNext()
  1612. {
  1613. while (AssociationIterator::doNext())
  1614. {
  1615. HqlExprAssociation & cur = AssociationIterator::get();
  1616. if (cur.getKind() == searchKind)
  1617. return true;
  1618. }
  1619. return false;
  1620. }
  1621. bool RowAssociationIterator::doNext()
  1622. {
  1623. while (AssociationIterator::doNext())
  1624. {
  1625. HqlExprAssociation & cur = AssociationIterator::get();
  1626. if (cur.isRowAssociation())
  1627. return true;
  1628. }
  1629. return false;
  1630. };
  1631. unsigned calcTotalChildren(IHqlStmt * stmt)
  1632. {
  1633. if (!stmt->isIncluded())
  1634. return 0;
  1635. unsigned num = stmt->numChildren();
  1636. unsigned total = 1;
  1637. switch (stmt->getStmt())
  1638. {
  1639. case alias_stmt:
  1640. case group_stmt:
  1641. case pass_stmt:
  1642. case indirect_stmt:
  1643. total = 0;
  1644. break;
  1645. }
  1646. for (unsigned i=0; i < num; i++)
  1647. total += calcTotalChildren(stmt->queryChild(i));
  1648. return total;
  1649. }