hqlresource.cpp 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878
  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 "hqlexpr.hpp"
  17. #include "hqlattr.hpp"
  18. #include "hqlmeta.hpp"
  19. #include "hqlutil.hpp"
  20. #include "hqlcpputil.hpp"
  21. #include "hqlthql.hpp"
  22. #include "hqlcatom.hpp"
  23. #include "hqlfold.hpp"
  24. #include "hqlcerrors.hpp"
  25. #include "hqltrans.ipp"
  26. #include "hqlpmap.hpp"
  27. #include "hqltcppc.ipp"
  28. #include "hqlttcpp.ipp"
  29. #include "hqlresource.ipp"
  30. #include "../../thorlcr/thorutil/thbufdef.hpp"
  31. #define MINIMAL_CHANGES
  32. #define MAX_INLINE_COMMON_COUNT 5
  33. //#define TRACE_RESOURCING
  34. //#define VERIFY_RESOURCING
  35. //#define SPOT_UNCONDITIONAL_CONDITIONS
  36. #define DEFAULT_LARGEMEM_BUFFER_SIZE (0x58000000) // ~ 1.4GB
  37. #define DEFAULT_MAX_SOCKETS 2000 // configurable by setting max_sockets in .ini
  38. #define DEFAULT_TOTAL_MEMORY ((1024*1024*1800)-DEFAULT_LARGEMEM_BUFFER_SIZE)
  39. #define FIXED_CLUSTER_SIZE 400
  40. #define MEM_Const_Minimal (1*1024*1024)
  41. #define DEFAULT_MAX_ACTIVITIES 100
  42. //=== The following provides information about how each kind of activity is resourced ====
  43. static void setHashResources(IHqlExpression * expr, CResources & resources, const CResourceOptions & options)
  44. {
  45. if (options.useMpForDistribute)
  46. {
  47. unsigned memneeded = MEM_Const_Minimal+resources.clusterSize*4*DISTRIBUTE_SINGLE_BUFFER_SIZE+DISTRIBUTE_PULL_BUFFER_SIZE;
  48. resources.set(RESslavememory, memneeded).set(REShashdist, 1);
  49. }
  50. else
  51. {
  52. resources.set(RESslavememory, MEM_Const_Minimal+DISTRIBUTE_PULL_BUFFER_SIZE).set(REShashdist, 1);
  53. resources.setManyToManySockets(2);
  54. }
  55. }
  56. //MORE: Use a single function to map an hqlexpression to an activity kind.
  57. void getResources(IHqlExpression * expr, CResources & resources, const CResourceOptions & options)
  58. {
  59. //MORE: What effect should a child query have? Definitely the following, but what about other resourcing?
  60. if (options.isChildQuery || queryHint(expr, lightweightAtom))
  61. {
  62. resources.setLightweight();
  63. return;
  64. }
  65. bool isLocal = isLocalActivity(expr);
  66. bool isGrouped = isGroupedActivity(expr);
  67. switch (expr->getOperator())
  68. {
  69. case no_join:
  70. case no_selfjoin:
  71. case no_denormalize:
  72. case no_denormalizegroup:
  73. if (isKeyedJoin(expr) || expr->hasProperty(_lightweight_Atom))
  74. resources.setLightweight();
  75. else if (expr->hasProperty(lookupAtom))
  76. {
  77. if (expr->hasProperty(fewAtom))
  78. {
  79. resources.setLightweight().set(RESslavememory, MEM_Const_Minimal+LOOKUPJOINL_SMART_BUFFER_SIZE);
  80. resources.setManyToMasterSockets(1);
  81. }
  82. else
  83. {
  84. resources.setHeavyweight().set(RESslavememory, MEM_Const_Minimal+LOOKUPJOINL_SMART_BUFFER_SIZE);
  85. resources.setManyToMasterSockets(1);
  86. }
  87. }
  88. else if (expr->hasProperty(hashAtom))
  89. {
  90. resources.setHeavyweight();
  91. setHashResources(expr, resources, options);
  92. }
  93. else
  94. {
  95. resources.setHeavyweight().set(RESslavememory, MEM_Const_Minimal+SORT_BUFFER_TOTAL+JOINR_SMART_BUFFER_SIZE);
  96. if (!isLocal)
  97. {
  98. #ifndef SORT_USING_MP
  99. resources.setManyToManySockets(2);
  100. #endif
  101. }
  102. }
  103. break;
  104. case no_dedup:
  105. if (isGrouped || (!expr->hasProperty(allAtom) && !expr->hasProperty(hashAtom)))
  106. {
  107. resources.setLightweight();
  108. if (!isGrouped && !isLocal)
  109. {
  110. resources.set(RESslavememory, MEM_Const_Minimal+DEDUP_SMART_BUFFER_SIZE);
  111. resources.setManyToMasterSockets(1);
  112. }
  113. }
  114. else if (isLocal)
  115. {
  116. resources.setHeavyweight().set(RESslavememory, MEM_Const_Minimal+DEDUP_SMART_BUFFER_SIZE);
  117. //This can't be right....
  118. //resources.setManyToMasterSockets(1);
  119. }
  120. else
  121. {
  122. //hash dedup.
  123. resources.setHeavyweight();
  124. setHashResources(expr, resources, options);
  125. }
  126. break;
  127. case no_rollup:
  128. resources.setLightweight();
  129. if (!isGrouped && !isLocal)
  130. {
  131. resources.set(RESslavememory, MEM_Const_Minimal+DEDUP_SMART_BUFFER_SIZE);
  132. resources.setManyToMasterSockets(1);
  133. }
  134. break;
  135. case no_distribute:
  136. case no_keyeddistribute:
  137. resources.setLightweight();
  138. setHashResources(expr, resources, options);
  139. break;
  140. case no_sort:
  141. if (isGrouped)
  142. {
  143. if (expr->hasProperty(manyAtom))
  144. resources.setHeavyweight();
  145. else
  146. resources.setLightweight();
  147. }
  148. else if (expr->hasProperty(fewAtom) && isLocal)
  149. resources.setLightweight();
  150. else if (isLocal)
  151. resources.setHeavyweight();
  152. else
  153. {
  154. resources.setHeavyweight();
  155. #ifndef SORT_USING_MP
  156. resources.setManyToManySockets(2);
  157. #endif
  158. }
  159. break;
  160. case no_topn:
  161. resources.setLightweight();
  162. break;
  163. case no_pipe:
  164. //surely it should be something like this.
  165. resources.setLightweight().set(RESslavesocket, 1);
  166. break;
  167. case no_table:
  168. {
  169. IHqlExpression * mode = expr->queryChild(2);
  170. if (mode && mode->getOperator() == no_pipe)
  171. {
  172. resources.setLightweight().set(RESslavesocket, 1);
  173. }
  174. else
  175. {
  176. resources.setLightweight();
  177. if (expr->hasProperty(_workflowPersist_Atom) && expr->hasProperty(distributedAtom))
  178. setHashResources(expr, resources, options); // may require a hash distribute
  179. }
  180. break;
  181. }
  182. case no_output:
  183. {
  184. IHqlExpression * filename = expr->queryChild(1);
  185. if (expr->hasProperty(_spill_Atom))
  186. {
  187. //resources.setLightweight(); // assume no resources(!)
  188. }
  189. else if (filename && filename->getOperator() == no_pipe)
  190. {
  191. resources.setLightweight().set(RESslavesocket, 1);
  192. }
  193. else if (filename && !filename->isAttribute())
  194. {
  195. resources.setLightweight();
  196. }
  197. else
  198. {
  199. resources.setLightweight().set(RESslavememory, WORKUNITWRITE_SMART_BUFFER_SIZE);
  200. }
  201. break;
  202. }
  203. case no_distribution:
  204. resources.setLightweight().set(RESmastersocket, 16).set(RESslavesocket, 1);
  205. break;
  206. case no_aggregate:
  207. case no_newaggregate:
  208. {
  209. IHqlExpression * grouping = queryRealChild(expr, 3);
  210. if (grouping)
  211. {
  212. //Is this really correct???
  213. resources.setLightweight();
  214. setHashResources(expr, resources, options);
  215. }
  216. else
  217. {
  218. resources.setLightweight();
  219. //if (!isGrouped)
  220. // resources.set(RESmastersocket, 16).set(RESslavesocket, 1);
  221. }
  222. }
  223. break;
  224. case no_hqlproject:
  225. resources.setLightweight();
  226. //Add a flag onto count project to indicate it is a different variety.
  227. if (expr->hasProperty(_countProject_Atom) && !isLocal)
  228. resources.set(RESslavememory, COUNTPROJECT_SMART_BUFFER_SIZE);
  229. break;
  230. case no_enth:
  231. resources.setLightweight();
  232. if (!isLocal)
  233. resources.set(RESslavememory, CHOOSESETS_SMART_BUFFER_SIZE);
  234. break;
  235. case no_metaactivity:
  236. if (expr->hasProperty(pullAtom))
  237. resources.setLightweight().set(RESslavememory, PULL_SMART_BUFFER_SIZE);
  238. break;
  239. case no_setresult:
  240. case no_extractresult:
  241. case no_outputscalar:
  242. resources.setLightweight();//.set(RESmastersocket, 1).set(RESslavesocket, 1);
  243. break;
  244. case no_choosesets:
  245. resources.setLightweight();
  246. if (!isLocal || expr->hasProperty(enthAtom) || expr->hasProperty(lastAtom))
  247. resources.set(RESslavememory, CHOOSESETS_SMART_BUFFER_SIZE);
  248. break;
  249. case no_iterate:
  250. resources.setLightweight();
  251. if (!isGrouped && !isLocal)
  252. resources.setManyToMasterSockets(1).set(RESslavememory, ITERATE_SMART_BUFFER_SIZE);
  253. break;
  254. case no_choosen:
  255. resources.setLightweight().set(RESslavememory, FIRSTN_SMART_BUFFER_SIZE);
  256. break;
  257. case no_spill:
  258. case no_spillgraphresult:
  259. //assumed to take no resources;
  260. break;
  261. case no_addfiles:
  262. case no_merge:
  263. {
  264. resources.setLightweight();
  265. unsigned bufSize = FUNNEL_PERINPUT_BUFF_SIZE*expr->numChildren();
  266. if (bufSize < FUNNEL_MIN_BUFF_SIZE) bufSize = FUNNEL_MIN_BUFF_SIZE;
  267. resources.set(RESslavememory, MEM_Const_Minimal+bufSize);
  268. break;
  269. }
  270. case no_compound:
  271. //MORE: Should really be the total resources for the lhs... Really needs more thought.
  272. break;
  273. case no_libraryselect:
  274. //Do not allocate any resources for this, we don't want it to cause a spill under any circumstances
  275. break;
  276. case no_split:
  277. //Should really be included in the cost....
  278. default:
  279. resources.setLightweight();
  280. break;
  281. }
  282. }
  283. CResources & CResources::setLightweight()
  284. {
  285. return set(RESslavememory, 0x10000).set(RESactivities, 1);
  286. }
  287. CResources & CResources::setHeavyweight()
  288. {
  289. return set(RESslavememory, 0x100000).set(RESheavy, 1).set(RESactivities, 1);
  290. }
  291. //-------------------------------------------------------------------------------------------
  292. const char * queryResourceName(ResourceType kind)
  293. {
  294. switch (kind)
  295. {
  296. case RESslavememory: return "Slave Memory";
  297. case RESslavesocket: return "Slave Sockets";
  298. case RESmastermemory: return "Master Memory";
  299. case RESmastersocket: return "Master Sockets";
  300. case REShashdist: return "Hash Distributes";
  301. case RESheavy: return "Heavyweight";
  302. case RESactivities: return "Activities";
  303. }
  304. return "Unknown";
  305. }
  306. inline ResourcerInfo * queryResourceInfo(IHqlExpression * expr) { return (ResourcerInfo *)expr->queryBody()->queryTransformExtra(); }
  307. inline bool isResourcedActivity(IHqlExpression * expr)
  308. {
  309. ResourcerInfo * extra = queryResourceInfo(expr);
  310. return (extra && (extra->isActivity || extra->containsActivity));
  311. }
  312. bool isWorthForcingHoist(IHqlExpression * expr)
  313. {
  314. loop
  315. {
  316. switch (expr->getOperator())
  317. {
  318. case no_selectnth:
  319. case no_filter:
  320. case no_newaggregate:
  321. if (isResourcedActivity(expr->queryChild(0)))
  322. return true;
  323. break;
  324. default:
  325. return false;
  326. }
  327. expr = expr->queryChild(0);
  328. }
  329. }
  330. void CResources::add(const CResources & other)
  331. {
  332. for (unsigned i = 0; i < RESmax; i++)
  333. resource[i] += other.resource[i];
  334. }
  335. bool CResources::addExceeds(const CResources & other, const CResources & limit) const
  336. {
  337. for (unsigned i = 0; i < RESmax; i++)
  338. {
  339. if (resource[i] + other.resource[i] > limit.resource[i])
  340. {
  341. //DBGLOG("Cannot merge because limit for %s exceeded (%d cf %d)", queryResourceName((ResourceType)i), resource[i] + other.resource[i], limit.resource[i]);
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. StringBuffer & CResources::getExceedsReason(StringBuffer & reasonText, const CResources & other, const CResources & limit) const
  348. {
  349. bool first = true;
  350. for (unsigned i = 0; i < RESmax; i++)
  351. {
  352. if (resource[i] + other.resource[i] > limit.resource[i])
  353. {
  354. if (!first) reasonText.append(", ");
  355. first = false;
  356. reasonText.appendf("%s (%d>%d)", queryResourceName((ResourceType)i), resource[i] + other.resource[i], limit.resource[i]);
  357. }
  358. }
  359. return reasonText;
  360. }
  361. bool CResources::exceeds(const CResources & limit) const
  362. {
  363. for (unsigned i = 0; i < RESmax; i++)
  364. {
  365. if (resource[i] > limit.resource[i])
  366. return true;
  367. }
  368. return false;
  369. }
  370. void CResources::maximize(const CResources & other)
  371. {
  372. for (unsigned i = 0; i < RESmax; i++)
  373. {
  374. if (resource[i] < other.resource[i])
  375. resource[i] = other.resource[i];
  376. }
  377. }
  378. CResources & CResources::setManyToMasterSockets(unsigned numSockets)
  379. {
  380. set(RESslavesocket, numSockets);
  381. set(RESmastersocket, numSockets * clusterSize);
  382. return *this;
  383. }
  384. CResources & CResources::setManyToManySockets(unsigned numSockets)
  385. {
  386. return set(RESslavesocket, numSockets * clusterSize);
  387. }
  388. void CResources::sub(const CResources & other)
  389. {
  390. for (unsigned i = 0; i < RESmax; i++)
  391. resource[i] -= other.resource[i];
  392. }
  393. //===========================================================================
  394. inline bool isAffectedByResourcing(IHqlExpression * expr)
  395. {
  396. switch (expr->getOperator())
  397. {
  398. case no_record:
  399. case no_constant:
  400. case no_attr:
  401. return false;
  402. }
  403. return true;
  404. }
  405. bool isSimpleAggregateResult(IHqlExpression * expr)
  406. {
  407. //MORE: no_extractresult is really what is meant
  408. if (expr->getOperator() != no_extractresult)
  409. return false;
  410. IHqlExpression * value = expr->queryChild(0);
  411. if (value->getOperator() != no_datasetfromrow)
  412. return false;
  413. //MORE: This currently doesn't hoist selects from nested records, but not sure there is a syntax to do that either.
  414. IHqlExpression * ds = value->queryChild(0);
  415. if (!isSelectFirstRow(ds))
  416. return false;
  417. ds = ds->queryChild(0);
  418. if (ds->getOperator() != no_newaggregate)
  419. return false;
  420. return true;
  421. }
  422. bool lightweightAndReducesDatasetSize(IHqlExpression * expr)
  423. {
  424. switch (expr->getOperator())
  425. {
  426. case no_hqlproject:
  427. case no_newusertable:
  428. return reducesRowSize(expr);
  429. case no_dedup:
  430. if (isGroupedActivity(expr) || (!expr->hasProperty(allAtom) && !expr->hasProperty(hashAtom)))
  431. return true;
  432. break;
  433. case no_aggregate:
  434. case no_newaggregate:
  435. {
  436. IHqlExpression * grouping = queryRealChild(expr, 3);
  437. if (grouping)
  438. return false;
  439. return true;
  440. }
  441. case no_rollupgroup:
  442. case no_rollup:
  443. case no_choosen:
  444. case no_choosesets:
  445. case no_enth:
  446. case no_sample:
  447. case no_filter:
  448. case no_limit:
  449. case no_filtergroup:
  450. return true;
  451. case no_group:
  452. //removing grouping will reduce size of the spill file.
  453. if (expr->queryType()->queryGroupInfo() == NULL)
  454. return true;
  455. break;
  456. }
  457. return false;
  458. }
  459. bool heavyweightAndReducesSizeOrSkew(IHqlExpression * expr)
  460. {
  461. switch (expr->getOperator())
  462. {
  463. case no_aggregate:
  464. case no_newaggregate:
  465. {
  466. //more; hash aggregate?
  467. break;
  468. }
  469. case no_distribute:
  470. return true;
  471. }
  472. return false;
  473. }
  474. //---------------------------------------------------------------------------
  475. IHqlExpression * CResourceOptions::createSpillName(bool isGraphResult)
  476. {
  477. if (isGraphResult)
  478. return getSizetConstant(nextResult++);
  479. StringBuffer s;
  480. s.append("~spill::");
  481. getUniqueId(s);
  482. if (!mangleSpillNameWithWuid)
  483. return createConstant(s.str());
  484. s.append("_");
  485. if (filenameMangler)
  486. {
  487. s.append(filenameMangler);
  488. return createConstant(s.str());
  489. }
  490. ITypeInfo * type = makeStringType(UNKNOWN_LENGTH, NULL, NULL);
  491. return createValue(no_concat, type, createConstant(s.str()), createValue(no_wuid, LINK(type)));
  492. }
  493. //---------------------------------------------------------------------------
  494. static bool isIndex(IHqlExpression * expr)
  495. {
  496. switch (expr->getOperator())
  497. {
  498. case no_keyindex:
  499. case no_newkeyindex:
  500. return true;
  501. }
  502. return false;
  503. }
  504. IHqlExpression * appendUniqueAttr(IHqlExpression * expr)
  505. {
  506. return replaceOwnedProperty(expr, createUniqueId());
  507. }
  508. bool queryAddUniqueToActivity(IHqlExpression * expr)
  509. {
  510. if (!isSourceActivity(expr))
  511. return false;
  512. switch (expr->getOperator())
  513. {
  514. case no_workunit_dataset:
  515. case no_getgraphresult:
  516. case no_getgraphloopresult:
  517. case no_xmlproject:
  518. case no_datasetfromrow:
  519. case no_rows:
  520. case no_allnodes:
  521. case no_thisnode:
  522. case no_select: // it can get lost, and that then causes inconsistent trees.
  523. return false;
  524. }
  525. return true;
  526. }
  527. //---------------------------------------------------------------------------
  528. ResourceGraphLink::ResourceGraphLink(ResourceGraphInfo * _sourceGraph, IHqlExpression * _sourceNode, ResourceGraphInfo * _sinkGraph, IHqlExpression * _sinkNode, LinkKind _linkKind)
  529. {
  530. assertex(_sourceGraph);
  531. sourceGraph.set(_sourceGraph);
  532. sourceNode.set(_sourceNode);
  533. sinkGraph.set(_sinkGraph);
  534. sinkNode.set(_sinkNode);
  535. assertex(!sinkGraph || sinkNode);
  536. linkKind = _linkKind;
  537. trace("create");
  538. }
  539. ResourceGraphLink::~ResourceGraphLink()
  540. {
  541. trace("delete");
  542. }
  543. void ResourceGraphLink::changeSourceGraph(ResourceGraphInfo * newGraph)
  544. {
  545. sourceGraph->sinks.zap(*this);
  546. sourceGraph.set(newGraph);
  547. newGraph->sinks.append(*this);
  548. trace("change source");
  549. }
  550. void ResourceGraphLink::changeSinkGraph(ResourceGraphInfo * newGraph)
  551. {
  552. sinkGraph->sources.zap(*this);
  553. sinkGraph.set(newGraph);
  554. newGraph->sources.append(*this);
  555. trace("change sink");
  556. }
  557. bool ResourceGraphLink::isRedundantLink()
  558. {
  559. ResourcerInfo * info = queryResourceInfo(sourceNode);
  560. return info->expandRatherThanSpill(false);
  561. }
  562. void ResourceGraphLink::trace(const char * name)
  563. {
  564. #ifdef TRACE_RESOURCING
  565. PrintLog("%s: %lx source(%lx,%lx) sink(%lx,%lx) %s", name, this, sourceGraph.get(), sourceNode->queryBody(), sinkGraph.get(), sinkNode ? sinkNode->queryBody() : NULL,
  566. linkKind == ConditionalLink ? "conditional" : linkKind == SequenceLink ? "sequence" : "");
  567. #endif
  568. }
  569. ResourceGraphDependencyLink::ResourceGraphDependencyLink(ResourceGraphInfo * _sourceGraph, IHqlExpression * _sourceNode, ResourceGraphInfo * _sinkGraph, IHqlExpression * _sinkNode)
  570. : ResourceGraphLink(_sourceGraph, _sourceNode, _sinkGraph, _sinkNode, UnconditionalLink)
  571. {
  572. }
  573. void ResourceGraphDependencyLink::changeSourceGraph(ResourceGraphInfo * newGraph)
  574. {
  575. sourceGraph.set(newGraph);
  576. trace("change source");
  577. }
  578. void ResourceGraphDependencyLink::changeSinkGraph(ResourceGraphInfo * newGraph)
  579. {
  580. sinkGraph.set(newGraph);
  581. newGraph->dependsOn.append(*this);
  582. trace("change sink");
  583. }
  584. //---------------------------------------------------------------------------
  585. ResourceGraphInfo::ResourceGraphInfo(CResourceOptions * _options) : resources(_options->clusterSize)
  586. {
  587. options = _options;
  588. depth = 0;
  589. beenResourced = false;
  590. isUnconditional = false;
  591. mergedConditionSource = false;
  592. hasConditionSource = false;
  593. isDead = false;
  594. gatheredDependants = false;
  595. startedGeneratingResourced = false;
  596. inheritedExpandedDependencies = false;
  597. }
  598. ResourceGraphInfo::~ResourceGraphInfo()
  599. {
  600. }
  601. bool ResourceGraphInfo::addCondition(IHqlExpression * condition)
  602. {
  603. if (conditions.find(*condition) == NotFound)
  604. {
  605. conditions.append(*LINK(condition));
  606. #ifdef SPOT_UNCONDITIONAL_CONDITIONS
  607. _ATOM name = condition->queryName();
  608. _ATOM invName = NULL;
  609. if (name == trueAtom)
  610. invName = falseAtom;
  611. else if (name == falseAtom)
  612. invName = trueAtom;
  613. if (invName)
  614. {
  615. IHqlExpression * parent = condition->queryChild(1);
  616. OwnedHqlExpr invTag = createAttribute(invName, LINK(condition->queryChild(0)), LINK(parent));
  617. if (conditions.find(*invTag) != NotFound)
  618. {
  619. if (!parent)
  620. return true;
  621. return addCondition(parent);
  622. }
  623. }
  624. #endif
  625. }
  626. return false;
  627. }
  628. bool ResourceGraphInfo::isSharedInput(IHqlExpression * expr)
  629. {
  630. IHqlExpression * body = expr->queryBody();
  631. if (unbalancedExternalSources.contains(*body))
  632. return false;
  633. if (queryResourceInfo(expr)->expandRatherThanSplit())
  634. return false;
  635. unsigned numUses = 0;
  636. ForEachItemIn(i, balancedExternalSources)
  637. {
  638. if (body == &balancedExternalSources.item(i))
  639. numUses++;
  640. }
  641. //NumUses could be zero if an input should be expanded, and that input is shared by another graph which also expands
  642. //the input. E.g. project(meta(diskread).
  643. return numUses > 1;
  644. }
  645. void ResourceGraphInfo::addSharedInput(IHqlExpression * expr, IHqlExpression * mapped)
  646. {
  647. sharedInputs.append(*LINK(expr));
  648. sharedInputs.append(*LINK(mapped));
  649. }
  650. IHqlExpression * ResourceGraphInfo::queryMappedSharedInput(IHqlExpression * expr)
  651. {
  652. unsigned max = sharedInputs.ordinality();
  653. for (unsigned i=0; i < max; i+= 2)
  654. {
  655. if (expr == &sharedInputs.item(i))
  656. return &sharedInputs.item(i+1);
  657. }
  658. return NULL;
  659. }
  660. bool ResourceGraphInfo::allocateResources(const CResources & value, const CResources & limit)
  661. {
  662. if (resources.addExceeds(value, limit))
  663. return false;
  664. resources.add(value);
  665. return true;
  666. }
  667. bool ResourceGraphInfo::containsActiveSinks()
  668. {
  669. ForEachItemIn(idx, sinks)
  670. {
  671. ResourcerInfo * info = queryResourceInfo(sinks.item(idx).sourceNode);
  672. if (!info->expandRatherThanSpill(false))
  673. return true;
  674. }
  675. return false;
  676. }
  677. void ResourceGraphInfo::display()
  678. {
  679. StringBuffer s;
  680. s.appendf("graph %p src(", this);
  681. ForEachItemIn(idxs, sources)
  682. s.appendf("%p ", sources.item(idxs).sourceGraph.get());
  683. s.append(") dep(");
  684. ForEachItemIn(idxd, dependsOn)
  685. s.appendf("%p ", dependsOn.item(idxd).sourceGraph.get());
  686. s.append(")");
  687. if (isUnconditional)
  688. s.append(" <unconditional>");
  689. DBGLOG("%s", s.str());
  690. }
  691. void ResourceGraphInfo::expandDependants(ResourceGraphArray & target)
  692. {
  693. ForEachItemIn(idx, dependsOn)
  694. {
  695. ResourceGraphInfo * source = dependsOn.item(idx).sourceGraph;
  696. if (target.find(*source) == NotFound)
  697. target.append(*LINK(source));
  698. }
  699. ForEachItemIn(idx2, sources)
  700. {
  701. ResourceGraphLink & cur = sources.item(idx2);
  702. // if (!queryResourceInfo(cur.sourceNode)->expandRatherThanSpill())
  703. {
  704. ResourceGraphInfo * source = cur.sourceGraph;
  705. if (target.find(*source) == NotFound)
  706. target.append(*LINK(source));
  707. }
  708. }
  709. ForEachItemIn(idx3, indirectSources)
  710. {
  711. ResourceGraphInfo & cur = indirectSources.item(idx3);
  712. if (target.find(cur) == NotFound)
  713. target.append(OLINK(cur));
  714. }
  715. }
  716. void ResourceGraphInfo::gatherDependants(bool recalculate)
  717. {
  718. if (gatheredDependants && !recalculate)
  719. return;
  720. gatheredDependants = true;
  721. depth = 0;
  722. indirectSources.kill();
  723. ForEachItemIn(idx, dependsOn)
  724. {
  725. ResourceGraphInfo * source = dependsOn.item(idx).sourceGraph;
  726. source->gatherDependants(false);
  727. source->expandDependants(indirectSources);
  728. if (source->depth >= depth)
  729. depth = source->depth + 1;
  730. }
  731. ForEachItemIn(idx2, sources)
  732. {
  733. ResourceGraphInfo * source = sources.item(idx2).sourceGraph;
  734. source->gatherDependants(false);
  735. source->expandDependants(indirectSources);
  736. if (source->getDepth() >= depth)
  737. depth = source->getDepth() + 1;
  738. }
  739. }
  740. void ResourceGraphInfo::getMergeFailReason(StringBuffer & reasonText, ResourceGraphInfo * otherGraph, const CResources & limit)
  741. {
  742. resources.getExceedsReason(reasonText, otherGraph->resources, limit);
  743. }
  744. void ResourceGraphInfo::replaceReferences(ResourceGraphInfo * oldGraph, ResourceGraphInfo * newGraph)
  745. {
  746. if (indirectSources.find(*oldGraph) != NotFound)
  747. gatheredDependants = false;
  748. }
  749. unsigned ResourceGraphInfo::getDepth()
  750. {
  751. gatherDependants(false);
  752. return depth;
  753. }
  754. bool ResourceGraphInfo::hasSameConditions(ResourceGraphInfo & other)
  755. {
  756. if (conditions.ordinality() != other.conditions.ordinality())
  757. return false;
  758. ForEachItemIn(i, conditions)
  759. if (other.conditions.find(conditions.item(i)) == NotFound)
  760. return false;
  761. return true;
  762. }
  763. bool ResourceGraphInfo::isDependentOn(ResourceGraphInfo & other, bool allowDirect)
  764. {
  765. gatherDependants(false);
  766. ForEachItemIn(idx, dependsOn)
  767. {
  768. ResourceGraphInfo * cur = dependsOn.item(idx).sourceGraph;
  769. if (cur == &other)
  770. return true;
  771. }
  772. ForEachItemIn(idx2, indirectSources)
  773. {
  774. ResourceGraphInfo & cur = indirectSources.item(idx2);
  775. if (&cur == &other)
  776. return true;
  777. }
  778. if (!allowDirect)
  779. {
  780. ForEachItemIn(idx3, sources)
  781. {
  782. if (sources.item(idx3).sourceGraph == &other)
  783. return true;
  784. }
  785. }
  786. return false;
  787. }
  788. bool ResourceGraphInfo::isVeryCheap()
  789. {
  790. if (sinks.ordinality() != 1)
  791. return false;
  792. IHqlExpression * sourceNode = sinks.item(0).sourceNode;
  793. if (isSimpleAggregateResult(sourceNode))
  794. return true;
  795. // Not sure about the following....
  796. // if (sourceNode->getOperator() == no_setresult)
  797. // return true;
  798. //Could be other examples...
  799. return false;
  800. }
  801. bool ResourceGraphInfo::mergeInSource(ResourceGraphInfo & other, const CResources & limit, bool isConditionalLink)
  802. {
  803. bool mergeConditions = false;
  804. if (!isUnconditional)
  805. {
  806. //if it is conditional and it is very cheap then it is still more efficient to merge
  807. //rather than read from a spill file.
  808. if (other.isUnconditional || !hasSameConditions(other))
  809. {
  810. if ((hasConditionSource || !isVeryCheap()) && (other.sinks.ordinality() != 1))
  811. return false;
  812. mergeConditions = true;
  813. }
  814. }
  815. if (isDependentOn(other, true))
  816. return false;
  817. if (!options->canSplit())
  818. {
  819. //Don't merge two graphs that will cause a splitter to be created
  820. //Either already used internally, or an output will be merged twice
  821. HqlExprArray mergeNodes;
  822. ForEachItemIn(idx, sources)
  823. {
  824. ResourceGraphLink & cur = sources.item(idx);
  825. if (cur.sourceGraph == &other)
  826. {
  827. IHqlExpression * sourceNode = cur.sourceNode->queryBody();
  828. ResourcerInfo * info = queryResourceInfo(sourceNode);
  829. if ((info->numInternalUses() != 0) || (mergeNodes.find(*sourceNode) != NotFound) || info->preventMerge())
  830. return false;
  831. mergeNodes.append(*LINK(sourceNode));
  832. }
  833. }
  834. }
  835. if (options->checkResources() && !allocateResources(other.resources, limit))
  836. return false;
  837. mergeGraph(other, isConditionalLink, mergeConditions);
  838. return true;
  839. }
  840. void ResourceGraphInfo::mergeGraph(ResourceGraphInfo & other, bool isConditionalLink, bool mergeConditions)
  841. {
  842. #ifdef TRACE_RESOURCING
  843. DBGLOG("Merging%s source into%s sink", other.isUnconditional ? "" : " conditional", isUnconditional ? "" : " conditional");
  844. other.display();
  845. display();
  846. PrintLog("Merge %p into %p", &other, this);
  847. #endif
  848. if (other.hasConditionSource)
  849. hasConditionSource = true;
  850. //Recalculate the dependents, because sources of the source merged in may no longer be indirect
  851. //although they may be via another path.
  852. gatheredDependants = false;
  853. //Any of my sources will already have the correct dependencies, however,
  854. //anything that is a sink of the source has just gained some dependencies.
  855. ForEachItemIn(idx, other.sinks)
  856. {
  857. ResourceGraphInfo * graph = other.sinks.item(idx).sinkGraph;
  858. if (graph)
  859. graph->gatheredDependants = false;
  860. }
  861. //If was very cheap and merged into an unconditional graph, make sure this is now tagged as
  862. //unconditional...
  863. if (other.isUnconditional)
  864. isUnconditional = true;
  865. //We need to stop spills being an arm of a conditional branch - otherwise they won't get executed.
  866. //so see if we have merged any conditional branches in
  867. if (isConditionalLink || other.mergedConditionSource)
  868. mergedConditionSource = true;
  869. if (mergeConditions)
  870. {
  871. //Replace conditions with those of parent. Only called when a very simple graph is
  872. //merged in, so replace conditions instead of merging
  873. conditions.kill();
  874. ForEachItemIn(i, other.conditions)
  875. conditions.append(OLINK(other.conditions.item(i)));
  876. }
  877. //sources and sinks are updated elsewhere...
  878. }
  879. bool ResourceGraphInfo::mergeInSibling(ResourceGraphInfo & other, const CResources & limit)
  880. {
  881. if ((!isUnconditional || !other.isUnconditional) && !hasSameConditions(other))
  882. return false;
  883. if (isDependentOn(other, false) || other.isDependentOn(*this, false))
  884. return false;
  885. if (options->checkResources() && !allocateResources(other.resources, limit))
  886. return false;
  887. mergeGraph(other, false, false);
  888. return true;
  889. }
  890. void ResourceGraphInfo::removeResources(const CResources & value)
  891. {
  892. resources.sub(value);
  893. }
  894. //---------------------------------------------------------------------------
  895. ResourcerInfo::ResourcerInfo(IHqlExpression * _original, CResourceOptions * _options)
  896. {
  897. original.set(_original);
  898. numUses = 0;
  899. numExternalUses = 0;
  900. gatheredDependencies = false;
  901. containsActivity = false;
  902. isActivity = false;
  903. transformed = NULL;
  904. conditionSourceCount = 0;
  905. pathToExpr = PathUnknown;
  906. outputToUseForSpill = NULL;
  907. isAlreadyInScope = false;
  908. isSpillPoint = false;
  909. options = _options;
  910. balanced = true;
  911. currentSource = 0;
  912. linkedFromChild = false;
  913. neverSplit = false;
  914. }
  915. void ResourcerInfo::setConditionSource(IHqlExpression * condition, bool isFirst)
  916. {
  917. if (isFirst)
  918. {
  919. conditionSourceCount++;
  920. graph->hasConditionSource = true;
  921. }
  922. }
  923. bool ResourcerInfo::addCondition(IHqlExpression * condition)
  924. {
  925. conditions.append(*LINK(condition));
  926. return graph->addCondition(condition);
  927. }
  928. void ResourcerInfo::addSpillFlags(HqlExprArray & args, bool isRead)
  929. {
  930. IHqlExpression * grouping = (IHqlExpression *)original->queryType()->queryGroupInfo();
  931. if (grouping)
  932. args.append(*createAttribute(groupedAtom));
  933. if (outputToUseForSpill)
  934. {
  935. assertex(isRead);
  936. if (outputToUseForSpill->hasProperty(__compressed__Atom))
  937. args.append(*createAttribute(__compressed__Atom));
  938. }
  939. else
  940. {
  941. args.append(*createAttribute(__compressed__Atom));
  942. args.append(*createAttribute(_spill_Atom));
  943. args.append(*createAttribute(_noReplicate_Atom));
  944. if (options->targetRoxie())
  945. args.append(*createAttribute(_noAccess_Atom));
  946. }
  947. if (isRead)
  948. {
  949. args.append(*createAttribute(_noVirtual_Atom)); // Don't interpret virtual fields as virtual...
  950. if (!original->isDataset() || hasSingleRow(original))
  951. args.append(*createAttribute(rowAtom)); // add a flag so the selectnth[1] can be removed later...
  952. }
  953. else
  954. {
  955. unsigned numUses = numExternalUses;
  956. if (false) // options->cloneConditionals)
  957. {
  958. //Remove all the links from conditional graphs...
  959. ForEachItemIn(i1, graph->sinks)
  960. {
  961. ResourceGraphLink & cur = graph->sinks.item(i1);
  962. if ((cur.sourceNode == original) && (cur.linkKind == ConditionalLink || !cur.sinkGraph->isUnconditional))
  963. numUses--;
  964. }
  965. numUses += calcNumConditionalUses();
  966. }
  967. args.append(*createAttribute(_tempCount_Atom, getSizetConstant(numUses)));
  968. }
  969. }
  970. bool ResourcerInfo::alwaysExpand()
  971. {
  972. return (original->getOperator() == no_mapto);
  973. }
  974. static IHqlExpression * stripTrueFalse(IHqlExpression * expr)
  975. {
  976. if (expr->queryName() == instanceAtom)
  977. {
  978. IHqlExpression * parent = expr->queryChild(2);
  979. if (parent)
  980. parent = stripTrueFalse(parent);
  981. return createAttribute(instanceAtom, LINK(expr->queryChild(0)), LINK(expr->queryChild(1)), parent);
  982. }
  983. else
  984. {
  985. IHqlExpression * parent = expr->queryChild(1);
  986. if (parent && parent->isAttribute())
  987. parent = stripTrueFalse(parent);
  988. return createAttribute(tempAtom, LINK(expr->queryChild(0)), parent);
  989. }
  990. }
  991. unsigned ResourcerInfo::calcNumConditionalUses()
  992. {
  993. //for thor and hthor, where the conditional graph is cloned, the maximum number of times it can be read
  994. //is 1 for a shared conditional graph, or once for each combination of conditions it is used as the
  995. //input for. However if it is used more than once in a single branch of a condition it needs to be counted
  996. //several times.
  997. //It is always better to overestimate than underestimate. (But even better to get it right.)
  998. HqlExprArray uniqueConditions;
  999. UnsignedArray uniqueCounts;
  1000. ForEachItemIn(idx, conditions)
  1001. {
  1002. IHqlExpression & cur = conditions.item(idx);
  1003. OwnedHqlExpr unique = stripTrueFalse(&cur);
  1004. unsigned numOccurences = 0;
  1005. ForEachItemIn(j, conditions)
  1006. if (&conditions.item(j) == &cur)
  1007. numOccurences++;
  1008. unsigned match = uniqueConditions.find(*unique);
  1009. if (match == NotFound)
  1010. {
  1011. uniqueConditions.append(*unique.getClear());
  1012. uniqueCounts.append(numOccurences);
  1013. }
  1014. else
  1015. {
  1016. if (uniqueCounts.item(match) < numOccurences)
  1017. uniqueCounts.replace(numOccurences, match);
  1018. }
  1019. }
  1020. unsigned condUses = 0;
  1021. ForEachItemIn(k, uniqueCounts)
  1022. condUses += uniqueCounts.item(k);
  1023. return condUses;
  1024. }
  1025. // Each aggregate has form. Setresult(select(selectnth(aggregate...,1),field),name,seq)
  1026. IHqlExpression * ResourcerInfo::createAggregation(IHqlExpression * expr)
  1027. {
  1028. LinkedHqlExpr transformed = expr;
  1029. ForEachItemIn(idx, aggregates)
  1030. {
  1031. IHqlExpression & cur = aggregates.item(idx);
  1032. IHqlExpression * row2ds = cur.queryChild(0);
  1033. IHqlExpression * selectnth = row2ds->queryChild(0);
  1034. IHqlExpression * aggregate = selectnth->queryChild(0);
  1035. IHqlExpression * aggregateRecord = aggregate->queryChild(1);
  1036. assertex(aggregate->getOperator() == no_newaggregate);
  1037. HqlExprArray aggargs, setargs;
  1038. //Through aggregate has form (dataset, record, transform, list of set results);
  1039. aggargs.append(*LINK(transformed));
  1040. aggargs.append(*LINK(aggregateRecord));
  1041. IHqlExpression * mapped = replaceSelector(aggregate->queryChild(2), original, expr->queryNormalizedSelector());
  1042. aggargs.append(*mapped);
  1043. OwnedHqlExpr active = createDataset(no_anon, LINK(aggregateRecord), NULL);
  1044. OwnedHqlExpr mappedSelect = replaceSelector(cur.queryChild(1), row2ds, active);
  1045. setargs.append(*LINK(active));
  1046. setargs.append(*LINK(mappedSelect));
  1047. unwindChildren(setargs, &cur, 1);
  1048. aggargs.append(*createValue(no_extractresult, makeVoidType(), setargs));
  1049. transformed.setown(createDataset(no_throughaggregate, aggargs));
  1050. }
  1051. return transformed.getClear();
  1052. }
  1053. bool ResourcerInfo::useGraphResult()
  1054. {
  1055. if (!options->useGraphResults)
  1056. return false;
  1057. if (linkedFromChild)
  1058. return true;
  1059. if (options->targetClusterType != HThorCluster)
  1060. return false;
  1061. return true;
  1062. }
  1063. bool ResourcerInfo::useGlobalResult()
  1064. {
  1065. return (linkedFromChild && !useGraphResult());
  1066. }
  1067. IHqlExpression * ResourcerInfo::createSpillName()
  1068. {
  1069. if (outputToUseForSpill)
  1070. return LINK(outputToUseForSpill->queryChild(1));
  1071. if (!spillName)
  1072. {
  1073. if (useGraphResult())
  1074. spillName.setown(options->createSpillName(true));
  1075. else if (useGlobalResult())
  1076. {
  1077. StringBuffer valueText;
  1078. getUniqueId(valueText.append("spill"));
  1079. spillName.setown(createConstant(valueText.str()));
  1080. }
  1081. else
  1082. spillName.setown(options->createSpillName(false));
  1083. }
  1084. return LINK(spillName);
  1085. }
  1086. IHqlExpression * ResourcerInfo::createSpilledRead(IHqlExpression * spillReason)
  1087. {
  1088. OwnedHqlExpr dataset;
  1089. HqlExprArray args;
  1090. IHqlExpression * record = original->queryRecord();
  1091. bool loseDistribution = true;
  1092. if (useGraphResult())
  1093. {
  1094. args.append(*LINK(record));
  1095. args.append(*LINK(options->graphIdExpr));
  1096. args.append(*createSpillName());
  1097. if (isGrouped(original))
  1098. args.append(*createAttribute(groupedAtom));
  1099. if (!original->isDataset())
  1100. args.append(*createAttribute(rowAtom));
  1101. args.append(*createAttribute(_spill_Atom));
  1102. IHqlExpression * recordCountAttr = queryRecordCountInfo(original);
  1103. if (recordCountAttr)
  1104. args.append(*LINK(recordCountAttr));
  1105. if (options->targetThor() && original->isDataset() && !options->isChildQuery)
  1106. args.append(*createAttribute(_distributed_Atom));
  1107. dataset.setown(createDataset(no_getgraphresult, args));
  1108. }
  1109. else if (useGlobalResult())
  1110. {
  1111. args.append(*LINK(record));
  1112. args.append(*createAttribute(nameAtom, createSpillName()));
  1113. args.append(*createAttribute(sequenceAtom, getLocalSequenceNumber()));
  1114. addSpillFlags(args, true);
  1115. IHqlExpression * recordCountAttr = queryRecordCountInfo(original);
  1116. if (recordCountAttr)
  1117. args.append(*LINK(recordCountAttr));
  1118. dataset.setown(createDataset(no_workunit_dataset, args));
  1119. }
  1120. else
  1121. {
  1122. if (spilledDataset)
  1123. {
  1124. args.append(*LINK(spilledDataset));
  1125. args.append(*createSpillName());
  1126. }
  1127. else
  1128. {
  1129. args.append(*createSpillName());
  1130. args.append(*LINK(record));
  1131. }
  1132. args.append(*createValue(no_thor));
  1133. addSpillFlags(args, true);
  1134. args.append(*createUniqueId());
  1135. if (options->isChildQuery && options->targetRoxie())
  1136. {
  1137. args.append(*createAttribute(_colocal_Atom));
  1138. args.append(*createLocalAttribute());
  1139. }
  1140. if (spillReason)
  1141. args.append(*LINK(spillReason));
  1142. if (spilledDataset)
  1143. dataset.setown(createDataset(no_readspill, args));
  1144. else
  1145. {
  1146. IHqlExpression * recordCountAttr = queryRecordCountInfo(original);
  1147. if (recordCountAttr)
  1148. args.append(*LINK(recordCountAttr));
  1149. dataset.setown(createDataset(no_table, args));
  1150. }
  1151. loseDistribution = false;
  1152. }
  1153. dataset.setown(preserveTableInfo(dataset, original, loseDistribution, NULL));
  1154. return wrapRowOwn(dataset.getClear());
  1155. }
  1156. IHqlExpression * ResourcerInfo::createSpilledWrite(IHqlExpression * transformed)
  1157. {
  1158. assertex(!outputToUseForSpill);
  1159. HqlExprArray args;
  1160. if (useGraphResult())
  1161. {
  1162. assertex(options->graphIdExpr);
  1163. args.append(*LINK(transformed));
  1164. args.append(*LINK(options->graphIdExpr));
  1165. args.append(*createSpillName());
  1166. args.append(*createAttribute(_spill_Atom));
  1167. return createValue(no_setgraphresult, makeVoidType(), args);
  1168. }
  1169. else if (useGlobalResult())
  1170. {
  1171. args.append(*LINK(transformed));
  1172. args.append(*createAttribute(sequenceAtom, getLocalSequenceNumber()));
  1173. args.append(*createAttribute(namedAtom, createSpillName()));
  1174. addSpillFlags(args, false);
  1175. return createValue(no_output, makeVoidType(), args);
  1176. }
  1177. else
  1178. {
  1179. if (options->createSpillAsDataset)
  1180. {
  1181. IHqlExpression * value = LINK(transformed);
  1182. if (value->isDatarow())
  1183. value = createDatasetFromRow(value);
  1184. spilledDataset.setown(createDataset(no_commonspill, value));
  1185. args.append(*LINK(spilledDataset));
  1186. }
  1187. else
  1188. args.append(*LINK(transformed));
  1189. args.append(*createSpillName());
  1190. addSpillFlags(args, false);
  1191. if (options->createSpillAsDataset)
  1192. return createValue(no_writespill, makeVoidType(), args);
  1193. return createValue(no_output, makeVoidType(), args);
  1194. }
  1195. }
  1196. bool ResourcerInfo::okToSpillThrough()
  1197. {
  1198. bool isGraphResult = useGraphResult();
  1199. if (isGraphResult)
  1200. return options->allowThroughResult;
  1201. if (useGlobalResult())
  1202. return false;
  1203. return (options->allowThroughSpill && !options->createSpillAsDataset);
  1204. }
  1205. bool ResourcerInfo::spillSharesSplitter()
  1206. {
  1207. if (outputToUseForSpill || useGraphResult() || useGlobalResult())
  1208. return false;
  1209. if (okToSpillThrough())
  1210. return false;
  1211. if (!isSplit() || !balanced)
  1212. return false;
  1213. return true;
  1214. }
  1215. IHqlExpression * ResourcerInfo::createSpiller(IHqlExpression * transformed, bool reuseSplitter)
  1216. {
  1217. if (outputToUseForSpill)
  1218. return LINK(transformed);
  1219. if (!okToSpillThrough())
  1220. {
  1221. OwnedHqlExpr split;
  1222. if (reuseSplitter)
  1223. {
  1224. assertex(transformed->getOperator() == no_split);
  1225. split.set(transformed);
  1226. }
  1227. else
  1228. {
  1229. if (transformed->isDataset())
  1230. split.setown(createDataset(no_split, LINK(transformed), createComma(createAttribute(balancedAtom), createUniqueId())));
  1231. else
  1232. split.setown(createRow(no_split, LINK(transformed), createComma(createAttribute(balancedAtom), createUniqueId())));
  1233. split.setown(cloneInheritedAnnotations(original, split));
  1234. }
  1235. splitterOutput.setown(createSpilledWrite(split));
  1236. return split.getClear();
  1237. }
  1238. HqlExprArray args;
  1239. node_operator op;
  1240. args.append(*LINK(transformed));
  1241. if (useGraphResult())
  1242. {
  1243. op = no_spillgraphresult;
  1244. args.append(*LINK(options->graphIdExpr));
  1245. args.append(*createSpillName());
  1246. args.append(*createAttribute(_spill_Atom));
  1247. }
  1248. else
  1249. {
  1250. op = no_spill;
  1251. args.append(*createSpillName());
  1252. addSpillFlags(args, false);
  1253. }
  1254. OwnedHqlExpr spill;
  1255. if (original->isDatarow())
  1256. spill.setown(createRow(op, args));
  1257. else
  1258. spill.setown(createDataset(op, args));
  1259. return cloneInheritedAnnotations(original, spill);
  1260. }
  1261. IHqlExpression * ResourcerInfo::createSplitter(IHqlExpression * transformed)
  1262. {
  1263. if (transformed->getOperator() == no_libraryscopeinstance)
  1264. return LINK(transformed);
  1265. IHqlExpression * attr = createUniqueId();
  1266. if (balanced)
  1267. attr = createComma(attr, createAttribute(balancedAtom));
  1268. OwnedHqlExpr split;
  1269. if (transformed->isDataset())
  1270. split.setown(createDataset(no_split, LINK(transformed), attr));
  1271. else
  1272. split.setown(createRow(no_split, LINK(transformed), attr));
  1273. return cloneInheritedAnnotations(original, split);
  1274. }
  1275. IHqlExpression * ResourcerInfo::createTransformedExpr(IHqlExpression * expr)
  1276. {
  1277. LinkedHqlExpr transformed = expr;
  1278. if (aggregates.ordinality())
  1279. transformed.setown(createAggregation(transformed));
  1280. if (spillSharesSplitter())
  1281. {
  1282. transformed.setown(createSplitter(transformed));
  1283. if (isExternalSpill())
  1284. transformed.setown(createSpiller(transformed, true));
  1285. }
  1286. else
  1287. {
  1288. if (isExternalSpill())
  1289. transformed.setown(createSpiller(transformed, false));
  1290. if (isSplit())
  1291. transformed.setown(createSplitter(transformed));
  1292. else if (isSpilledWrite())
  1293. transformed.setown(createSpilledWrite(transformed));
  1294. }
  1295. return transformed.getClear();
  1296. }
  1297. bool ResourcerInfo::expandRatherThanSpill(bool noteOtherSpills)
  1298. {
  1299. if (options->shareDontExpand)
  1300. return expandRatherThanSplit();
  1301. IHqlExpression * expr = original;
  1302. if (!options->minimiseSpills || linkedFromChild)
  1303. noteOtherSpills = false;
  1304. if (noteOtherSpills)
  1305. {
  1306. ResourcerInfo * info = queryResourceInfo(expr);
  1307. if (info && info->isSpilledWrite())
  1308. return (info->transformed == NULL);
  1309. }
  1310. bool isFiltered = false;
  1311. bool isProcessed = false;
  1312. loop
  1313. {
  1314. ResourcerInfo * info = queryResourceInfo(expr);
  1315. if (info && info->neverSplit)
  1316. return true;
  1317. node_operator op = expr->getOperator();
  1318. switch (op)
  1319. {
  1320. case no_table:
  1321. {
  1322. //This is only executed for hthor/thor. Roxie has used expandRatherThanSplit().
  1323. //We need to balance the saving from reading reduced data in the other branches with the cost of
  1324. //writing the spill file to disk.
  1325. if (isFiltered && (numExternalUses >= options->filteredSpillThreshold))
  1326. return false;
  1327. IHqlExpression * mode = expr->queryChild(2);
  1328. switch (mode->getOperator())
  1329. {
  1330. case no_thor: case no_flat:
  1331. //MORE: The following is possibly better - but roxie should be able to read from non spill data files in child queries fine
  1332. //if ((options->targetClusterType == RoxieCluster) && linkedFromChild)) return false;
  1333. return true;
  1334. default:
  1335. return false;
  1336. }
  1337. }
  1338. case no_stepped:
  1339. return true;
  1340. case no_inlinetable:
  1341. {
  1342. IHqlExpression * transforms = expr->queryChild(0);
  1343. //The inline table code means this should generate smaller code, and more efficient
  1344. if (!isFiltered && !isProcessed && transforms->isConstant())
  1345. return true;
  1346. if (transforms->numChildren() > MAX_INLINE_COMMON_COUNT)
  1347. return false;
  1348. return true;
  1349. }
  1350. case no_getresult:
  1351. case no_temptable:
  1352. case no_rows:
  1353. case no_xmlproject:
  1354. case no_workunit_dataset:
  1355. return !isProcessed && !isFiltered;
  1356. case no_getgraphresult:
  1357. return !expr->hasProperty(_streaming_Atom); // we must not duplicate streaming inputs!
  1358. case no_keyindex:
  1359. case no_newkeyindex:
  1360. if (!isFiltered)
  1361. return true;
  1362. return options->cloneFilteredIndex;
  1363. case no_datasetfromrow:
  1364. if (getNumActivityArguments(expr) == 0)
  1365. return true;
  1366. return false;
  1367. case no_fail:
  1368. case no_null:
  1369. return !expr->isAction();
  1370. case no_assertsorted:
  1371. case no_sorted:
  1372. case no_grouped:
  1373. case no_distributed:
  1374. case no_preservemeta:
  1375. case no_nofold:
  1376. case no_nohoist:
  1377. case no_section:
  1378. case no_sectioninput:
  1379. case no_dataset_alias:
  1380. expr = expr->queryChild(0);
  1381. break;
  1382. case no_newusertable:
  1383. case no_limit:
  1384. case no_keyedlimit:
  1385. expr = expr->queryChild(0);
  1386. isProcessed = true;
  1387. break;
  1388. case no_hqlproject:
  1389. if (expr->hasProperty(_countProject_Atom) || expr->hasProperty(prefetchAtom))
  1390. return false;
  1391. expr = expr->queryChild(0);
  1392. isProcessed = true;
  1393. break;
  1394. //MORE: Not so sure about all the following, include them so behaviour doesn't change
  1395. case no_compound_diskread:
  1396. case no_compound_disknormalize:
  1397. case no_compound_diskaggregate:
  1398. case no_compound_diskcount:
  1399. case no_compound_diskgroupaggregate:
  1400. case no_compound_indexread:
  1401. case no_compound_indexnormalize:
  1402. case no_compound_indexaggregate:
  1403. case no_compound_indexcount:
  1404. case no_compound_indexgroupaggregate:
  1405. case no_compound_childread:
  1406. case no_compound_childnormalize:
  1407. case no_compound_childaggregate:
  1408. case no_compound_childcount:
  1409. case no_compound_childgroupaggregate:
  1410. case no_compound_selectnew:
  1411. case no_compound_inline:
  1412. expr = expr->queryChild(0);
  1413. break;
  1414. case no_filter:
  1415. isFiltered = true;
  1416. expr = expr->queryChild(0);
  1417. break;
  1418. case no_select:
  1419. {
  1420. if (options->targetClusterType == RoxieCluster)
  1421. return false;
  1422. if (!expr->hasProperty(newAtom))
  1423. return true;
  1424. expr = expr->queryChild(0);
  1425. break;
  1426. }
  1427. default:
  1428. return false;
  1429. }
  1430. //The following reduces the number of spills by taking into account other spills.
  1431. if (noteOtherSpills)
  1432. {
  1433. ResourcerInfo * info = queryResourceInfo(expr);
  1434. if (info)
  1435. {
  1436. if (info->isSpilledWrite())
  1437. return (info->transformed == NULL);
  1438. if (info->numExternalUses)
  1439. {
  1440. if (isFiltered && (numExternalUses >= options->filteredSpillThreshold))
  1441. return false;
  1442. return true;
  1443. }
  1444. }
  1445. }
  1446. }
  1447. }
  1448. bool ResourcerInfo::expandRatherThanSplit()
  1449. {
  1450. //MORE: This doesn't really work - should do indexMatching first.
  1451. //should only expand if one side that uses this is also filtered
  1452. IHqlExpression * expr = original;
  1453. loop
  1454. {
  1455. ResourcerInfo * info = queryResourceInfo(expr);
  1456. if (info && info->neverSplit)
  1457. return true;
  1458. switch (expr->getOperator())
  1459. {
  1460. case no_keyindex:
  1461. case no_newkeyindex:
  1462. case no_rowset:
  1463. case no_getgraphloopresultset:
  1464. return true;
  1465. case no_null:
  1466. return !expr->isAction();
  1467. case no_inlinetable:
  1468. if (options->expandSingleConstRow && hasSingleRow(expr))
  1469. {
  1470. IHqlExpression * values = expr->queryChild(0);
  1471. if (values->queryChild(0)->isConstant())
  1472. return true;
  1473. }
  1474. return false;
  1475. case no_stepped:
  1476. case no_rowsetrange:
  1477. case no_rowsetindex:
  1478. return true;
  1479. case no_sorted:
  1480. case no_grouped:
  1481. case no_distributed:
  1482. case no_preservemeta:
  1483. case no_compound_diskread:
  1484. case no_compound_disknormalize:
  1485. case no_compound_diskaggregate:
  1486. case no_compound_diskcount:
  1487. case no_compound_diskgroupaggregate:
  1488. case no_compound_indexread:
  1489. case no_compound_indexnormalize:
  1490. case no_compound_indexaggregate:
  1491. case no_compound_indexcount:
  1492. case no_compound_indexgroupaggregate:
  1493. case no_compound_childread:
  1494. case no_compound_childnormalize:
  1495. case no_compound_childaggregate:
  1496. case no_compound_childcount:
  1497. case no_compound_childgroupaggregate:
  1498. case no_compound_selectnew:
  1499. case no_compound_inline:
  1500. case no_section:
  1501. case no_sectioninput:
  1502. case no_dataset_alias:
  1503. break;
  1504. case no_select:
  1505. if (options->targetClusterType == RoxieCluster)
  1506. return false;
  1507. if (!expr->hasProperty(newAtom))
  1508. {
  1509. if (!options->useLinkedRawIterator || !hasLinkCountedModifier(expr))
  1510. return false;
  1511. return true;
  1512. }
  1513. break;
  1514. case no_rows:
  1515. //If executing in a child query then you'll have less thread contention if the iterator is duplicated
  1516. //So should probably uncomment the following.
  1517. //return true;
  1518. return false;
  1519. default:
  1520. return false;
  1521. }
  1522. expr = expr->queryChild(0);
  1523. }
  1524. }
  1525. bool neverCommonUp(IHqlExpression * expr)
  1526. {
  1527. loop
  1528. {
  1529. node_operator op = expr->getOperator();
  1530. switch (op)
  1531. {
  1532. case no_keyindex:
  1533. case no_newkeyindex:
  1534. return true;
  1535. case no_filter:
  1536. expr = expr->queryChild(0);
  1537. break;
  1538. default:
  1539. return false;
  1540. }
  1541. }
  1542. }
  1543. bool ResourcerInfo::neverCommonUp()
  1544. {
  1545. return ::neverCommonUp(original);
  1546. }
  1547. bool ResourcerInfo::isExternalSpill()
  1548. {
  1549. if (expandRatherThanSpill(true) || (numInternalUses() == 0))
  1550. return false;
  1551. return (numExternalUses != 0);
  1552. }
  1553. bool ResourcerInfo::isSplit()
  1554. {
  1555. return numSplitPaths() > 1;
  1556. }
  1557. unsigned ResourcerInfo::numSplitPaths()
  1558. {
  1559. unsigned internal = numInternalUses();
  1560. if ((internal == 0) || !options->allowSplitBetweenSubGraphs)
  1561. return internal;
  1562. //MORE
  1563. return internal;
  1564. }
  1565. bool ResourcerInfo::isSpilledWrite()
  1566. {
  1567. if (numInternalUses() == 0)
  1568. return true;
  1569. return false;
  1570. }
  1571. IHqlExpression * ResourcerInfo::wrapRowOwn(IHqlExpression * expr)
  1572. {
  1573. if (!original->isDataset())
  1574. expr = createRow(no_selectnth, expr, getSizetConstant(1));
  1575. return expr;
  1576. }
  1577. //---------------------------------------------------------------------------
  1578. EclResourcer::EclResourcer(IErrorReceiver * _errors, IConstWorkUnit * _wu, ClusterType _targetClusterType, unsigned _clusterSize, const HqlCppOptions & _translatorOptions)
  1579. {
  1580. wu.set(_wu);
  1581. errors = _errors;
  1582. lockTransformMutex();
  1583. targetClusterType = _targetClusterType;
  1584. clusterSize = _clusterSize ? _clusterSize : FIXED_CLUSTER_SIZE;
  1585. insideNeverSplit = false;
  1586. options.mangleSpillNameWithWuid = false;
  1587. options.minimizeSpillSize = _translatorOptions.minimizeSpillSize;
  1588. bool wuidIsConstant = (targetClusterType == RoxieCluster) || !wu->getCloneable();
  1589. if (wuidIsConstant)
  1590. {
  1591. SCMStringBuffer wuNameText;
  1592. wu->getWuid(wuNameText);
  1593. options.filenameMangler.set(wuNameText.str());
  1594. }
  1595. unsigned totalMemory = _translatorOptions.resourceMaxMemory ? _translatorOptions.resourceMaxMemory : DEFAULT_TOTAL_MEMORY;
  1596. unsigned maxSockets = _translatorOptions.resourceMaxSockets ? _translatorOptions.resourceMaxSockets : DEFAULT_MAX_SOCKETS;
  1597. unsigned maxActivities = _translatorOptions.resourceMaxActivities ? _translatorOptions.resourceMaxActivities : DEFAULT_MAX_ACTIVITIES;
  1598. unsigned maxHeavy = _translatorOptions.resourceMaxHeavy;
  1599. unsigned maxDistribute = _translatorOptions.resourceMaxDistribute;
  1600. resourceLimit = new CResources(0);
  1601. resourceLimit->set(RESactivities, maxActivities);
  1602. switch (targetClusterType)
  1603. {
  1604. case ThorCluster:
  1605. case ThorLCRCluster:
  1606. resourceLimit->set(RESheavy, maxHeavy).set(REShashdist, maxDistribute);
  1607. resourceLimit->set(RESmastersocket, maxSockets).set(RESslavememory,totalMemory);
  1608. resourceLimit->set(RESslavesocket, maxSockets).set(RESmastermemory, totalMemory);
  1609. break;
  1610. default:
  1611. resourceLimit->set(RESheavy, 0xffffffff).set(REShashdist, 0xffffffff);
  1612. resourceLimit->set(RESmastersocket, 0xffffffff).set(RESslavememory, 0xffffffff);
  1613. resourceLimit->set(RESslavesocket, 0xffffffff).set(RESmastermemory, 0xffffffff);
  1614. clusterSize = 1;
  1615. break;
  1616. }
  1617. if (_translatorOptions.unlimitedResources)
  1618. {
  1619. resourceLimit->set(RESheavy, 0xffffffff).set(REShashdist, 0xffffffff);
  1620. resourceLimit->set(RESmastersocket, 0xffffffff).set(RESslavememory,0xffffffff);
  1621. resourceLimit->set(RESslavesocket, 0xffffffff).set(RESmastermemory,0xffffffff);
  1622. }
  1623. #ifdef MPHASHDISTRIBUTE
  1624. options.useMpForDistribute = true;
  1625. #else
  1626. options.useMpForDistribute = false;
  1627. #endif
  1628. if (_translatorOptions.hasResourceUseMpForDistribute)
  1629. options.useMpForDistribute = _translatorOptions.resourceUseMpForDistribute;
  1630. options.isChildQuery = false;
  1631. options.targetClusterType = targetClusterType;
  1632. options.filteredSpillThreshold = _translatorOptions.filteredReadSpillThreshold;
  1633. options.allowThroughSpill = _translatorOptions.allowThroughSpill;
  1634. options.allowThroughResult = (targetClusterType != RoxieCluster) && (targetClusterType != ThorLCRCluster);
  1635. options.cloneFilteredIndex = (targetClusterType != RoxieCluster);
  1636. options.spillSharedConditionals = (targetClusterType == RoxieCluster);
  1637. options.shareDontExpand = (targetClusterType == RoxieCluster);
  1638. options.graphIdExpr = NULL;
  1639. //MORE The following doesn't always work - it gets sometimes confused about spill files - see latestheaderbuild for an example.
  1640. //Try again once cloneConditionals is false for thor
  1641. options.minimiseSpills = _translatorOptions.minimiseSpills;
  1642. spillMultiCondition = _translatorOptions.spillMultiCondition;
  1643. spotThroughAggregate = _translatorOptions.spotThroughAggregate && (targetClusterType != RoxieCluster) && (targetClusterType != ThorLCRCluster);
  1644. options.noConditionalLinks = (targetClusterType == RoxieCluster);
  1645. options.hoistResourced = _translatorOptions.hoistResourced;
  1646. options.useGraphResults = false; // modified by later call
  1647. options.groupedChildIterators = _translatorOptions.groupedChildIterators;
  1648. options.allowSplitBetweenSubGraphs = false;//(targetClusterType == RoxieCluster);
  1649. options.supportsChildQueries = (targetClusterType != ThorCluster);
  1650. options.clusterSize = clusterSize;
  1651. options.preventKeyedSplit = _translatorOptions.preventKeyedSplit;
  1652. options.preventSteppedSplit = _translatorOptions.preventSteppedSplit;
  1653. options.minimizeSkewBeforeSpill = _translatorOptions.minimizeSkewBeforeSpill;
  1654. options.expandSingleConstRow = true;
  1655. options.createSpillAsDataset = _translatorOptions.optimizeSpillProject && (targetClusterType != HThorCluster);
  1656. options.useLinkedRawIterator = _translatorOptions.useLinkedRawIterator;
  1657. options.combineSiblings = _translatorOptions.combineSiblingGraphs && (targetClusterType != HThorCluster) && (targetClusterType != RoxieCluster);
  1658. options.optimizeSharedInputs = _translatorOptions.optimizeSharedGraphInputs && options.combineSiblings;
  1659. }
  1660. EclResourcer::~EclResourcer()
  1661. {
  1662. delete resourceLimit;
  1663. unlockTransformMutex();
  1664. }
  1665. void EclResourcer::setChildQuery(bool value)
  1666. {
  1667. options.isChildQuery = value;
  1668. if (value)
  1669. options.createSpillAsDataset = false;
  1670. }
  1671. void EclResourcer::setNewChildQuery(IHqlExpression * graphIdExpr, unsigned numResults)
  1672. {
  1673. options.graphIdExpr = graphIdExpr;
  1674. options.nextResult = numResults;
  1675. }
  1676. void EclResourcer::changeGraph(IHqlExpression * expr, ResourceGraphInfo * newGraph)
  1677. {
  1678. ResourcerInfo * info = queryResourceInfo(expr);
  1679. info->graph.set(newGraph);
  1680. ForEachItemInRev(idx, links)
  1681. {
  1682. ResourceGraphLink & cur = links.item(idx);
  1683. if (cur.sourceNode == expr)
  1684. cur.changeSourceGraph(newGraph);
  1685. else if (cur.sinkNode == expr)
  1686. cur.changeSinkGraph(newGraph);
  1687. assertex(cur.sinkGraph != cur.sourceGraph);
  1688. }
  1689. }
  1690. ResourceGraphInfo * EclResourcer::createGraph()
  1691. {
  1692. ResourceGraphInfo * graph = new ResourceGraphInfo(&options);
  1693. graphs.append(*LINK(graph));
  1694. //PrintLog("Create graph %p", graph);
  1695. return graph;
  1696. }
  1697. void EclResourcer::connectGraphs(ResourceGraphInfo * sourceGraph, IHqlExpression * sourceNode, ResourceGraphInfo * sinkGraph, IHqlExpression * sinkNode, LinkKind kind)
  1698. {
  1699. ResourceGraphLink * link = new ResourceGraphLink(sourceGraph, sourceNode, sinkGraph, sinkNode, kind);
  1700. links.append(*link);
  1701. if (sourceGraph)
  1702. sourceGraph->sinks.append(*link);
  1703. if (sinkGraph)
  1704. sinkGraph->sources.append(*link);
  1705. }
  1706. ResourcerInfo * EclResourcer::queryCreateResourceInfo(IHqlExpression * expr)
  1707. {
  1708. IHqlExpression * body = expr->queryBody();
  1709. ResourcerInfo * info = (ResourcerInfo *)body->queryTransformExtra();
  1710. if (!info)
  1711. {
  1712. info = new ResourcerInfo(expr, &options);
  1713. body->setTransformExtraOwned(info);
  1714. }
  1715. return info;
  1716. }
  1717. void EclResourcer::replaceGraphReferences(IHqlExpression * expr, ResourceGraphInfo * oldGraph, ResourceGraphInfo * newGraph)
  1718. {
  1719. ResourcerInfo * info = queryResourceInfo(expr);
  1720. if (!info || !info->containsActivity)
  1721. return;
  1722. if (info->isActivity && info->graph != oldGraph)
  1723. return;
  1724. info->graph.set(newGraph);
  1725. unsigned first = getFirstActivityArgument(expr);
  1726. unsigned last = first + getNumActivityArguments(expr);
  1727. for (unsigned idx=first; idx < last; idx++)
  1728. replaceGraphReferences(expr->queryChild(idx), oldGraph, newGraph);
  1729. }
  1730. void EclResourcer::removeLink(ResourceGraphLink & link, bool keepExternalUses)
  1731. {
  1732. ResourcerInfo * info = (ResourcerInfo *)queryResourceInfo(link.sourceNode);
  1733. assertex(info && info->numExternalUses > 0);
  1734. if (!keepExternalUses)
  1735. info->numExternalUses--;
  1736. if (link.sinkGraph)
  1737. link.sinkGraph->sources.zap(link);
  1738. link.sourceGraph->sinks.zap(link);
  1739. links.zap(link);
  1740. }
  1741. void EclResourcer::replaceGraphReferences(ResourceGraphInfo * oldGraph, ResourceGraphInfo * newGraph)
  1742. {
  1743. ForEachItemIn(idx1, oldGraph->sinks)
  1744. {
  1745. ResourceGraphLink & sink = oldGraph->sinks.item(idx1);
  1746. replaceGraphReferences(sink.sourceNode, oldGraph, newGraph);
  1747. }
  1748. ForEachItemInRev(idx2, links)
  1749. {
  1750. ResourceGraphLink & cur = links.item(idx2);
  1751. if (cur.sourceGraph == oldGraph)
  1752. {
  1753. if (cur.sinkGraph == newGraph)
  1754. removeLink(cur, false);
  1755. else
  1756. cur.changeSourceGraph(newGraph);
  1757. }
  1758. else if (cur.sinkGraph == oldGraph)
  1759. {
  1760. if (cur.sourceGraph == newGraph)
  1761. removeLink(cur, false);
  1762. else
  1763. cur.changeSinkGraph(newGraph);
  1764. }
  1765. }
  1766. ForEachItemIn(idx3, graphs)
  1767. graphs.item(idx3).replaceReferences(oldGraph, newGraph);
  1768. }
  1769. //------------------------------------------------------------------------------------------
  1770. // PASS1: Gather information about splitter locations..
  1771. void EclResourcer::tagActiveCursors(HqlExprCopyArray & activeRows)
  1772. {
  1773. ForEachItemIn(i, activeRows)
  1774. {
  1775. IHqlExpression & cur = activeRows.item(i);
  1776. activeSelectors.append(cur);
  1777. queryCreateResourceInfo(&cur)->isAlreadyInScope = true;
  1778. }
  1779. }
  1780. inline bool projectSelectorDatasetToField(IHqlExpression * row)
  1781. {
  1782. return ((row->getOperator() == no_selectnth) && getFieldCount(row->queryRecord()) > 1);
  1783. }
  1784. static HqlTransformerInfo eclHoistLocatorInfo("EclHoistLocator");
  1785. class EclHoistLocator : public NewHqlTransformer
  1786. {
  1787. public:
  1788. EclHoistLocator(HqlExprCopyArray & _originalMatches, HqlExprArray & _matches, BoolArray & _alwaysHoistMatches)
  1789. : NewHqlTransformer(eclHoistLocatorInfo), originalMatched(_originalMatches), matched(_matches), alwaysHoistMatches(_alwaysHoistMatches)
  1790. {
  1791. }
  1792. void noteDataset(IHqlExpression * expr, IHqlExpression * hoisted, bool alwaysHoist)
  1793. {
  1794. unsigned match = originalMatched.find(*expr);
  1795. if (match == NotFound)
  1796. {
  1797. if (!hoisted)
  1798. hoisted = expr;
  1799. originalMatched.append(*expr);
  1800. matched.append(*LINK(hoisted));
  1801. alwaysHoistMatches.append(alwaysHoist);
  1802. }
  1803. else if (alwaysHoist && !alwaysHoistMatches.item(match))
  1804. alwaysHoistMatches.replace(true, match);
  1805. }
  1806. void noteScalar(IHqlExpression * expr, IHqlExpression * value)
  1807. {
  1808. if (!originalMatched.contains(*expr))
  1809. {
  1810. OwnedHqlExpr hoisted;
  1811. if (value->getOperator() == no_select)
  1812. {
  1813. bool isNew;
  1814. IHqlExpression * row = querySelectorDataset(value, isNew);
  1815. if(isNew || row->isDatarow())
  1816. {
  1817. if (projectSelectorDatasetToField(row))
  1818. {
  1819. IHqlExpression * ds = row->queryChild(0);
  1820. //Project down to a single field.so implicit fields can still be optimized
  1821. IHqlExpression * field = value->queryChild(1);
  1822. OwnedHqlExpr record = createRecord(field);
  1823. OwnedHqlExpr self = getSelf(record);
  1824. OwnedHqlExpr activeDs = createRow(no_activetable, LINK(ds->queryNormalizedSelector()));
  1825. OwnedHqlExpr selected = replaceSelector(value, row, activeDs);
  1826. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), selected.getClear());
  1827. OwnedHqlExpr transform = createValue(no_newtransform, makeTransformType(record->getType()), LINK(assign));
  1828. OwnedHqlExpr projectedDs = createDataset(no_newusertable, LINK(ds), createComma(LINK(record), LINK(transform)));
  1829. hoisted.setown(replaceChild(row, 0, projectedDs));
  1830. }
  1831. if (!hoisted)
  1832. hoisted.set(row);
  1833. }
  1834. }
  1835. else if (value->getOperator() == no_createset)
  1836. {
  1837. IHqlExpression * ds = value->queryChild(0);
  1838. IHqlExpression * selected = value->queryChild(1);
  1839. OwnedHqlExpr field;
  1840. //Project down to a single field.so implicit fields can still be optimized
  1841. if (selected->getOperator() == no_select)
  1842. field.set(selected->queryChild(1));
  1843. else
  1844. field.setown(createField(valueAtom, selected->getType(), NULL));
  1845. OwnedHqlExpr record = createRecord(field);
  1846. OwnedHqlExpr self = getSelf(record);
  1847. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), LINK(selected));
  1848. OwnedHqlExpr transform = createValue(no_newtransform, makeTransformType(record->getType()), LINK(assign));
  1849. hoisted.setown(createDataset(no_newusertable, LINK(ds), createComma(LINK(record), LINK(transform))));
  1850. }
  1851. if (!hoisted)
  1852. {
  1853. OwnedHqlExpr field = createField(valueAtom, value->getType(), NULL);
  1854. OwnedHqlExpr record = createRecord(field);
  1855. OwnedHqlExpr self = getSelf(record);
  1856. OwnedHqlExpr assign = createAssign(createSelectExpr(LINK(self), LINK(field)), LINK(value));
  1857. OwnedHqlExpr transform = createValue(no_transform, makeTransformType(record->getType()), LINK(assign));
  1858. hoisted.setown(createRow(no_createrow, LINK(transform)));
  1859. }
  1860. originalMatched.append(*expr);
  1861. matched.append(*hoisted.getClear());
  1862. alwaysHoistMatches.append(true);
  1863. }
  1864. }
  1865. protected:
  1866. HqlExprCopyArray & originalMatched;
  1867. HqlExprArray & matched;
  1868. BoolArray & alwaysHoistMatches;
  1869. };
  1870. class EclChildSplitPointLocator : public EclHoistLocator
  1871. {
  1872. public:
  1873. EclChildSplitPointLocator(IHqlExpression * _original, HqlExprCopyArray & _selectors, HqlExprCopyArray & _originalMatches, HqlExprArray & _matches, BoolArray & _alwaysHoistMatches, bool _groupedChildIterators, bool _supportsChildQueries)
  1874. : EclHoistLocator(_originalMatches, _matches, _alwaysHoistMatches), selectors(_selectors), groupedChildIterators(_groupedChildIterators), supportsChildQueries(_supportsChildQueries)
  1875. {
  1876. original = _original;
  1877. okToSelect = false;
  1878. gathered = false;
  1879. conditionalDepth = 0;
  1880. executedOnce = false;
  1881. switch (original->getOperator())
  1882. {
  1883. case no_call:
  1884. case no_externalcall:
  1885. case no_libraryscopeinstance:
  1886. okToSelect = true;
  1887. break;
  1888. }
  1889. }
  1890. void findSplitPoints(IHqlExpression * expr, unsigned from, unsigned to, bool _executedOnce)
  1891. {
  1892. for (unsigned i=from; i < to; i++)
  1893. {
  1894. IHqlExpression * cur = expr->queryChild(i);
  1895. executedOnce = _executedOnce || cur->isAttribute(); // assume attributes are only executed once.
  1896. findSplitPoints(cur);
  1897. }
  1898. }
  1899. protected:
  1900. void findSplitPoints(IHqlExpression * expr)
  1901. {
  1902. //containsNonActiveDataset() would be nice - but that isn't percolated outside assigns etc.
  1903. if (containsAnyDataset(expr) || containsMustHoist(expr))
  1904. {
  1905. if (!gathered)
  1906. {
  1907. gatherAmbiguousSelectors(original);
  1908. gathered = true;
  1909. }
  1910. analyse(expr, 0);
  1911. }
  1912. }
  1913. bool queryHoistDataset(IHqlExpression * ds)
  1914. {
  1915. bool alwaysHoist = true;
  1916. if (executedOnce)
  1917. {
  1918. if (conditionalDepth != 0)
  1919. {
  1920. if (supportsChildQueries || canProcessInline(NULL, ds))
  1921. alwaysHoist = false;
  1922. }
  1923. }
  1924. return alwaysHoist;
  1925. }
  1926. bool queryNoteDataset(IHqlExpression * ds)
  1927. {
  1928. bool alwaysHoist = queryHoistDataset(ds);
  1929. //MORE: It should be possible to remove this condition, but it causes problems with resourcing hsss.xhql amongst others -> disable for the moment
  1930. if (alwaysHoist)
  1931. noteDataset(ds, ds, alwaysHoist);
  1932. return alwaysHoist;
  1933. }
  1934. virtual void analyseExpr(IHqlExpression * expr)
  1935. {
  1936. if (alreadyVisited(expr))
  1937. return;
  1938. node_operator op = expr->getOperator();
  1939. switch (op)
  1940. {
  1941. case no_select:
  1942. if (expr->hasProperty(newAtom))
  1943. {
  1944. IHqlExpression * ds = expr->queryChild(0);
  1945. if (isEvaluateable(ds))
  1946. {
  1947. //MORE: Following isn't a very nice test - stops implicit denormalize getting messed up
  1948. if (expr->isDataset())
  1949. break;
  1950. //Debtable.....
  1951. //Don't hoist counts on indexes or dataset - it may mean they are evaluated more frequently than need be.
  1952. //If dependencies and root graphs are handled correctly this could be deleted.
  1953. if (isCompoundAggregate(ds))
  1954. break;
  1955. if (!expr->isDatarow() && !expr->isDataset())
  1956. {
  1957. if (queryHoistDataset(ds))
  1958. {
  1959. noteScalar(expr, expr);
  1960. return;
  1961. }
  1962. }
  1963. else
  1964. {
  1965. if (queryNoteDataset(ds))
  1966. return;
  1967. }
  1968. }
  1969. }
  1970. break;
  1971. case no_createset:
  1972. {
  1973. IHqlExpression * ds = expr->queryChild(0);
  1974. if (isEvaluateable(ds))
  1975. {
  1976. if (queryHoistDataset(ds))
  1977. {
  1978. noteScalar(expr, expr);
  1979. //?? queryNoteDataset(ds);
  1980. return;
  1981. }
  1982. }
  1983. break;
  1984. }
  1985. case no_assign:
  1986. {
  1987. IHqlExpression * rhs = expr->queryChild(1);
  1988. //if rhs is a new, evaluatable, dataset then we want to add it
  1989. if (rhs->isDataset() && isEvaluateable(rhs))
  1990. {
  1991. if (queryNoteDataset(rhs))
  1992. return;
  1993. }
  1994. break;
  1995. }
  1996. case no_sizeof:
  1997. case no_allnodes:
  1998. case no_nohoist:
  1999. return;
  2000. case no_globalscope:
  2001. case no_evalonce:
  2002. if (expr->isDataset() || expr->isDatarow())
  2003. noteDataset(expr, expr->queryChild(0), true);
  2004. else
  2005. noteScalar(expr, expr->queryChild(0));
  2006. return;
  2007. case no_thisnode:
  2008. throwUnexpected();
  2009. case no_getgraphresult:
  2010. if (expr->hasProperty(_streaming_Atom) || expr->hasProperty(_distributed_Atom))
  2011. {
  2012. noteDataset(expr, expr, true);
  2013. return;
  2014. }
  2015. break;
  2016. case no_getgraphloopresult:
  2017. noteDataset(expr, expr, true);
  2018. return;
  2019. case no_selectnth:
  2020. if (expr->queryChild(1)->isConstant())
  2021. {
  2022. IHqlExpression * ds = expr->queryChild(0);
  2023. switch (ds->getOperator())
  2024. {
  2025. case no_getgraphresult:
  2026. if (!expr->hasProperty(_streaming_Atom) && !expr->hasProperty(_distributed_Atom))
  2027. break;
  2028. //fallthrough
  2029. case no_getgraphloopresult:
  2030. noteDataset(expr, expr, true);
  2031. return;
  2032. }
  2033. }
  2034. break;
  2035. }
  2036. bool wasOkToSelect = okToSelect;
  2037. if (expr->isDataset())
  2038. {
  2039. switch (expr->getOperator())
  2040. {
  2041. case no_compound_diskread:
  2042. case no_compound_disknormalize:
  2043. case no_compound_diskaggregate:
  2044. case no_compound_diskcount:
  2045. case no_compound_diskgroupaggregate:
  2046. case no_compound_indexread:
  2047. case no_compound_indexnormalize:
  2048. case no_compound_indexaggregate:
  2049. case no_compound_indexcount:
  2050. case no_compound_indexgroupaggregate:
  2051. case no_compound_childread:
  2052. case no_compound_childnormalize:
  2053. case no_compound_childaggregate:
  2054. case no_compound_childcount:
  2055. case no_compound_childgroupaggregate:
  2056. case no_compound_selectnew:
  2057. case no_compound_inline:
  2058. case no_newkeyindex:
  2059. case no_keyindex:
  2060. case no_table:
  2061. okToSelect = false;
  2062. break;
  2063. }
  2064. if (okToSelect && isEvaluateable(expr))
  2065. {
  2066. if (queryNoteDataset(expr))
  2067. return;
  2068. }
  2069. }
  2070. else
  2071. okToSelect = true;
  2072. switch (op)
  2073. {
  2074. case no_if:
  2075. {
  2076. IHqlExpression * cond = expr->queryChild(0);
  2077. // bool condCanBeEvaluated = isEvaluateable(cond, true);
  2078. analyseExpr(cond);
  2079. if (expr->isDataset() || expr->isDatarow())
  2080. conditionalDepth++;
  2081. doAnalyseChildren(expr, 1);
  2082. if (expr->isDataset() || expr->isDatarow())
  2083. conditionalDepth--;
  2084. break;
  2085. }
  2086. case no_mapto:
  2087. {
  2088. analyseExpr(expr->queryChild(0));
  2089. if (expr->isDataset() || expr->isDatarow())
  2090. conditionalDepth++;
  2091. analyseExpr(expr->queryChild(1));
  2092. if (expr->isDataset() || expr->isDatarow())
  2093. conditionalDepth--;
  2094. break;
  2095. }
  2096. default:
  2097. NewHqlTransformer::analyseExpr(expr);
  2098. break;
  2099. }
  2100. okToSelect = wasOkToSelect;
  2101. }
  2102. bool isCompoundAggregate(IHqlExpression * ds)
  2103. {
  2104. return false;
  2105. //Generates worse code unless we take into account whether or not the newDisk operation flags are enabled.
  2106. if (!isTrivialSelectN(ds))
  2107. return false;
  2108. IHqlExpression * agg = ds->queryChild(0);
  2109. if (isSimpleCountAggregate(agg, true))
  2110. return true;
  2111. return false;
  2112. }
  2113. void gatherAmbiguousSelectors(IHqlExpression * expr)
  2114. {
  2115. #ifndef ENSURE_SELSEQ_UID
  2116. //Horrible code to try and cope with ambiguous left selectors.
  2117. //o Tree is ambiguous so same child expression can occur in different contexts - so can't depend on the context it is found in to work out if can hoist
  2118. //o If any selector that is hidden within child expressions matches one in scope then can't hoist it.
  2119. //If the current expression creates a selector, then can't hoist anything that depends on it [only add to hidden if in selectors to reduce searching]
  2120. //o Want to hoist as much as possible.
  2121. if (selectors.empty())
  2122. return;
  2123. unsigned first = getFirstActivityArgument(expr);
  2124. unsigned last = first + getNumActivityArguments(expr);
  2125. unsigned max = expr->numChildren();
  2126. unsigned i;
  2127. HqlExprCopyArray hiddenSelectors;
  2128. for (i = 0; i < first; i++)
  2129. expr->queryChild(i)->gatherTablesUsed(&hiddenSelectors, NULL);
  2130. for (i = last; i < max; i++)
  2131. expr->queryChild(i)->gatherTablesUsed(&hiddenSelectors, NULL);
  2132. ForEachItemIn(iSel, selectors)
  2133. {
  2134. IHqlExpression & cur = selectors.item(iSel);
  2135. if (hiddenSelectors.contains(cur))
  2136. ambiguousSelectors.append(cur);
  2137. }
  2138. switch (getChildDatasetType(expr))
  2139. {
  2140. case childdataset_datasetleft:
  2141. case childdataset_left:
  2142. {
  2143. IHqlExpression * ds = expr->queryChild(0);
  2144. IHqlExpression * selSeq = querySelSeq(expr);
  2145. OwnedHqlExpr left = createSelector(no_left, ds, selSeq);
  2146. if (selectors.contains(*left))
  2147. ambiguousSelectors.append(*left);
  2148. break;
  2149. }
  2150. case childdataset_same_left_right:
  2151. case childdataset_top_left_right:
  2152. case childdataset_nway_left_right:
  2153. {
  2154. IHqlExpression * ds = expr->queryChild(0);
  2155. IHqlExpression * selSeq = querySelSeq(expr);
  2156. OwnedHqlExpr left = createSelector(no_left, ds, selSeq);
  2157. OwnedHqlExpr right = createSelector(no_right, ds, selSeq);
  2158. if (selectors.contains(*left))
  2159. ambiguousSelectors.append(*left);
  2160. if (selectors.contains(*right))
  2161. ambiguousSelectors.append(*right);
  2162. break;
  2163. }
  2164. case childdataset_leftright:
  2165. {
  2166. IHqlExpression * leftDs = expr->queryChild(0);
  2167. IHqlExpression * rightDs = expr->queryChild(1);
  2168. IHqlExpression * selSeq = querySelSeq(expr);
  2169. OwnedHqlExpr left = createSelector(no_left, leftDs, selSeq);
  2170. OwnedHqlExpr right = createSelector(no_right, rightDs, selSeq);
  2171. if (selectors.contains(*left))
  2172. ambiguousSelectors.append(*left);
  2173. if (selectors.contains(*right))
  2174. ambiguousSelectors.append(*right);
  2175. break;
  2176. }
  2177. }
  2178. #endif
  2179. }
  2180. bool isEvaluateable(IHqlExpression * ds, bool ignoreInline = false)
  2181. {
  2182. //Don't hoist an alias - it could create unnecessary duplicate spills - hoist its input
  2183. if (ds->getOperator() == no_dataset_alias)
  2184. return false;
  2185. //Not allowed to hoist
  2186. if (isContextDependent(ds, (conditionalDepth == 0), true))
  2187. return false;
  2188. //MORE: Needs more work for child queries - need a GroupedChildIterator activity
  2189. if (isGrouped(ds) && selectors.ordinality() && !groupedChildIterators)
  2190. return false;
  2191. //Check datasets are available
  2192. HqlExprCopyArray scopeUsed;
  2193. ds->gatherTablesUsed(NULL, &scopeUsed);
  2194. ForEachItemIn(i, scopeUsed)
  2195. {
  2196. IHqlExpression & cur = scopeUsed.item(i);
  2197. if (!selectors.contains(cur))
  2198. return false;
  2199. if (ambiguousSelectors.contains(cur))
  2200. return false;
  2201. }
  2202. #ifdef MINIMAL_CHANGES
  2203. if (isInlineTrivialDataset(ds) || (!ignoreInline && canProcessInline(NULL, ds)))
  2204. // if (isInlineTrivialDataset(ds))// || (!ignoreInline && canProcessInline(NULL, ds)))
  2205. return false;
  2206. #else
  2207. //Not worth hoisting...
  2208. if (isTrivialDataset(ds))
  2209. return false;
  2210. #endif
  2211. return true;
  2212. }
  2213. protected:
  2214. IHqlExpression * original;
  2215. HqlExprCopyArray & selectors;
  2216. HqlExprCopyArray ambiguousSelectors;
  2217. unsigned conditionalDepth;
  2218. bool okToSelect;
  2219. bool gathered;
  2220. bool groupedChildIterators;
  2221. bool executedOnce;
  2222. bool supportsChildQueries;
  2223. };
  2224. void EclResourcer::gatherChildSplitPoints(IHqlExpression * expr, BoolArray & alwaysHoistChild, ResourcerInfo * info, unsigned first, unsigned last)
  2225. {
  2226. //NB: Don't call member functions to ensure correct nesting of transform mutexes.
  2227. EclChildSplitPointLocator locator(expr, activeSelectors, info->originalChildDependents, info->childDependents, alwaysHoistChild, options.groupedChildIterators, options.supportsChildQueries);
  2228. unsigned max = expr->numChildren();
  2229. //If child queries are supported then don't hoist the expressions if they might only be evaluated once
  2230. //because they may be conditional
  2231. switch (expr->getOperator())
  2232. {
  2233. case no_setresult:
  2234. case no_selectnth:
  2235. //set results, only done once=>don't hoist conditionals
  2236. locator.findSplitPoints(expr, last, max, true);
  2237. return;
  2238. }
  2239. locator.findSplitPoints(expr, 0, first, true); // IF() conditions only evaluated once... => don't force
  2240. locator.findSplitPoints(expr, last, max, false);
  2241. }
  2242. class EclThisNodeLocator : public EclHoistLocator
  2243. {
  2244. public:
  2245. EclThisNodeLocator(HqlExprCopyArray & _originalMatches, HqlExprArray & _matches, BoolArray & _alwaysHoistMatches) : EclHoistLocator(_originalMatches, _matches, _alwaysHoistMatches)
  2246. {
  2247. allNodesDepth = 0;
  2248. }
  2249. protected:
  2250. virtual void analyseExpr(IHqlExpression * expr)
  2251. {
  2252. //NB: This doesn't really work for no_thisnode occurring in multiple contexts. We should probably hoist it from everywhere if it is hoistable from anywhere,
  2253. // although theoretically that gives us problems with ambiguous selectors.
  2254. if (alreadyVisited(expr) || !containsThisNode(expr))
  2255. return;
  2256. node_operator op = expr->getOperator();
  2257. switch (op)
  2258. {
  2259. case no_allnodes:
  2260. allNodesDepth++;
  2261. NewHqlTransformer::analyseExpr(expr);
  2262. allNodesDepth--;
  2263. return;
  2264. case no_thisnode:
  2265. if (allNodesDepth == 0)
  2266. {
  2267. if (expr->isDataset() || expr->isDatarow())
  2268. noteDataset(expr, expr->queryChild(0), true);
  2269. else
  2270. noteScalar(expr, expr->queryChild(0));
  2271. return;
  2272. }
  2273. allNodesDepth--;
  2274. NewHqlTransformer::analyseExpr(expr);
  2275. allNodesDepth++;
  2276. return;
  2277. }
  2278. NewHqlTransformer::analyseExpr(expr);
  2279. }
  2280. protected:
  2281. unsigned allNodesDepth;
  2282. };
  2283. bool EclResourcer::findSplitPoints(IHqlExpression * expr)
  2284. {
  2285. ResourcerInfo * info = queryResourceInfo(expr);
  2286. bool savedInsideNeverSplit = insideNeverSplit;
  2287. if (info && info->numUses)
  2288. {
  2289. if (insideNeverSplit)
  2290. info->neverSplit = true;
  2291. if (info->isAlreadyInScope && (info->numUses == 0) && expr->isDatarow())
  2292. {
  2293. // A row is already bound to a temporary
  2294. info->isActivity = true;
  2295. info->containsActivity = true;
  2296. info->numUses++;
  2297. //More: May need to force child activities to not be resourced (e.g., if somehow visited via another path)
  2298. //info->preserve = true;
  2299. return info->containsActivity;
  2300. }
  2301. if (info->isAlreadyInScope || info->isActivity || !info->containsActivity)
  2302. {
  2303. info->numUses++;
  2304. return info->containsActivity;
  2305. }
  2306. }
  2307. else
  2308. {
  2309. info = queryCreateResourceInfo(expr);
  2310. info->numUses++;
  2311. if (insideNeverSplit)
  2312. info->neverSplit = true;
  2313. bool isActivity = true;
  2314. switch (expr->getOperator())
  2315. {
  2316. case no_select:
  2317. //either a select from a setresult or use of a child-dataset
  2318. if (expr->hasProperty(newAtom))
  2319. {
  2320. info->containsActivity = findSplitPoints(expr->queryChild(0));
  2321. assertex(queryResourceInfo(expr->queryChild(0))->isActivity);
  2322. }
  2323. if (expr->isDataset() || expr->isDatarow())
  2324. {
  2325. info->isActivity = true;
  2326. info->containsActivity = true;
  2327. }
  2328. return info->containsActivity;
  2329. case no_mapto:
  2330. throwUnexpected();
  2331. info->containsActivity = findSplitPoints(expr->queryChild(1));
  2332. return info->containsActivity;
  2333. case no_activerow:
  2334. info->isActivity = true;
  2335. info->containsActivity = false;
  2336. return false;
  2337. case no_attr:
  2338. case no_attr_expr:
  2339. case no_attr_link:
  2340. case no_rowset: // don't resource this as an activity
  2341. case no_getgraphloopresultset:
  2342. info->isActivity = false;
  2343. info->containsActivity = false;
  2344. return false;
  2345. case no_datasetlist:
  2346. isActivity = false;
  2347. break;
  2348. case no_rowsetrange:
  2349. {
  2350. //Don't resource this as an activity if it is a function of the input graph rows,
  2351. //however we do want to if it is coming from a dataset list.
  2352. IHqlExpression * ds = expr->queryChild(0);
  2353. //MORE: Should walk further down the tree to allow for nested rowsetranges etc.
  2354. if (ds->getOperator() == no_rowset || ds->getOperator() == no_getgraphloopresultset)
  2355. {
  2356. info->isActivity = false;
  2357. info->containsActivity = false;
  2358. return false;
  2359. }
  2360. isActivity = false;
  2361. break;
  2362. }
  2363. case no_keyedlimit:
  2364. if (options.preventKeyedSplit)
  2365. insideNeverSplit = true;
  2366. break;
  2367. case no_filter:
  2368. if (options.preventKeyedSplit && filterIsKeyed(expr))
  2369. insideNeverSplit = true;
  2370. break;
  2371. case no_hqlproject:
  2372. case no_newusertable:
  2373. case no_aggregate:
  2374. case no_newaggregate:
  2375. if (options.preventKeyedSplit && expr->hasProperty(keyedAtom))
  2376. insideNeverSplit = true;
  2377. break;
  2378. case no_stepped:
  2379. case no_mergejoin:
  2380. case no_nwayjoin:
  2381. if (options.preventSteppedSplit)
  2382. insideNeverSplit = true;
  2383. break;
  2384. case no_compound_diskread:
  2385. case no_compound_disknormalize:
  2386. case no_compound_diskaggregate:
  2387. case no_compound_diskcount:
  2388. case no_compound_diskgroupaggregate:
  2389. case no_compound_indexread:
  2390. case no_compound_indexnormalize:
  2391. case no_compound_indexaggregate:
  2392. case no_compound_indexcount:
  2393. case no_compound_indexgroupaggregate:
  2394. case no_compound_childread:
  2395. case no_compound_childnormalize:
  2396. case no_compound_childaggregate:
  2397. case no_compound_childcount:
  2398. case no_compound_childgroupaggregate:
  2399. case no_compound_selectnew:
  2400. case no_compound_inline:
  2401. insideNeverSplit = true;
  2402. break;
  2403. }
  2404. ITypeInfo * type = expr->queryType();
  2405. if (!type || type->isScalar())
  2406. {
  2407. insideNeverSplit = savedInsideNeverSplit;
  2408. return false;
  2409. }
  2410. info->isActivity = isActivity;
  2411. info->containsActivity = true;
  2412. }
  2413. unsigned first = getFirstActivityArgument(expr);
  2414. unsigned last = first + getNumActivityArguments(expr);
  2415. if (options.hoistResourced)
  2416. {
  2417. BoolArray alwaysHoistChild;
  2418. switch (expr->getOperator())
  2419. {
  2420. case no_allnodes:
  2421. {
  2422. //MORE: This needs to recursively walk and lift any contained no_selfnode, but don't go past another nested no_allnodes;
  2423. EclThisNodeLocator locator(info->originalChildDependents, info->childDependents, alwaysHoistChild);
  2424. locator.analyse(expr->queryChild(0), 0);
  2425. break;
  2426. }
  2427. default:
  2428. {
  2429. for (unsigned idx=first; idx < last; idx++)
  2430. {
  2431. IHqlExpression * cur = expr->queryChild(idx);
  2432. findSplitPoints(cur);
  2433. }
  2434. insideNeverSplit = savedInsideNeverSplit;
  2435. gatherChildSplitPoints(expr, alwaysHoistChild, info, first, last);
  2436. break;
  2437. }
  2438. }
  2439. insideNeverSplit = false;
  2440. ForEachItemIn(i2, info->childDependents)
  2441. {
  2442. IHqlExpression & cur = info->childDependents.item(i2);
  2443. if (alwaysHoistChild.item(i2))
  2444. findSplitPoints(&cur);
  2445. else
  2446. conditionalChildren.append(cur);
  2447. }
  2448. }
  2449. else
  2450. {
  2451. for (unsigned idx=first; idx < last; idx++)
  2452. findSplitPoints(expr->queryChild(idx));
  2453. }
  2454. insideNeverSplit = savedInsideNeverSplit;
  2455. return info->containsActivity;
  2456. }
  2457. void EclResourcer::findSplitPoints(HqlExprArray & exprs)
  2458. {
  2459. ForEachItemIn(idx, exprs)
  2460. findSplitPoints(&exprs.item(idx));
  2461. extendSplitPoints();
  2462. }
  2463. void EclResourcer::extendSplitPoints()
  2464. {
  2465. for (unsigned i=0; i < conditionalChildren.ordinality(); i++)
  2466. {
  2467. IHqlExpression & cur = conditionalChildren.item(i);
  2468. if (isWorthForcingHoist(&cur))
  2469. findSplitPoints(&cur);
  2470. }
  2471. }
  2472. //------------------------------------------------------------------------------------------
  2473. // PASS2: Actually create the subgraphs based on splitters.
  2474. void EclResourcer::createInitialGraph(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerGraph, LinkKind linkKind, bool forceNewGraph)
  2475. {
  2476. ResourcerInfo * info = queryResourceInfo(expr);
  2477. if (!info || !info->containsActivity)
  2478. return;
  2479. LinkKind childLinkKind = UnconditionalLink;
  2480. Linked<ResourceGraphInfo> thisGraph = ownerGraph;
  2481. bool forceNewChildGraph = false;
  2482. if (info->isActivity)
  2483. {
  2484. //Need to ensure no_libraryselects are not separated from the no_libraryscopeinstance
  2485. //so ensure they are placed in the same graph.
  2486. node_operator op = expr->getOperator();
  2487. if (op == no_libraryselect)
  2488. {
  2489. ResourcerInfo * moduleInfo = queryResourceInfo(expr->queryChild(1));
  2490. if (!info->graph && moduleInfo->graph)
  2491. info->graph.set(moduleInfo->graph);
  2492. }
  2493. if (info->graph)
  2494. {
  2495. connectGraphs(info->graph, expr, ownerGraph, owner, linkKind);
  2496. info->numExternalUses++;
  2497. return;
  2498. }
  2499. unsigned numUses = info->numUses;
  2500. switch (op)
  2501. {
  2502. case no_libraryscopeinstance:
  2503. numUses = 1;
  2504. break;
  2505. case no_libraryselect:
  2506. forceNewGraph = true;
  2507. break;
  2508. }
  2509. if (!ownerGraph || numUses > 1 || (linkKind != UnconditionalLink) || forceNewGraph)
  2510. {
  2511. thisGraph.setown(createGraph());
  2512. connectGraphs(thisGraph, expr, ownerGraph, owner, linkKind);
  2513. info->numExternalUses++;
  2514. }
  2515. info->graph.set(thisGraph);
  2516. switch (expr->getOperator())
  2517. {
  2518. case no_compound:
  2519. //NB: First argument is forced into a separate graph
  2520. createInitialGraph(expr->queryChild(0), expr, NULL, UnconditionalLink, true);
  2521. createInitialGraph(expr->queryChild(1), expr, thisGraph, UnconditionalLink, false);
  2522. return;
  2523. case no_executewhen:
  2524. {
  2525. bool newGraph = expr->isAction() && (options.targetClusterType == HThorCluster);
  2526. createInitialGraph(expr->queryChild(0), expr, thisGraph, UnconditionalLink, newGraph);
  2527. createInitialGraph(expr->queryChild(1), expr, thisGraph, UnconditionalLink, true);
  2528. return;
  2529. }
  2530. case no_keyindex:
  2531. case no_newkeyindex:
  2532. return;
  2533. case no_parallel:
  2534. {
  2535. ForEachChild(i, expr)
  2536. createInitialGraph(expr->queryChild(i), expr, thisGraph, UnconditionalLink, true);
  2537. return;
  2538. }
  2539. case no_if:
  2540. //conditional nodes, the child branches are marked as conditional
  2541. childLinkKind = UnconditionalLink;
  2542. thisGraph->mergedConditionSource = true;
  2543. if (!options.noConditionalLinks || expr->isAction())
  2544. forceNewChildGraph = true;
  2545. break;
  2546. // case no_nonempty:
  2547. case no_sequential:
  2548. {
  2549. unsigned first = getFirstActivityArgument(expr);
  2550. unsigned last = first + getNumActivityArguments(expr);
  2551. createInitialGraph(expr->queryChild(first), expr, thisGraph, SequenceLink, true);
  2552. for (unsigned idx = first+1; idx < last; idx++)
  2553. createInitialGraph(expr->queryChild(idx), expr, thisGraph, SequenceLink, true);
  2554. return;
  2555. }
  2556. case no_case:
  2557. case no_map:
  2558. {
  2559. throwUnexpected();
  2560. }
  2561. case no_output:
  2562. {
  2563. //Tag the inputs to an output statement, so that if a spill was going to occur we read
  2564. //from the output file instead of spilling.
  2565. //Needs the grouping to be saved in the same way. Could cope with compressed matching, but not
  2566. //much point - since fairly unlikely.
  2567. IHqlExpression * filename = expr->queryChild(1);
  2568. if (filename && (filename->getOperator() == no_constant) && !expr->hasProperty(xmlAtom) && !expr->hasProperty(csvAtom))
  2569. {
  2570. IHqlExpression * dataset = expr->queryChild(0);
  2571. if (expr->hasProperty(groupedAtom) == (dataset->queryType()->queryGroupInfo() != NULL))
  2572. {
  2573. StringBuffer filenameText;
  2574. filename->queryValue()->getStringValue(filenameText);
  2575. ResourcerInfo * childInfo = queryResourceInfo(dataset);
  2576. if (!childInfo->linkedFromChild && !isUpdatedConditionally(expr))
  2577. childInfo->outputToUseForSpill = expr;
  2578. }
  2579. }
  2580. if (isUpdatedConditionally(expr))
  2581. thisGraph->mergedConditionSource = true;
  2582. break;
  2583. }
  2584. case no_buildindex:
  2585. if (isUpdatedConditionally(expr))
  2586. thisGraph->mergedConditionSource = true;
  2587. break;
  2588. }
  2589. }
  2590. unsigned first = getFirstActivityArgument(expr);
  2591. unsigned last = first + getNumActivityArguments(expr);
  2592. for (unsigned idx = first; idx < last; idx++)
  2593. createInitialGraph(expr->queryChild(idx), expr, thisGraph, childLinkKind, forceNewChildGraph);
  2594. ForEachItemIn(i2, info->childDependents)
  2595. {
  2596. IHqlExpression & cur = info->childDependents.item(i2);
  2597. if (isResourcedActivity(&cur))
  2598. createInitialGraph(&cur, expr, thisGraph, SequenceLink, true);
  2599. }
  2600. }
  2601. void EclResourcer::createInitialGraphs(HqlExprArray & exprs)
  2602. {
  2603. ForEachItemIn(idx, exprs)
  2604. createInitialGraph(&exprs.item(idx), NULL, NULL, UnconditionalLink, false);
  2605. }
  2606. void EclResourcer::createInitialRemoteGraph(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerGraph, bool forceNewGraph)
  2607. {
  2608. ResourcerInfo * info = queryResourceInfo(expr);
  2609. if (!info || !info->containsActivity)
  2610. return;
  2611. Linked<ResourceGraphInfo> thisGraph = ownerGraph;
  2612. if (info->isActivity)
  2613. {
  2614. if (info->graph)
  2615. {
  2616. connectGraphs(info->graph, expr, ownerGraph, owner, UnconditionalLink);
  2617. info->numExternalUses++;
  2618. return;
  2619. }
  2620. if (!ownerGraph || forceNewGraph)
  2621. {
  2622. thisGraph.setown(createGraph());
  2623. connectGraphs(thisGraph, expr, ownerGraph, owner, UnconditionalLink);
  2624. info->numExternalUses++;
  2625. }
  2626. info->graph.set(thisGraph);
  2627. switch (expr->getOperator())
  2628. {
  2629. case no_compound:
  2630. createInitialRemoteGraph(expr->queryChild(0), expr, NULL, true);
  2631. createInitialRemoteGraph(expr->queryChild(1), expr, thisGraph, false);
  2632. return;
  2633. case no_executewhen:
  2634. createInitialRemoteGraph(expr->queryChild(0), expr, thisGraph, false);
  2635. createInitialRemoteGraph(expr->queryChild(1), expr, thisGraph, true);
  2636. return;
  2637. }
  2638. }
  2639. unsigned first = getFirstActivityArgument(expr);
  2640. unsigned last = first + getNumActivityArguments(expr);
  2641. for (unsigned idx = first; idx < last; idx++)
  2642. createInitialRemoteGraph(expr->queryChild(idx), expr, thisGraph, false);
  2643. }
  2644. void EclResourcer::createInitialRemoteGraphs(HqlExprArray & exprs)
  2645. {
  2646. ForEachItemIn(idx, exprs)
  2647. createInitialRemoteGraph(&exprs.item(idx), NULL, NULL, false);
  2648. }
  2649. //------------------------------------------------------------------------------------------
  2650. // PASS3: Tag graphs/links that are conditional or unconditional
  2651. void EclResourcer::markChildDependentsAsUnconditional(ResourcerInfo * info, IHqlExpression * condition)
  2652. {
  2653. if (options.hoistResourced)
  2654. {
  2655. ForEachItemIn(i2, info->childDependents)
  2656. {
  2657. IHqlExpression & cur = info->childDependents.item(i2);
  2658. if (isResourcedActivity(&cur))
  2659. markAsUnconditional(&cur, NULL, condition);
  2660. }
  2661. }
  2662. }
  2663. void EclResourcer::markAsUnconditional(IHqlExpression * expr, ResourceGraphInfo * ownerGraph, IHqlExpression * condition)
  2664. {
  2665. ResourcerInfo * info = queryResourceInfo(expr);
  2666. if (!info || !info->containsActivity)
  2667. return;
  2668. if (!info->isActivity)
  2669. {
  2670. unsigned first = getFirstActivityArgument(expr);
  2671. unsigned last = first + getNumActivityArguments(expr);
  2672. for (unsigned idx=first; idx < last; idx++)
  2673. markAsUnconditional(expr->queryChild(idx), ownerGraph, condition);
  2674. return;
  2675. }
  2676. if (condition)
  2677. if (info->addCondition(condition))
  2678. condition = NULL;
  2679. if (info->pathToExpr == ResourcerInfo::PathUnconditional)
  2680. return;
  2681. if ((info->pathToExpr == ResourcerInfo::PathConditional) && condition)
  2682. {
  2683. if (targetClusterType == RoxieCluster)
  2684. {
  2685. if (spillMultiCondition)
  2686. {
  2687. if (info->graph != ownerGraph)
  2688. info->graph->isUnconditional = true;
  2689. }
  2690. return;
  2691. }
  2692. else
  2693. {
  2694. if (info->graph != ownerGraph)
  2695. return;
  2696. }
  2697. }
  2698. bool wasConditional = (info->pathToExpr == ResourcerInfo::PathConditional);
  2699. if (!condition)
  2700. {
  2701. info->pathToExpr = ResourcerInfo::PathUnconditional;
  2702. if (info->graph != ownerGraph)
  2703. info->graph->isUnconditional = true;
  2704. }
  2705. else
  2706. info->pathToExpr = ResourcerInfo::PathConditional;
  2707. node_operator op = expr->getOperator();
  2708. switch (op)
  2709. {
  2710. case no_if:
  2711. if (options.noConditionalLinks)
  2712. break;
  2713. if (condition)
  2714. markCondition(expr, condition, wasConditional);
  2715. else
  2716. {
  2717. //This list is processed in a second phase.
  2718. if (rootConditions.find(*expr) == NotFound)
  2719. rootConditions.append(*LINK(expr));
  2720. }
  2721. markChildDependentsAsUnconditional(info, condition);
  2722. return;
  2723. case no_sequential:
  2724. // case no_nonempty:
  2725. if (!options.isChildQuery)
  2726. {
  2727. unsigned first = getFirstActivityArgument(expr);
  2728. unsigned last = first + getNumActivityArguments(expr);
  2729. IHqlExpression * child0 = expr->queryChild(0);
  2730. markAsUnconditional(child0, info->graph, condition);
  2731. queryResourceInfo(child0)->graph->hasConditionSource = true; // force it to generate even if contains something very simple e.g., null action
  2732. for (unsigned idx = first+1; idx < last; idx++)
  2733. {
  2734. OwnedHqlExpr tag = createAttribute(instanceAtom, LINK(expr), getSizetConstant(idx), LINK(condition));
  2735. IHqlExpression * child = expr->queryChild(idx);
  2736. markAsUnconditional(child, queryResourceInfo(child)->graph, tag);
  2737. queryResourceInfo(child)->setConditionSource(tag, !wasConditional);
  2738. }
  2739. markChildDependentsAsUnconditional(info, condition);
  2740. return;
  2741. }
  2742. break;
  2743. case no_case:
  2744. case no_map:
  2745. UNIMPLEMENTED;
  2746. }
  2747. unsigned first = getFirstActivityArgument(expr);
  2748. unsigned last = first + getNumActivityArguments(expr);
  2749. for (unsigned idx=first; idx < last; idx++)
  2750. markAsUnconditional(expr->queryChild(idx), info->graph, condition);
  2751. markChildDependentsAsUnconditional(info, condition);
  2752. }
  2753. void EclResourcer::markConditionBranch(unsigned childIndex, IHqlExpression * expr, IHqlExpression * condition, bool wasConditional)
  2754. {
  2755. IHqlExpression * child = expr->queryChild(childIndex);
  2756. if (child)
  2757. {
  2758. OwnedHqlExpr tag = createAttribute(((childIndex==1) ? trueAtom : falseAtom), LINK(expr), LINK(condition));
  2759. markAsUnconditional(child, queryResourceInfo(child)->graph, tag);
  2760. queryResourceInfo(child)->setConditionSource(tag, !wasConditional);
  2761. }
  2762. }
  2763. void EclResourcer::markCondition(IHqlExpression * expr, IHqlExpression * condition, bool wasConditional)
  2764. {
  2765. markConditionBranch(1, expr, condition, wasConditional);
  2766. markConditionBranch(2, expr, condition, wasConditional);
  2767. }
  2768. void EclResourcer::markConditions(HqlExprArray & exprs)
  2769. {
  2770. ForEachItemIn(idx, exprs)
  2771. markAsUnconditional(&exprs.item(idx), NULL, NULL);
  2772. ForEachItemIn(idx2, rootConditions)
  2773. markCondition(&rootConditions.item(idx2), NULL, false);
  2774. }
  2775. //------------------------------------------------------------------------------------------
  2776. // PASS4: Split subgraphs based on resource requirements for activities
  2777. //This will need to be improved if we allow backtracking to get the best combination of activities to fit in the subgraph
  2778. void EclResourcer::createResourceSplit(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerNewGraph, ResourceGraphInfo * originalGraph)
  2779. {
  2780. ResourcerInfo * info = queryResourceInfo(expr);
  2781. info->graph.setown(createGraph());
  2782. info->graph->isUnconditional = originalGraph->isUnconditional;
  2783. changeGraph(expr, info->graph);
  2784. connectGraphs(info->graph, expr, ownerNewGraph, owner, UnconditionalLink);
  2785. info->numExternalUses++;
  2786. }
  2787. void EclResourcer::getResources(IHqlExpression * expr, CResources & exprResources)
  2788. {
  2789. ::getResources(expr, exprResources, options);
  2790. }
  2791. bool EclResourcer::calculateResourceSpillPoints(IHqlExpression * expr, ResourceGraphInfo * graph, CResources & resourcesSoFar, bool hasGoodSpillPoint, bool canSpill)
  2792. {
  2793. ResourcerInfo * info = queryResourceInfo(expr);
  2794. if (!info || !info->containsActivity)
  2795. return true;
  2796. if (!info->isActivity)
  2797. {
  2798. unsigned first = getFirstActivityArgument(expr);
  2799. unsigned last = first + getNumActivityArguments(expr);
  2800. if (last - first == 1)
  2801. return calculateResourceSpillPoints(expr->queryChild(first), graph, resourcesSoFar, hasGoodSpillPoint, canSpill);
  2802. for (unsigned idx = first; idx < last; idx++)
  2803. calculateResourceSpillPoints(expr->queryChild(idx), graph, resourcesSoFar, false, canSpill);
  2804. return true;
  2805. }
  2806. if (info->graph != graph)
  2807. return true;
  2808. CResources exprResources(clusterSize);
  2809. getResources(expr, exprResources);
  2810. info->isSpillPoint = false;
  2811. Owned<CResources> curResources = LINK(&resourcesSoFar);
  2812. if (resourcesSoFar.addExceeds(exprResources, *resourceLimit))
  2813. {
  2814. if (hasGoodSpillPoint)
  2815. return false;
  2816. info->isSpillPoint = true;
  2817. spilled = true;
  2818. curResources.setown(new CResources(clusterSize));
  2819. if (exprResources.exceeds(*resourceLimit))
  2820. throwError2(HQLERR_CannotResourceActivity, getOpString(expr->getOperator()), clusterSize);
  2821. }
  2822. if (options.minimizeSkewBeforeSpill)
  2823. {
  2824. if (canSpill && heavyweightAndReducesSizeOrSkew(expr))
  2825. {
  2826. //if the input activity is going to cause us to run out of resources, then it is going to be better to split here than anywhere else
  2827. //this code may conceivably cause extra spills far away because the hash distributes are moved.
  2828. IHqlExpression * childExpr = expr->queryChild(0);
  2829. ResourcerInfo * childInfo = queryResourceInfo(childExpr);
  2830. if (childInfo->graph == graph)
  2831. {
  2832. CResources childResources(clusterSize);
  2833. getResources(childExpr, childResources);
  2834. childResources.add(exprResources);
  2835. if (curResources->addExceeds(childResources, *resourceLimit))
  2836. {
  2837. info->isSpillPoint = true;
  2838. spilled = true;
  2839. calculateResourceSpillPoints(childExpr, graph, exprResources, false, true);
  2840. return true;
  2841. }
  2842. }
  2843. //otherwise continue as normal.
  2844. }
  2845. }
  2846. curResources->add(exprResources);
  2847. unsigned first = getFirstActivityArgument(expr);
  2848. unsigned last = first + getNumActivityArguments(expr);
  2849. if (hasGoodSpillPoint)
  2850. {
  2851. if (exprResources.resource[RESheavy] || exprResources.resource[REShashdist] || last-first != 1)
  2852. hasGoodSpillPoint = false;
  2853. }
  2854. else if (!info->isSpillPoint && canSpill)
  2855. {
  2856. if (lightweightAndReducesDatasetSize(expr) || queryHint(expr, spillAtom))
  2857. {
  2858. CResources savedResources(*curResources);
  2859. if (!calculateResourceSpillPoints(expr->queryChild(0), graph, *curResources, true, true))
  2860. {
  2861. curResources->set(savedResources);
  2862. info->isSpillPoint = true;
  2863. spilled = true;
  2864. calculateResourceSpillPoints(expr->queryChild(0), graph, exprResources, false, true);
  2865. }
  2866. return true;
  2867. }
  2868. }
  2869. if (expr->getOperator() == no_if)
  2870. {
  2871. //For conditions, spill on intersection of resources used, not union.
  2872. CResources savedResources(*curResources);
  2873. if (!calculateResourceSpillPoints(expr->queryChild(1), graph, *curResources, hasGoodSpillPoint, true))
  2874. return false;
  2875. if (expr->queryChild(2))
  2876. {
  2877. if (!calculateResourceSpillPoints(expr->queryChild(2), graph, savedResources, hasGoodSpillPoint, true))
  2878. return false;
  2879. curResources->maximize(savedResources);
  2880. }
  2881. }
  2882. else
  2883. {
  2884. for (unsigned idx = first; idx < last; idx++)
  2885. if (!calculateResourceSpillPoints(expr->queryChild(idx), graph, *curResources, hasGoodSpillPoint, true))
  2886. return false;
  2887. }
  2888. return true;
  2889. }
  2890. void EclResourcer::insertResourceSpillPoints(IHqlExpression * expr, IHqlExpression * owner, ResourceGraphInfo * ownerOriginalGraph, ResourceGraphInfo * ownerNewGraph)
  2891. {
  2892. ResourcerInfo * info = queryResourceInfo(expr);
  2893. if (!info || !info->containsActivity)
  2894. return;
  2895. if (!info->isActivity)
  2896. {
  2897. unsigned first = getFirstActivityArgument(expr);
  2898. unsigned last = first + getNumActivityArguments(expr);
  2899. for (unsigned idx = first; idx < last; idx++)
  2900. insertResourceSpillPoints(expr->queryChild(idx), expr, ownerOriginalGraph, ownerNewGraph);
  2901. return;
  2902. }
  2903. ResourceGraphInfo * originalGraph = info->graph; //NB: Graph will never cease to exist, so don't need to link.
  2904. if (originalGraph != ownerOriginalGraph)
  2905. return;
  2906. if (info->isSpillPoint)
  2907. createResourceSplit(expr, owner, ownerNewGraph, originalGraph);
  2908. else if (info->graph != ownerNewGraph)
  2909. changeGraph(expr, ownerNewGraph);
  2910. CResources exprResources(clusterSize);
  2911. getResources(expr, exprResources);
  2912. bool ok = info->graph->allocateResources(exprResources, *resourceLimit);
  2913. assertex(ok);
  2914. if (expr->getOperator() == no_if)
  2915. {
  2916. CResources savedResources(info->graph->resources);
  2917. insertResourceSpillPoints(expr->queryChild(1), expr, originalGraph, info->graph);
  2918. if (expr->queryChild(2))
  2919. {
  2920. CResources branchResources(info->graph->resources);
  2921. info->graph->resources.set(savedResources);
  2922. insertResourceSpillPoints(expr->queryChild(2), expr, originalGraph, info->graph);
  2923. info->graph->resources.maximize(branchResources);
  2924. }
  2925. }
  2926. else
  2927. {
  2928. unsigned first = getFirstActivityArgument(expr);
  2929. unsigned last = first + getNumActivityArguments(expr);
  2930. for (unsigned idx = first; idx < last; idx++)
  2931. insertResourceSpillPoints(expr->queryChild(idx), expr, originalGraph, info->graph);
  2932. }
  2933. }
  2934. void EclResourcer::resourceSubGraph(ResourceGraphInfo * graph)
  2935. {
  2936. if (graph->beenResourced)
  2937. return;
  2938. graph->beenResourced = true;
  2939. ForEachItemIn(idx, graph->sources)
  2940. resourceSubGraph(graph->sources.item(idx).sourceGraph);
  2941. IHqlExpression * sourceNode = graph->sinks.item(0).sourceNode->queryBody();
  2942. #ifdef _DEBUG
  2943. //Sanity check, ensure there is only a single sink for this graph.
  2944. //However because libraryselects are tightly bound to their library instance there may be multiple library selects.
  2945. //They won't affect the resourcing though, since they'll plug into the same library instance, and the selects use no resources.
  2946. ForEachItemIn(idx2, graph->sinks)
  2947. {
  2948. IHqlExpression * thisSink = graph->sinks.item(idx2).sourceNode->queryBody();
  2949. if (thisSink->getOperator() != no_libraryselect)
  2950. assertex(thisSink == sourceNode);
  2951. }
  2952. #endif
  2953. spilled = false;
  2954. CResources resources(clusterSize);
  2955. calculateResourceSpillPoints(sourceNode, graph, resources, false, false);
  2956. if (spilled)
  2957. insertResourceSpillPoints(sourceNode, NULL, graph, graph);
  2958. else
  2959. graph->resources.set(resources);
  2960. }
  2961. void EclResourcer::resourceSubGraphs(HqlExprArray & exprs)
  2962. {
  2963. ForEachItemIn(idx, graphs)
  2964. resourceSubGraph(&graphs.item(idx));
  2965. }
  2966. //------------------------------------------------------------------------------------------
  2967. // PASS5: Link subrgaphs with dependency information so they don't get merged by accident.
  2968. void EclResourcer::addDependencySource(IHqlExpression * search, ResourceGraphInfo * curGraph, IHqlExpression * expr)
  2969. {
  2970. //MORE: Should we check this doesn't already exist?
  2971. dependencySource.search.append(*LINK(search));
  2972. dependencySource.graphs.append(*LINK(curGraph));
  2973. dependencySource.exprs.append(*LINK(expr));
  2974. }
  2975. void EclResourcer::addDependencyUse(IHqlExpression * search, ResourceGraphInfo * curGraph, IHqlExpression * expr)
  2976. {
  2977. unsigned index = dependencySource.search.find(*search);
  2978. if (index != NotFound)
  2979. {
  2980. if (&dependencySource.graphs.item(index) == curGraph)
  2981. {
  2982. //Don't give a warning if get/set is within the same activity (e.g., within a local())
  2983. if (&dependencySource.exprs.item(index) != expr)
  2984. //errors->reportWarning(HQLWRN_RecursiveDependendencies, HQLWRN_RecursiveDependendencies_Text, *codeGeneratorAtom, 0, 0, 0);
  2985. errors->reportError(HQLWRN_RecursiveDependendencies, HQLWRN_RecursiveDependendencies_Text, *codeGeneratorAtom, 0, 0, 0);
  2986. }
  2987. else
  2988. {
  2989. ResourceGraphLink * link = new ResourceGraphDependencyLink(&dependencySource.graphs.item(index), &dependencySource.exprs.item(index), curGraph, expr);
  2990. curGraph->dependsOn.append(*link);
  2991. links.append(*link);
  2992. }
  2993. }
  2994. }
  2995. void EclResourcer::addRefExprDependency(IHqlExpression * expr, ResourceGraphInfo * curGraph, IHqlExpression * activityExpr)
  2996. {
  2997. IHqlExpression * filename = queryTableFilename(expr);
  2998. if (filename)
  2999. {
  3000. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(filename));
  3001. addDependencySource(value, curGraph, activityExpr);
  3002. }
  3003. }
  3004. bool EclResourcer::addExprDependency(IHqlExpression * expr, ResourceGraphInfo * curGraph, IHqlExpression * activityExpr)
  3005. {
  3006. switch (expr->getOperator())
  3007. {
  3008. case no_buildindex:
  3009. case no_output:
  3010. {
  3011. IHqlExpression * filename = queryRealChild(expr, 1);
  3012. if (filename)
  3013. {
  3014. switch (filename->getOperator())
  3015. {
  3016. case no_pipe:
  3017. // allWritten = true;
  3018. break;
  3019. default:
  3020. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(filename));
  3021. addDependencySource(value, curGraph, activityExpr);
  3022. break;
  3023. }
  3024. }
  3025. else
  3026. {
  3027. IHqlExpression * seq = querySequence(expr);
  3028. assertex(seq && seq->queryValue());
  3029. IHqlExpression * name = queryResultName(expr);
  3030. OwnedHqlExpr value = createAttribute(resultAtom, LINK(seq), LINK(name));
  3031. addDependencySource(value, curGraph, activityExpr);
  3032. }
  3033. return true;
  3034. }
  3035. case no_keydiff:
  3036. {
  3037. addRefExprDependency(expr->queryChild(0), curGraph, activityExpr);
  3038. addRefExprDependency(expr->queryChild(1), curGraph, activityExpr);
  3039. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(expr->queryChild(2)));
  3040. addDependencySource(value, curGraph, activityExpr);
  3041. return true;
  3042. }
  3043. case no_keypatch:
  3044. {
  3045. addRefExprDependency(expr->queryChild(0), curGraph, activityExpr);
  3046. OwnedHqlExpr patchName = createAttribute(fileAtom, getNormalizedFilename(expr->queryChild(1)));
  3047. addDependencyUse(patchName, curGraph, activityExpr);
  3048. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(expr->queryChild(2)));
  3049. addDependencySource(value, curGraph, activityExpr);
  3050. return true;
  3051. }
  3052. case no_table:
  3053. {
  3054. IHqlExpression * filename = expr->queryChild(0);
  3055. OwnedHqlExpr value = createAttribute(fileAtom, getNormalizedFilename(filename));
  3056. addDependencyUse(value, curGraph, activityExpr);
  3057. return !filename->isConstant();
  3058. }
  3059. case no_select:
  3060. return expr->hasProperty(newAtom);
  3061. case no_workunit_dataset:
  3062. {
  3063. IHqlExpression * sequence = queryPropertyChild(expr, sequenceAtom, 0);
  3064. IHqlExpression * name = queryPropertyChild(expr, nameAtom, 0);
  3065. OwnedHqlExpr value = createAttribute(resultAtom, LINK(sequence), LINK(name));
  3066. addDependencyUse(value, curGraph, activityExpr);
  3067. return false;
  3068. }
  3069. case no_getresult:
  3070. {
  3071. IHqlExpression * sequence = queryPropertyChild(expr, sequenceAtom, 0);
  3072. IHqlExpression * name = queryPropertyChild(expr, namedAtom, 0);
  3073. OwnedHqlExpr value = createAttribute(resultAtom, LINK(sequence), LINK(name));
  3074. addDependencyUse(value, curGraph, activityExpr);
  3075. return false;
  3076. }
  3077. case no_getgraphresult:
  3078. {
  3079. OwnedHqlExpr value = createAttribute(resultAtom, LINK(expr->queryChild(1)), LINK(expr->queryChild(2)));
  3080. addDependencyUse(value, curGraph, activityExpr);
  3081. return false;
  3082. }
  3083. case no_setgraphresult:
  3084. {
  3085. OwnedHqlExpr value = createAttribute(resultAtom, LINK(expr->queryChild(1)), LINK(expr->queryChild(2)));
  3086. addDependencySource(value, curGraph, activityExpr);
  3087. return true;
  3088. }
  3089. case no_ensureresult:
  3090. case no_setresult:
  3091. case no_extractresult:
  3092. {
  3093. IHqlExpression * sequence = queryPropertyChild(expr, sequenceAtom, 0);
  3094. IHqlExpression * name = queryPropertyChild(expr, namedAtom, 0);
  3095. OwnedHqlExpr value = createAttribute(resultAtom, LINK(sequence), LINK(name));
  3096. addDependencySource(value, curGraph, activityExpr);
  3097. return true;
  3098. }
  3099. case no_attr:
  3100. case no_attr_link:
  3101. case no_record:
  3102. case no_field:
  3103. return false; //no need to look any further
  3104. default:
  3105. return true;
  3106. }
  3107. }
  3108. void EclResourcer::doAddChildDependencies(IHqlExpression * expr, ResourceGraphInfo * graph, IHqlExpression * activityExpr)
  3109. {
  3110. if (expr->queryTransformExtra())
  3111. return;
  3112. expr->setTransformExtraUnlinked(expr);
  3113. if (addExprDependency(expr, graph, activityExpr))
  3114. {
  3115. ForEachChild(idx, expr)
  3116. doAddChildDependencies(expr->queryChild(idx), graph, activityExpr);
  3117. }
  3118. }
  3119. void EclResourcer::addChildDependencies(IHqlExpression * expr, ResourceGraphInfo * graph, IHqlExpression * activityExpr)
  3120. {
  3121. if (graph)
  3122. {
  3123. lockTransformMutex();
  3124. doAddChildDependencies(expr, graph, activityExpr);
  3125. unlockTransformMutex();
  3126. }
  3127. }
  3128. void EclResourcer::addDependencies(IHqlExpression * expr, ResourceGraphInfo * graph, IHqlExpression * activityExpr)
  3129. {
  3130. ResourcerInfo * info = queryResourceInfo(expr);
  3131. if (info && info->containsActivity)
  3132. {
  3133. if (info->isActivity)
  3134. {
  3135. if (info->gatheredDependencies)
  3136. return;
  3137. info->gatheredDependencies = true;
  3138. graph = info->graph;
  3139. activityExpr = expr;
  3140. }
  3141. if (addExprDependency(expr, graph, activityExpr))
  3142. {
  3143. unsigned first = getFirstActivityArgument(expr);
  3144. unsigned last = first + getNumActivityArguments(expr);
  3145. ForEachChild(idx, expr)
  3146. {
  3147. if ((idx >= first) && (idx < last))
  3148. addDependencies(expr->queryChild(idx), graph, activityExpr);
  3149. else
  3150. addChildDependencies(expr->queryChild(idx), graph, activityExpr);
  3151. }
  3152. }
  3153. }
  3154. else
  3155. addChildDependencies(expr, graph, activityExpr);
  3156. ForEachItemIn(i, info->childDependents)
  3157. {
  3158. IHqlExpression & cur = info->childDependents.item(i);
  3159. if (isResourcedActivity(&cur))
  3160. {
  3161. addDependencies(&cur, NULL, NULL);
  3162. ResourcerInfo * sourceInfo = queryResourceInfo(&cur);
  3163. sourceInfo->noteUsedFromChild();
  3164. ResourceGraphLink * link = new ResourceGraphDependencyLink(sourceInfo->graph, &cur, graph, expr);
  3165. graph->dependsOn.append(*link);
  3166. links.append(*link);
  3167. }
  3168. }
  3169. }
  3170. void EclResourcer::addDependencies(HqlExprArray & exprs)
  3171. {
  3172. ForEachItemIn(idx, exprs)
  3173. addDependencies(&exprs.item(idx), NULL, NULL);
  3174. }
  3175. void EclResourcer::spotUnbalancedSplitters(IHqlExpression * expr, unsigned whichSource, IHqlExpression * path, ResourceGraphInfo * graph)
  3176. {
  3177. ResourcerInfo * info = queryResourceInfo(expr);
  3178. if (!info)
  3179. return;
  3180. if (graph && info->graph && info->graph != graph)
  3181. {
  3182. if ((info->currentSource == whichSource) && (info->pathToSplitter != path))
  3183. graph->unbalancedExternalSources.append(*LINK(expr->queryBody()));
  3184. info->currentSource = whichSource;
  3185. info->pathToSplitter.set(path);
  3186. return;
  3187. }
  3188. else
  3189. {
  3190. if (info->currentSource == whichSource)
  3191. {
  3192. if (info->pathToSplitter != path)
  3193. info->balanced = false;
  3194. return;
  3195. }
  3196. info->currentSource = whichSource;
  3197. info->pathToSplitter.set(path);
  3198. }
  3199. if (info->containsActivity)
  3200. {
  3201. unsigned first = getFirstActivityArgument(expr);
  3202. unsigned num = getNumActivityArguments(expr);
  3203. bool modify = false;
  3204. if (num > 1)
  3205. {
  3206. switch (expr->getOperator())
  3207. {
  3208. case no_addfiles:
  3209. if (expr->hasProperty(_ordered_Atom) || expr->hasProperty(_orderedPull_Atom) || isGrouped(expr))
  3210. modify = true;
  3211. break;
  3212. default:
  3213. modify = true;
  3214. break;
  3215. }
  3216. }
  3217. unsigned last = first + num;
  3218. for (unsigned idx = first; idx < last; idx++)
  3219. {
  3220. OwnedHqlExpr childPath = modify ? createAttribute(pathAtom, getSizetConstant(idx), LINK(path)) : LINK(path);
  3221. spotUnbalancedSplitters(expr->queryChild(idx), whichSource, childPath, graph);
  3222. }
  3223. }
  3224. //Now check dependencies between graphs (for roxie)
  3225. if (!graph)
  3226. {
  3227. if (info->graph)
  3228. {
  3229. GraphLinkArray & graphLinks = info->graph->dependsOn;
  3230. ForEachItemIn(i, graphLinks)
  3231. {
  3232. ResourceGraphLink & link = graphLinks.item(i);
  3233. if (link.sinkNode == expr)
  3234. {
  3235. OwnedHqlExpr childPath = createAttribute(dependencyAtom, LINK(link.sourceNode), LINK(path));
  3236. spotUnbalancedSplitters(link.sourceNode, whichSource, childPath, graph);
  3237. }
  3238. }
  3239. }
  3240. else
  3241. {
  3242. ForEachItemIn(i, links)
  3243. {
  3244. ResourceGraphLink & link = links.item(i);
  3245. if (link.sinkNode == expr)
  3246. {
  3247. OwnedHqlExpr childPath = createAttribute(dependencyAtom, LINK(link.sourceNode), LINK(path));
  3248. spotUnbalancedSplitters(link.sourceNode, whichSource, childPath, graph);
  3249. }
  3250. }
  3251. }
  3252. }
  3253. }
  3254. void EclResourcer::spotUnbalancedSplitters(HqlExprArray & exprs)
  3255. {
  3256. unsigned curSource = 1;
  3257. switch (targetClusterType)
  3258. {
  3259. case HThorCluster:
  3260. break;
  3261. case ThorCluster:
  3262. case ThorLCRCluster:
  3263. {
  3264. //Thor only handles one graph at a time, so only walk expressions within a single graph.
  3265. ForEachItemIn(i1, graphs)
  3266. {
  3267. ResourceGraphInfo & curGraph = graphs.item(i1);
  3268. ForEachItemIn(i2, curGraph.sinks)
  3269. {
  3270. ResourceGraphLink & cur = curGraph.sinks.item(i2);
  3271. spotUnbalancedSplitters(cur.sourceNode, curSource++, 0, &curGraph);
  3272. }
  3273. }
  3274. }
  3275. break;
  3276. case RoxieCluster:
  3277. {
  3278. //Roxie pulls all at once, so need to analyse globally.
  3279. ForEachItemIn(idx, exprs)
  3280. spotUnbalancedSplitters(&exprs.item(idx), curSource++, 0, NULL);
  3281. break;
  3282. }
  3283. }
  3284. }
  3285. void EclResourcer::spotSharedInputs(IHqlExpression * expr, ResourceGraphInfo * graph)
  3286. {
  3287. ResourcerInfo * info = queryResourceInfo(expr);
  3288. if (!info)
  3289. return;
  3290. if (info->graph && info->graph != graph)
  3291. {
  3292. IHqlExpression * body = expr->queryBody();
  3293. if (!graph->unbalancedExternalSources.contains(*body))
  3294. graph->balancedExternalSources.append(*LINK(body));
  3295. return;
  3296. }
  3297. if (info->isSplit())
  3298. {
  3299. //overload currentSource to track if we have visited this splitter before. It cannot have value value NotFound up to now
  3300. if (info->currentSource == NotFound)
  3301. return;
  3302. info->currentSource = NotFound;
  3303. }
  3304. if (info->containsActivity)
  3305. {
  3306. unsigned first = getFirstActivityArgument(expr);
  3307. unsigned num = getNumActivityArguments(expr);
  3308. unsigned last = first + num;
  3309. for (unsigned idx = first; idx < last; idx++)
  3310. {
  3311. spotSharedInputs(expr->queryChild(idx), graph);
  3312. }
  3313. }
  3314. }
  3315. void EclResourcer::spotSharedInputs()
  3316. {
  3317. //Thor only handles one graph at a time, so only walk expressions within a single graph.
  3318. ForEachItemIn(i1, graphs)
  3319. {
  3320. ResourceGraphInfo & curGraph = graphs.item(i1);
  3321. HqlExprCopyArray visited;
  3322. ForEachItemIn(i2, curGraph.sinks)
  3323. {
  3324. ResourceGraphLink & cur = curGraph.sinks.item(i2);
  3325. IHqlExpression * curExpr = cur.sourceNode;
  3326. if (!visited.contains(*curExpr))
  3327. {
  3328. ResourcerInfo * info = queryResourceInfo(curExpr);
  3329. if (!info->isExternalSpill() && !info->expandRatherThanSpill(true))
  3330. {
  3331. spotSharedInputs(curExpr, &curGraph);
  3332. visited.append(*curExpr);
  3333. }
  3334. }
  3335. }
  3336. }
  3337. }
  3338. //------------------------------------------------------------------------------------------
  3339. // PASS6: Merge sub graphs that can share resources and don't have dependencies
  3340. // MORE: Once sources are merged, should try merging between trees.
  3341. static bool conditionsMatch(const HqlExprArray & left, const HqlExprArray & right)
  3342. {
  3343. if (left.ordinality() != right.ordinality())
  3344. return false;
  3345. ForEachItemIn(i, left)
  3346. {
  3347. if (!left.contains(right.item(i)) || !right.contains(left.item(i)))
  3348. return false;
  3349. }
  3350. return true;
  3351. }
  3352. bool EclResourcer::queryMergeGraphLink(ResourceGraphLink & link)
  3353. {
  3354. if (link.linkKind == UnconditionalLink)
  3355. {
  3356. //Don't combine any dependencies
  3357. const GraphLinkArray & sinks = link.sourceGraph->sinks;
  3358. ForEachItemIn(i1, sinks)
  3359. {
  3360. ResourceGraphLink & cur = sinks.item(i1);
  3361. if (cur.sinkGraph && cur.sourceNode->isAction())
  3362. return false;
  3363. }
  3364. //Roxie pulls all subgraphs at same time, so no problem with conditional links since handled at run time.
  3365. if (options.noConditionalLinks)
  3366. return true;
  3367. //No conditionals in the sink graph=>will be executed just as frequently
  3368. if (!link.sinkGraph->mergedConditionSource)
  3369. return true;
  3370. //Is this the only place this source graph is used? If so, always fine to merge
  3371. if (sinks.ordinality() == 1)
  3372. return true;
  3373. //1) if context the source graph is being merged into is unconditional, then it is ok [ could have conditional and unconditional paths to same graph]
  3374. //2) if context is conditional, then we don't really want to do it unless the conditions on all sinks are identical, and the only links occur between these two graphs.
  3375. // (situation occurs with spill fed into two branches of a join).
  3376. bool isConditionalInSinkGraph = false;
  3377. bool accessedFromManyGraphs = false;
  3378. ForEachItemIn(i, sinks)
  3379. {
  3380. ResourceGraphLink & cur = sinks.item(i);
  3381. if (cur.sinkNode)
  3382. {
  3383. if (cur.sinkGraph != link.sinkGraph)
  3384. accessedFromManyGraphs = true;
  3385. else
  3386. {
  3387. if (!isConditionalInSinkGraph)
  3388. {
  3389. ResourcerInfo * sinkInfo = queryResourceInfo(cur.sinkNode);
  3390. //If this is conditional, don't merge if there is a link to another graph
  3391. if ((!cur.isDependency() && sinkInfo->isConditionExpr()) ||
  3392. //if (sinkInfo->isConditionExpr() ||
  3393. (!sinkInfo->isUnconditional() && sinkInfo->conditions.ordinality()))
  3394. isConditionalInSinkGraph = true;
  3395. }
  3396. }
  3397. }
  3398. }
  3399. if (isConditionalInSinkGraph && accessedFromManyGraphs)
  3400. return false;
  3401. return true;
  3402. }
  3403. return false;
  3404. }
  3405. unsigned EclResourcer::getMaxDepth() const
  3406. {
  3407. unsigned maxDepth = 0;
  3408. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3409. {
  3410. unsigned depth = graphs.item(idx).getDepth();
  3411. if (depth > maxDepth)
  3412. maxDepth = depth;
  3413. }
  3414. return maxDepth;
  3415. }
  3416. void EclResourcer::mergeSubGraphs(unsigned pass)
  3417. {
  3418. unsigned maxDepth = getMaxDepth();
  3419. for (unsigned curDepth = maxDepth+1; curDepth-- != 0;)
  3420. {
  3421. mergeAgain:
  3422. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3423. {
  3424. ResourceGraphInfo & cur = graphs.item(idx);
  3425. if ((cur.getDepth() == curDepth) && !cur.isDead)
  3426. {
  3427. bool tryAgain;
  3428. do
  3429. {
  3430. tryAgain = false;
  3431. for (unsigned idxSource = 0; idxSource < cur.sources.ordinality(); /*incremented in loop*/)
  3432. {
  3433. ResourceGraphLink & curLink = cur.sources.item(idxSource);
  3434. ResourceGraphInfo * source = curLink.sourceGraph;
  3435. IHqlExpression * sourceNode = curLink.sourceNode;
  3436. bool tryToMerge;
  3437. bool expandSourceInPlace = queryResourceInfo(sourceNode)->expandRatherThanSpill(false);
  3438. if (pass == 0)
  3439. tryToMerge = !expandSourceInPlace;
  3440. else
  3441. tryToMerge = expandSourceInPlace;
  3442. if (tryToMerge)
  3443. {
  3444. bool ok = true;
  3445. ResourcerInfo * sourceResourceInfo = queryResourceInfo(sourceNode);
  3446. if (sourceResourceInfo->outputToUseForSpill && (targetClusterType == HThorCluster))
  3447. {
  3448. if (curLink.sinkNode != sourceResourceInfo->outputToUseForSpill)
  3449. ok = false;
  3450. }
  3451. unsigned curSourceDepth = source->getDepth();
  3452. //MORE: Merging identical conditionals?
  3453. if (ok && queryMergeGraphLink(curLink) &&
  3454. !sourceResourceInfo->expandRatherThanSplit() &&
  3455. cur.mergeInSource(*source, *resourceLimit, (curLink.linkKind == ConditionalLink)))
  3456. {
  3457. //NB: Following cannot remove sources below the current index.
  3458. replaceGraphReferences(source, &cur);
  3459. source->isDead = true;
  3460. #ifdef VERIFY_RESOURCING
  3461. checkRecursion(&cur);
  3462. #endif
  3463. unsigned newDepth = cur.getDepth();
  3464. //Unusual: The source we are merging with has just increased in depth, so any
  3465. //dependents have also increased in depth. Need to try again at different depth
  3466. //to see if one of those will merge in.
  3467. if (newDepth > curSourceDepth)
  3468. {
  3469. curDepth += (newDepth - curSourceDepth);
  3470. goto mergeAgain;
  3471. }
  3472. //depth of this element has changed, so don't check to see if it merges with any other
  3473. //sources on this iteration.
  3474. if (newDepth != curDepth)
  3475. {
  3476. tryAgain = false;
  3477. break;
  3478. }
  3479. tryAgain = true;
  3480. }
  3481. else
  3482. idxSource++;
  3483. }
  3484. else
  3485. idxSource++;
  3486. }
  3487. } while (tryAgain);
  3488. }
  3489. }
  3490. }
  3491. }
  3492. void EclResourcer::mergeSiblings()
  3493. {
  3494. unsigned maxDepth = getMaxDepth();
  3495. for (unsigned curDepth = maxDepth+1; curDepth-- != 0;)
  3496. {
  3497. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3498. {
  3499. ResourceGraphInfo & cur = graphs.item(idx);
  3500. if ((cur.getDepth() == curDepth) && !cur.isDead)
  3501. {
  3502. ForEachItemIn(idxSource, cur.sources)
  3503. {
  3504. ResourceGraphLink & curLink = cur.sources.item(idxSource);
  3505. ResourceGraphInfo * source = curLink.sourceGraph;
  3506. IHqlExpression * sourceNode = curLink.sourceNode;
  3507. ResourcerInfo * sourceInfo = queryResourceInfo(sourceNode);
  3508. if (sourceInfo->neverSplit || sourceInfo->expandRatherThanSplit())
  3509. continue;
  3510. for (unsigned iSink = 0; iSink < source->sinks.ordinality(); )
  3511. {
  3512. ResourceGraphLink & secondLink = source->sinks.item(iSink);
  3513. ResourceGraphInfo * sink = secondLink.sinkGraph;
  3514. if (sink && (sink != &cur) && !sink->isDead && sourceNode->queryBody() == secondLink.sourceNode->queryBody())
  3515. {
  3516. if (cur.mergeInSibling(*sink, *resourceLimit))
  3517. {
  3518. //NB: Following cannot remove sources below the current index.
  3519. replaceGraphReferences(sink, &cur);
  3520. sink->isDead = true;
  3521. }
  3522. else
  3523. iSink++;
  3524. }
  3525. else
  3526. iSink++;
  3527. }
  3528. }
  3529. }
  3530. }
  3531. }
  3532. }
  3533. void EclResourcer::mergeSubGraphs()
  3534. {
  3535. for (unsigned pass=0; pass < 2; pass++)
  3536. mergeSubGraphs(pass);
  3537. if (options.combineSiblings)
  3538. mergeSiblings();
  3539. ForEachItemInRev(idx2, graphs)
  3540. {
  3541. if (graphs.item(idx2).isDead)
  3542. graphs.remove(idx2);
  3543. }
  3544. }
  3545. //------------------------------------------------------------------------------------------
  3546. // PASS7: Optimize aggregates off of splitters into through aggregates.
  3547. bool EclResourcer::optimizeAggregate(IHqlExpression * expr)
  3548. {
  3549. if (!isSimpleAggregateResult(expr))
  3550. return false;
  3551. //expr is a no_extractresult
  3552. if (queryResourceInfo(expr)->childDependents.ordinality())
  3553. return false;
  3554. IHqlExpression * row2ds = expr->queryChild(0); // no_datasetfromrow
  3555. IHqlExpression * selectNth = row2ds->queryChild(0);
  3556. ResourcerInfo * row2dsInfo = queryResourceInfo(row2ds);
  3557. //If more than one set result for the same aggregate don't merge the aggregation because
  3558. //it messes up the internal count. Should really fix it and do multiple stores in the
  3559. //through aggregate.
  3560. if (row2dsInfo->numInternalUses() > 1)
  3561. return false;
  3562. //Be careful not to lose any spills...
  3563. if (row2dsInfo->numExternalUses)
  3564. return false;
  3565. ResourcerInfo * selectNthInfo = queryResourceInfo(selectNth);
  3566. if (selectNthInfo->numExternalUses)
  3567. return false;
  3568. IHqlExpression * aggregate = selectNth->queryChild(0); // no_newaggregate
  3569. IHqlExpression * parent = aggregate->queryChild(0);
  3570. ResourcerInfo * info = queryResourceInfo(parent);
  3571. if (info->numInternalUses() <= 1)
  3572. return false;
  3573. //ok, we can go ahead and merge.
  3574. info->aggregates.append(*LINK(expr));
  3575. // info->numExternalUses--;
  3576. // info->numUses--;
  3577. return true;
  3578. }
  3579. void EclResourcer::optimizeAggregates()
  3580. {
  3581. for (unsigned idx = 0; idx < graphs.ordinality(); idx++)
  3582. {
  3583. ResourceGraphInfo & cur = graphs.item(idx);
  3584. for (unsigned idxSink = 0; idxSink < cur.sinks.ordinality(); /*incremented in loop*/)
  3585. {
  3586. ResourceGraphLink & link = cur.sinks.item(idxSink);
  3587. if ((link.sinkGraph == NULL) && optimizeAggregate(link.sourceNode))
  3588. cur.sinks.remove(idxSink);
  3589. else
  3590. idxSink++;
  3591. }
  3592. }
  3593. }
  3594. //------------------------------------------------------------------------------------------
  3595. // PASS8: Improve efficiency by merging the split points slightly
  3596. IHqlExpression * EclResourcer::findPredecessor(IHqlExpression * expr, IHqlExpression * search, IHqlExpression * prev)
  3597. {
  3598. if (expr == search)
  3599. return prev;
  3600. ResourcerInfo * info = queryResourceInfo(expr);
  3601. if (info && info->containsActivity)
  3602. {
  3603. unsigned first = getFirstActivityArgument(expr);
  3604. unsigned last = first + getNumActivityArguments(expr);
  3605. for (unsigned idx=first; idx < last; idx++)
  3606. {
  3607. IHqlExpression * match = findPredecessor(expr->queryChild(idx), search, expr);
  3608. if (match)
  3609. return match;
  3610. }
  3611. }
  3612. return NULL;
  3613. }
  3614. IHqlExpression * EclResourcer::findPredecessor(ResourcerInfo * search)
  3615. {
  3616. ForEachItemIn(idx, links)
  3617. {
  3618. ResourceGraphLink & cur = links.item(idx);
  3619. if (cur.sourceGraph == search->graph)
  3620. {
  3621. IHqlExpression * match = findPredecessor(cur.sourceNode, search->original, NULL);
  3622. if (match)
  3623. return match;
  3624. }
  3625. }
  3626. return NULL;
  3627. }
  3628. void EclResourcer::moveExternalSpillPoints()
  3629. {
  3630. if (options.minimizeSpillSize == 0)
  3631. return;
  3632. //if we have a external spill point where all the external outputs reduce their data significantly
  3633. //either via a project or a filter, then it might be worth including those activities in the main
  3634. //graph and ,if all external children reduce data, then may be best to filter
  3635. ForEachItemIn(idx, links)
  3636. {
  3637. ResourceGraphLink & cur = links.item(idx);
  3638. if ((cur.linkKind == UnconditionalLink) && cur.sinkGraph)
  3639. {
  3640. while (lightweightAndReducesDatasetSize(cur.sinkNode))
  3641. {
  3642. ResourcerInfo * sourceInfo = queryResourceInfo(cur.sourceNode);
  3643. if (!sourceInfo->isExternalSpill() || (sourceInfo->numExternalUses > options.minimizeSpillSize))
  3644. break;
  3645. ResourcerInfo * sinkInfo = queryResourceInfo(cur.sinkNode);
  3646. if (sinkInfo->numInternalUses() != 1)
  3647. break;
  3648. IHqlExpression * sinkPred = findPredecessor(sinkInfo);
  3649. sinkInfo->graph.set(cur.sourceGraph);
  3650. sourceInfo->numExternalUses--;
  3651. sinkInfo->numExternalUses++;
  3652. cur.sourceNode.set(cur.sinkNode);
  3653. cur.sinkNode.set(sinkPred);
  3654. }
  3655. }
  3656. }
  3657. }
  3658. //------------------------------------------------------------------------------------------
  3659. // PASS9: Create a new expression tree representing the information
  3660. static HqlTransformerInfo childDependentReplacerInfo("ChildDependentReplacer");
  3661. class ChildDependentReplacer : public MergingHqlTransformer
  3662. {
  3663. public:
  3664. ChildDependentReplacer(const HqlExprCopyArray & _childDependents, const HqlExprArray & _replacements)
  3665. : MergingHqlTransformer(childDependentReplacerInfo), childDependents(_childDependents), replacements(_replacements)
  3666. {
  3667. }
  3668. protected:
  3669. virtual IHqlExpression * createTransformed(IHqlExpression * expr)
  3670. {
  3671. unsigned match = childDependents.find(*expr);
  3672. if (match != NotFound)
  3673. return LINK(&replacements.item(match));
  3674. return MergingHqlTransformer::createTransformed(expr);
  3675. }
  3676. protected:
  3677. const HqlExprCopyArray & childDependents;
  3678. const HqlExprArray & replacements;
  3679. };
  3680. static IHqlExpression * getScalarReplacement(IHqlExpression * original, IHqlExpression * replacement)
  3681. {
  3682. IHqlExpression * value = original;
  3683. //First skip any wrappers which are there to cause things to be hoisted.
  3684. loop
  3685. {
  3686. node_operator op = value->getOperator();
  3687. if ((op != no_globalscope) && (op != no_thisnode) && (op != no_evalonce))
  3688. break;
  3689. value = value->queryChild(0);
  3690. }
  3691. //Now modify the spilled result depending on how the spilled result was created (see EclHoistLocator::noteScalar() above)
  3692. if (value->getOperator() == no_select)
  3693. {
  3694. IHqlExpression * field = value->queryChild(1);
  3695. bool isNew;
  3696. IHqlExpression * ds = querySelectorDataset(value, isNew);
  3697. if(isNew || ds->isDatarow())
  3698. {
  3699. if (projectSelectorDatasetToField(ds))
  3700. return createNewSelectExpr(LINK(replacement), LINK(field));
  3701. return replaceSelectorDataset(value, replacement);
  3702. }
  3703. }
  3704. else if (value->getOperator() == no_createset)
  3705. {
  3706. IHqlExpression * record = replacement->queryRecord();
  3707. IHqlExpression * field = record->queryChild(0);
  3708. return createValue(no_createset, original->getType(), LINK(replacement), createSelectExpr(LINK(replacement->queryNormalizedSelector()), LINK(field)));
  3709. }
  3710. IHqlExpression * record = replacement->queryRecord();
  3711. return createNewSelectExpr(LINK(replacement), LINK(record->queryChild(0)));
  3712. }
  3713. IHqlExpression * EclResourcer::replaceResourcedReferences(ResourcerInfo * info, IHqlExpression * expr)
  3714. {
  3715. if (!isAffectedByResourcing(expr))
  3716. return LINK(expr);
  3717. LinkedHqlExpr mapped = expr;
  3718. if (info && (info->childDependents.ordinality()))
  3719. {
  3720. HqlExprArray replacements;
  3721. ForEachItemIn(i, info->originalChildDependents)
  3722. {
  3723. IHqlExpression & cur = info->childDependents.item(i);
  3724. LinkedHqlExpr replacement = &cur;
  3725. if (isResourcedActivity(&cur))
  3726. replacement.setown(createResourced(&cur, NULL, false, false));
  3727. IHqlExpression * original = &info->originalChildDependents.item(i);
  3728. if (!original->isDataset() && !original->isDatarow())
  3729. replacement.setown(getScalarReplacement(original, replacement));
  3730. replacements.append(*replacement.getClear());
  3731. }
  3732. ChildDependentReplacer replacer(info->originalChildDependents, replacements);
  3733. mapped.setown(replacer.transformRoot(mapped));
  3734. }
  3735. return mapped.getClear();
  3736. }
  3737. IHqlExpression * EclResourcer::doCreateResourced(IHqlExpression * expr, ResourceGraphInfo * ownerGraph, bool expandInParent, bool defineSideEffect)
  3738. {
  3739. ResourcerInfo * info = queryResourceInfo(expr);
  3740. node_operator op = expr->getOperator();
  3741. HqlExprArray args;
  3742. bool same = true;
  3743. unsigned first = getFirstActivityArgument(expr);
  3744. unsigned last = first + getNumActivityArguments(expr);
  3745. OwnedHqlExpr transformed;
  3746. switch (op)
  3747. {
  3748. case no_if:
  3749. {
  3750. ForEachChild(idx, expr)
  3751. {
  3752. IHqlExpression * child = expr->queryChild(idx);
  3753. IHqlExpression * resourced;
  3754. if ((idx < first) || (idx >= last))
  3755. resourced = replaceResourcedReferences(info, child);
  3756. else
  3757. resourced = createResourced(child, ownerGraph, expandInParent, false);
  3758. if (child != resourced)
  3759. same = false;
  3760. args.append(*resourced);
  3761. }
  3762. break;
  3763. }
  3764. case no_case:
  3765. case no_map:
  3766. UNIMPLEMENTED;
  3767. case no_keyed:
  3768. return LINK(expr);
  3769. case no_compound:
  3770. transformed.setown(createResourced(expr->queryChild(1), ownerGraph, expandInParent, false));
  3771. break;
  3772. case no_executewhen:
  3773. {
  3774. args.append(*createResourced(expr->queryChild(0), ownerGraph, expandInParent, false));
  3775. args.append(*createResourced(expr->queryChild(1), ownerGraph, expandInParent, false));
  3776. assertex(args.item(1).getOperator() == no_callsideeffect);
  3777. unwindChildren(args, expr, 2);
  3778. same = false;
  3779. break;
  3780. }
  3781. case no_join:
  3782. case no_denormalize:
  3783. case no_denormalizegroup:
  3784. if (false)//if (isKeyedJoin(expr))
  3785. {
  3786. args.append(*createResourced(expr->queryChild(0), ownerGraph, expandInParent, false));
  3787. args.append(*LINK(expr->queryChild(1)));
  3788. unsigned max = expr->numChildren();
  3789. for (unsigned idx=2; idx < max; idx++)
  3790. args.append(*replaceResourcedReferences(info, expr->queryChild(idx)));
  3791. same = false;
  3792. break;
  3793. }
  3794. //fall through...
  3795. default:
  3796. {
  3797. IHqlExpression * activeTable = NULL;
  3798. // Check to see if the activity has a dataset which is in scope for the rest of its arguments.
  3799. // If so we'll need to remap references from the children.
  3800. if (hasActiveTopDataset(expr) && (first != last))
  3801. activeTable = expr->queryChild(0);
  3802. ForEachChild(idx, expr)
  3803. {
  3804. IHqlExpression * child = expr->queryChild(idx);
  3805. IHqlExpression * resourced;
  3806. if ((idx < first) || (idx >= last))
  3807. {
  3808. LinkedHqlExpr mapped = child;
  3809. if (activeTable && isAffectedByResourcing(child))
  3810. {
  3811. IHqlExpression * activeTableTransformed = &args.item(0);
  3812. if (activeTable != activeTableTransformed)
  3813. mapped.setown(scopedReplaceSelector(child, activeTable, activeTableTransformed));
  3814. }
  3815. resourced = replaceResourcedReferences(info, mapped);
  3816. }
  3817. else
  3818. resourced = createResourced(child, ownerGraph, expandInParent, false);
  3819. if (child != resourced)
  3820. same = false;
  3821. args.append(*resourced);
  3822. }
  3823. }
  3824. break;
  3825. }
  3826. if (!transformed)
  3827. transformed.setown(same ? LINK(expr) : expr->clone(args));
  3828. if (!expandInParent)
  3829. {
  3830. if (!transformed->isAction())
  3831. transformed.setown(info->createTransformedExpr(transformed));
  3832. else if (defineSideEffect)
  3833. transformed.setown(createValue(no_definesideeffect, LINK(transformed), createUniqueId()));
  3834. }
  3835. return transformed.getClear();
  3836. }
  3837. /*
  3838. Need to be careful because result should not reuse the same expression tree unless that element is a splitter.
  3839. createResourced()
  3840. {
  3841. if (!isActivity)
  3842. if (!containsActivity)
  3843. replace any refs to the activeTable with whatever it has been mapped to
  3844. else
  3845. recurse
  3846. else if (!isDefinedInSameGraph)
  3847. expand/create reader
  3848. set active table
  3849. else isSplitter and alreadyGeneratedForThisGraph
  3850. return previous result
  3851. else
  3852. create transformed
  3853. }
  3854. */
  3855. void EclResourcer::doCheckRecursion(ResourceGraphInfo * graph, PointerArray & visited)
  3856. {
  3857. visited.append(graph);
  3858. ForEachItemIn(idxD, graph->dependsOn)
  3859. checkRecursion(graph->dependsOn.item(idxD).sourceGraph, visited);
  3860. ForEachItemIn(idxS, graph->sources)
  3861. checkRecursion(graph->sources.item(idxS).sourceGraph, visited);
  3862. visited.pop();
  3863. }
  3864. void EclResourcer::checkRecursion(ResourceGraphInfo * graph, PointerArray & visited)
  3865. {
  3866. if (visited.find(graph) != NotFound)
  3867. throwUnexpected();
  3868. doCheckRecursion(graph, visited);
  3869. }
  3870. void EclResourcer::checkRecursion(ResourceGraphInfo * graph)
  3871. {
  3872. PointerArray visited;
  3873. doCheckRecursion(graph, visited);
  3874. }
  3875. IHqlExpression * EclResourcer::createResourced(IHqlExpression * expr, ResourceGraphInfo * ownerGraph, bool expandInParent, bool defineSideEffect)
  3876. {
  3877. ResourcerInfo * info = queryResourceInfo(expr);
  3878. if (!info || !info->containsActivity)
  3879. return replaceResourcedReferences(info, expr);
  3880. if (!info->isActivity)
  3881. {
  3882. assertex(!defineSideEffect);
  3883. HqlExprArray args;
  3884. bool same = true;
  3885. ForEachChild(idx, expr)
  3886. {
  3887. IHqlExpression * cur = expr->queryChild(idx);
  3888. IHqlExpression * curResourced = createResourced(cur, ownerGraph, expandInParent, false);
  3889. args.append(*curResourced);
  3890. if (cur != curResourced)
  3891. same = false;
  3892. }
  3893. if (same)
  3894. return LINK(expr);
  3895. return expr->clone(args);
  3896. }
  3897. if (info->graph != ownerGraph)
  3898. {
  3899. assertex(!defineSideEffect);
  3900. bool isShared = options.optimizeSharedInputs && ownerGraph && ownerGraph->isSharedInput(expr);
  3901. if (isShared)
  3902. {
  3903. IHqlExpression * mapped = ownerGraph->queryMappedSharedInput(expr->queryBody());
  3904. if (mapped)
  3905. return LINK(mapped);
  3906. }
  3907. IHqlExpression * source;
  3908. if (info->expandRatherThanSpill(true))
  3909. {
  3910. bool expandChildInParent = options.minimiseSpills ? expandInParent : true;
  3911. OwnedHqlExpr resourced = doCreateResourced(expr, ownerGraph, expandChildInParent, false);
  3912. if (queryAddUniqueToActivity(resourced))
  3913. source = appendUniqueAttr(resourced);
  3914. else
  3915. source = LINK(resourced);
  3916. }
  3917. else
  3918. {
  3919. if (!expr->isAction())
  3920. {
  3921. OwnedHqlExpr reason;
  3922. if (ownerGraph && options.checkResources())
  3923. {
  3924. StringBuffer reasonText;
  3925. ownerGraph->getMergeFailReason(reasonText, info->graph, *resourceLimit);
  3926. if (reasonText.length())
  3927. {
  3928. reasonText.insert(0, "Resource limit spill: ");
  3929. reason.setown(createAttribute(_spillReason_Atom, createConstant(reasonText.str())));
  3930. }
  3931. }
  3932. source = info->createSpilledRead(reason);
  3933. }
  3934. else
  3935. {
  3936. IHqlExpression * uid = info->transformed->queryProperty(_uid_Atom);
  3937. source = createValue(no_callsideeffect, makeVoidType(), LINK(uid));
  3938. //source = LINK(info->transformed);
  3939. }
  3940. }
  3941. if (isShared)
  3942. {
  3943. source = createDatasetF(no_split, source, createAttribute(balancedAtom), createUniqueId(), NULL);
  3944. ownerGraph->addSharedInput(expr->queryBody(), source);
  3945. }
  3946. return source;
  3947. }
  3948. if (!expandInParent && info->transformed && info->isSplit())
  3949. {
  3950. return LINK(info->transformed);
  3951. }
  3952. OwnedHqlExpr resourced = doCreateResourced(expr, ownerGraph, expandInParent, defineSideEffect);
  3953. if (queryAddUniqueToActivity(resourced))// && !resourced->hasProperty(_internal_Atom))
  3954. resourced.setown(appendUniqueAttr(resourced));
  3955. if (!expandInParent)
  3956. {
  3957. info->transformed = resourced;
  3958. }
  3959. return resourced.getClear();
  3960. }
  3961. void EclResourcer::createResourced(ResourceGraphInfo * graph, HqlExprArray & transformed)
  3962. {
  3963. if (graph->createdGraph || graph->isDead)
  3964. return;
  3965. if (!graph->containsActiveSinks() && (!graph->hasConditionSource))
  3966. return;
  3967. #ifdef VERIFY_RESOURCING
  3968. checkRecursion(graph);
  3969. #endif
  3970. // DBGLOG("Prepare to CreateResourced(%p)", graph);
  3971. if (graph->startedGeneratingResourced)
  3972. throwError(HQLWRN_RecursiveDependendencies);
  3973. graph->startedGeneratingResourced = true;
  3974. ForEachItemIn(idxD, graph->dependsOn)
  3975. createResourced(graph->dependsOn.item(idxD).sourceGraph, transformed);
  3976. ForEachItemIn(idxS, graph->sources)
  3977. createResourced(graph->sources.item(idxS).sourceGraph, transformed);
  3978. // DBGLOG("Create resourced %p", graph);
  3979. //First generate the graphs for all the unconditional sinks
  3980. HqlExprArray args;
  3981. ForEachItemIn(idx, graph->sinks)
  3982. {
  3983. ResourceGraphLink & sink = graph->sinks.item(idx);
  3984. IHqlExpression * sinkNode = sink.sourceNode;
  3985. ResourcerInfo * info = queryResourceInfo(sinkNode);
  3986. //If graph is unconditional, any condition sinks are forced to be generated (and spilt)
  3987. if (!info->transformed)
  3988. {
  3989. // if it is a spiller, then it will be generated from another sink
  3990. if (!info->isExternalSpill())
  3991. {
  3992. IHqlExpression * resourced = createResourced(sinkNode, graph, false, sinkNode->isAction() && sink.sinkGraph);
  3993. assertex(info->transformed);
  3994. args.append(*resourced);
  3995. }
  3996. }
  3997. }
  3998. ForEachItemIn(i2, graph->sinks)
  3999. {
  4000. ResourceGraphLink & sink = graph->sinks.item(i2);
  4001. IHqlExpression * sinkNode = sink.sourceNode;
  4002. ResourcerInfo * info = queryResourceInfo(sinkNode);
  4003. IHqlExpression * splitter = info->splitterOutput;
  4004. if (splitter && !args.contains(*splitter))
  4005. args.append(*LINK(splitter));
  4006. }
  4007. if (args.ordinality() == 0)
  4008. graph->isDead = true;
  4009. else
  4010. {
  4011. if (options.useGraphResults)
  4012. args.append(*createAttribute(childAtom));
  4013. graph->createdGraph.setown(createValue(no_subgraph, makeVoidType(), args));
  4014. transformed.append(*LINK(graph->createdGraph));
  4015. }
  4016. }
  4017. void EclResourcer::inheritRedundantDependencies(ResourceGraphInfo * thisGraph)
  4018. {
  4019. if (thisGraph->inheritedExpandedDependencies)
  4020. return;
  4021. thisGraph->inheritedExpandedDependencies = true;
  4022. ForEachItemIn(idx, thisGraph->sources)
  4023. {
  4024. ResourceGraphLink & cur = thisGraph->sources.item(idx);
  4025. if (cur.isRedundantLink())
  4026. {
  4027. inheritRedundantDependencies(cur.sourceGraph);
  4028. ForEachItemIn(i, cur.sourceGraph->dependsOn)
  4029. {
  4030. ResourceGraphLink & curDepend = cur.sourceGraph->dependsOn.item(i);
  4031. ResourceGraphLink * link = new ResourceGraphDependencyLink(curDepend.sourceGraph, curDepend.sourceNode, thisGraph, cur.sinkNode);
  4032. thisGraph->dependsOn.append(*link);
  4033. links.append(*link);
  4034. }
  4035. }
  4036. }
  4037. }
  4038. void EclResourcer::createResourced(HqlExprArray & transformed)
  4039. {
  4040. //Before removing null links (e.g., where the source graph is expanded inline), need to make sure
  4041. //dependencies are cloned, otherwise graphs can be generated in the wrong order
  4042. ForEachItemIn(idx1, graphs)
  4043. inheritRedundantDependencies(&graphs.item(idx1));
  4044. ForEachItemInRev(idx2, links)
  4045. {
  4046. ResourceGraphLink & cur = links.item(idx2);
  4047. if (cur.isRedundantLink())
  4048. removeLink(cur, true);
  4049. }
  4050. ForEachItemIn(idx3, graphs)
  4051. createResourced(&graphs.item(idx3), transformed);
  4052. }
  4053. static int compareGraphDepth(CInterface * * _l, CInterface * * _r)
  4054. {
  4055. ResourceGraphInfo * l = (ResourceGraphInfo *)*_l;
  4056. ResourceGraphInfo * r = (ResourceGraphInfo *)*_r;
  4057. return l->getDepth() - r->getDepth();
  4058. }
  4059. static int compareLinkDepth(CInterface * * _l, CInterface * * _r)
  4060. {
  4061. ResourceGraphLink * l = (ResourceGraphLink *)*_l;
  4062. ResourceGraphLink * r = (ResourceGraphLink *)*_r;
  4063. int diff = l->sourceGraph->getDepth() - r->sourceGraph->getDepth();
  4064. if (diff) return diff;
  4065. if (l->sinkGraph)
  4066. if (r->sinkGraph)
  4067. return l->sinkGraph->getDepth() - r->sinkGraph->getDepth();
  4068. else
  4069. return -1;
  4070. else
  4071. if (r->sinkGraph)
  4072. return +1;
  4073. else
  4074. return 0;
  4075. }
  4076. void EclResourcer::display(StringBuffer & out)
  4077. {
  4078. CIArrayOf<ResourceGraphInfo> sortedGraphs;
  4079. ForEachItemIn(j1, graphs)
  4080. sortedGraphs.append(OLINK(graphs.item(j1)));
  4081. sortedGraphs.sort(compareGraphDepth);
  4082. out.append("Graphs:\n");
  4083. ForEachItemIn(i, sortedGraphs)
  4084. {
  4085. ResourceGraphInfo & cur = sortedGraphs.item(i);
  4086. out.appendf("%d: depth(%d) uncond(%d) cond(%d) %s {%p}\n", i, cur.getDepth(), cur.isUnconditional, cur.hasConditionSource, cur.isDead ? "dead" : "", &cur);
  4087. ForEachItemIn(j, cur.sources)
  4088. {
  4089. ResourceGraphLink & link = cur.sources.item(j);
  4090. out.appendf(" Source: %p %s\n", link.sinkNode.get(), getOpString(link.sinkNode->getOperator()));
  4091. }
  4092. ForEachItemIn(k, cur.sinks)
  4093. {
  4094. ResourceGraphLink & link = cur.sinks.item(k);
  4095. IHqlExpression * sourceNode = link.sourceNode;
  4096. ResourcerInfo * sourceInfo = queryResourceInfo(sourceNode);
  4097. out.appendf(" Sink: %p %s cond(%d,%d) int(%d) ext(%d)\n", sourceNode, getOpString(sourceNode->getOperator()), sourceInfo->conditions.ordinality(), sourceInfo->conditionSourceCount, sourceInfo->numInternalUses(), sourceInfo->numExternalUses);
  4098. }
  4099. ForEachItemIn(i3, dependencySource.graphs)
  4100. {
  4101. if (&dependencySource.graphs.item(i3) == &cur)
  4102. {
  4103. StringBuffer s;
  4104. toECL(&dependencySource.search.item(i3), s);
  4105. out.appendf(" Creates: %s\n", s.str());
  4106. }
  4107. }
  4108. }
  4109. out.append("Links:\n");
  4110. CIArrayOf<ResourceGraphLink> sortedLinks;
  4111. ForEachItemIn(j2, links)
  4112. sortedLinks.append(OLINK(links.item(j2)));
  4113. sortedLinks.sort(compareLinkDepth);
  4114. ForEachItemIn(i2, sortedLinks)
  4115. {
  4116. ResourceGraphLink & link = sortedLinks.item(i2);
  4117. unsigned len = out.length();
  4118. out.appendf(" Source: %d %s", sortedGraphs.find(*link.sourceGraph), getOpString(link.sourceNode->getOperator()));
  4119. if (link.sinkNode)
  4120. {
  4121. out.padTo(len+30);
  4122. out.appendf(" Sink: %d %s", sortedGraphs.find(*link.sinkGraph), getOpString(link.sinkNode->getOperator()));
  4123. }
  4124. if (link.linkKind == ConditionalLink)
  4125. out.append(" <conditional>");
  4126. else if (link.linkKind == SequenceLink)
  4127. out.append(" <sequence>");
  4128. out.newline();
  4129. }
  4130. }
  4131. void EclResourcer::trace()
  4132. {
  4133. StringBuffer s;
  4134. display(s);
  4135. DBGLOG("%s", s.str());
  4136. }
  4137. //---------------------------------------------------------------------------
  4138. void EclResourcer::resourceGraph(HqlExprArray & exprs, HqlExprArray & transformed)
  4139. {
  4140. //NB: This only resources a single level of queries. SubQueries should be resourced in a separate
  4141. //pass so that commonality between different activities/subgraphs isn't introduced/messed up.
  4142. findSplitPoints(exprs);
  4143. createInitialGraphs(exprs);
  4144. markConditions(exprs);
  4145. if (options.checkResources())
  4146. resourceSubGraphs(exprs);
  4147. addDependencies(exprs);
  4148. #ifdef TRACE_RESOURCING
  4149. trace();
  4150. #endif
  4151. mergeSubGraphs();
  4152. #ifdef TRACE_RESOURCING
  4153. trace();
  4154. #endif
  4155. spotUnbalancedSplitters(exprs);
  4156. if (options.optimizeSharedInputs)
  4157. spotSharedInputs();
  4158. if (spotThroughAggregate)
  4159. optimizeAggregates();
  4160. moveExternalSpillPoints();
  4161. createResourced(transformed);
  4162. }
  4163. void EclResourcer::resourceRemoteGraph(HqlExprArray & exprs, HqlExprArray & transformed)
  4164. {
  4165. //NB: This only resources a single level of queries. SubQueries should be resourced in a separate
  4166. //pass so that commonality between different activities/subgraphs isn't introduced/messed up.
  4167. findSplitPoints(exprs);
  4168. createInitialRemoteGraphs(exprs);
  4169. markConditions(exprs);
  4170. addDependencies(exprs);
  4171. #ifdef TRACE_RESOURCING
  4172. trace();
  4173. #endif
  4174. mergeSubGraphs();
  4175. #ifdef TRACE_RESOURCING
  4176. trace();
  4177. #endif
  4178. createResourced(transformed);
  4179. }
  4180. //---------------------------------------------------------------------------
  4181. void expandLists(HqlExprArray & args, IHqlExpression * expr)
  4182. {
  4183. switch (expr->getOperator())
  4184. {
  4185. case no_comma:
  4186. case no_compound:
  4187. case no_parallel:
  4188. case no_actionlist:
  4189. // for the moment, expand root parallel nodes, it generates much better code.
  4190. // I should really come up with a better way of implementing sequential/parallel.
  4191. {
  4192. ForEachChild(idx, expr)
  4193. expandLists(args, expr->queryChild(idx));
  4194. break;
  4195. }
  4196. default:
  4197. args.append(*LINK(expr));
  4198. break;
  4199. }
  4200. }
  4201. IHqlExpression * resourceThorGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize, IHqlExpression * graphIdExpr)
  4202. {
  4203. HqlExprArray transformed;
  4204. {
  4205. EclResourcer resourcer(translator.queryErrors(), translator.wu(), targetClusterType, clusterSize, translator.queryOptions());
  4206. if (graphIdExpr)
  4207. resourcer.setNewChildQuery(graphIdExpr, 0);
  4208. HqlExprArray exprs;
  4209. expandLists(exprs, expr);
  4210. resourcer.resourceGraph(exprs, transformed);
  4211. }
  4212. hoistNestedCompound(translator, transformed);
  4213. return createActionList(transformed);
  4214. }
  4215. static IHqlExpression * doResourceGraph(HqlCppTranslator & translator, HqlExprCopyArray * activeRows, IHqlExpression * expr,
  4216. ClusterType targetClusterType, unsigned clusterSize,
  4217. IHqlExpression * graphIdExpr, unsigned * numResults, bool isChild, bool useGraphResults)
  4218. {
  4219. HqlExprArray transformed;
  4220. {
  4221. EclResourcer resourcer(translator.queryErrors(), translator.wu(), targetClusterType, clusterSize, translator.queryOptions());
  4222. if (isChild)
  4223. resourcer.setChildQuery(true);
  4224. resourcer.setNewChildQuery(graphIdExpr, *numResults);
  4225. resourcer.setUseGraphResults(useGraphResults);
  4226. if (activeRows)
  4227. resourcer.tagActiveCursors(*activeRows);
  4228. HqlExprArray exprs;
  4229. expandLists(exprs, expr);
  4230. resourcer.resourceGraph(exprs, transformed);
  4231. *numResults = resourcer.numGraphResults();
  4232. }
  4233. hoistNestedCompound(translator, transformed);
  4234. return createActionList(transformed);
  4235. }
  4236. IHqlExpression * resourceLibraryGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize, IHqlExpression * graphIdExpr, unsigned * numResults)
  4237. {
  4238. return doResourceGraph(translator, NULL, expr, targetClusterType, clusterSize, graphIdExpr, numResults, false, true); //?? what value for isChild (e.g., thor library call). Need to gen twice?
  4239. }
  4240. IHqlExpression * resourceNewChildGraph(HqlCppTranslator & translator, HqlExprCopyArray & activeRows, IHqlExpression * expr, ClusterType targetClusterType, IHqlExpression * graphIdExpr, unsigned * numResults)
  4241. {
  4242. return doResourceGraph(translator, &activeRows, expr, targetClusterType, 0, graphIdExpr, numResults, true, true);
  4243. }
  4244. IHqlExpression * resourceLoopGraph(HqlCppTranslator & translator, HqlExprCopyArray & activeRows, IHqlExpression * expr, ClusterType targetClusterType, IHqlExpression * graphIdExpr, unsigned * numResults, bool insideChildQuery)
  4245. {
  4246. return doResourceGraph(translator, &activeRows, expr, targetClusterType, 0, graphIdExpr, numResults, insideChildQuery, true);
  4247. }
  4248. IHqlExpression * resourceRemoteGraph(HqlCppTranslator & translator, IHqlExpression * expr, ClusterType targetClusterType, unsigned clusterSize)
  4249. {
  4250. HqlExprArray transformed;
  4251. {
  4252. EclResourcer resourcer(translator.queryErrors(), translator.wu(), targetClusterType, clusterSize, translator.queryOptions());
  4253. HqlExprArray exprs;
  4254. expandLists(exprs, expr);
  4255. resourcer.resourceRemoteGraph(exprs, transformed);
  4256. }
  4257. hoistNestedCompound(translator, transformed);
  4258. return createActionList(transformed);
  4259. }
  4260. /*
  4261. Conditions:
  4262. They are nasty. We process the tree in two passes. First we tag anything which must be evaluated, and
  4263. save a list of condition statements to process later.
  4264. Second pass we tag conditionals.
  4265. a) all left and right branches of a condition are tagged. [conditionSourceCount]
  4266. b) all conditional expressions are tagged with the conditions they are evaluated for.
  4267. [if the condition lists match then it should be possible to merge the graphs]
  4268. c) The spill count for an node should ignore the number of links from conditional graphs,
  4269. but should add the number of conditions.
  4270. d) if (a, b(f1) +b(f2), c) needs to link b twice though!
  4271. */
  4272. /*
  4273. This transformer converts spill activities to no_dataset/no_output, and also converts splitters of splitters into
  4274. a single splitter.
  4275. */
  4276. class SpillActivityTransformer : public NewHqlTransformer
  4277. {
  4278. public:
  4279. SpillActivityTransformer();
  4280. protected:
  4281. virtual void analyseExpr(IHqlExpression * expr);
  4282. virtual IHqlExpression * createTransformed(IHqlExpression * expr);
  4283. bool isUnbalanced(IHqlExpression * body)
  4284. {
  4285. ANewTransformInfo * info = queryTransformExtra(body);
  4286. return info->spareByte1 != 0;
  4287. }
  4288. void setUnbalanced(IHqlExpression * body)
  4289. {
  4290. ANewTransformInfo * info = queryTransformExtra(body);
  4291. info->spareByte1 = true;
  4292. }
  4293. };
  4294. static HqlTransformerInfo spillActivityTransformerInfo("SpillActivityTransformer");
  4295. SpillActivityTransformer::SpillActivityTransformer()
  4296. : NewHqlTransformer(spillActivityTransformerInfo)
  4297. {
  4298. }
  4299. void SpillActivityTransformer::analyseExpr(IHqlExpression * expr)
  4300. {
  4301. IHqlExpression * body = expr->queryBody();
  4302. if (alreadyVisited(body))
  4303. return;
  4304. if (body->getOperator() == no_split)
  4305. {
  4306. IHqlExpression * input = body->queryChild(0);
  4307. if (input->getOperator() == no_split)
  4308. {
  4309. loop
  4310. {
  4311. IHqlExpression * cur = input->queryChild(0);
  4312. if (cur->getOperator() != no_split)
  4313. break;
  4314. input = cur;
  4315. }
  4316. if (!body->hasProperty(balancedAtom))
  4317. setUnbalanced(input->queryBody());
  4318. }
  4319. }
  4320. NewHqlTransformer::analyseExpr(expr);
  4321. }
  4322. IHqlExpression * SpillActivityTransformer::createTransformed(IHqlExpression * expr)
  4323. {
  4324. IHqlExpression * annotation = queryTransformAnnotation(expr);
  4325. if (annotation)
  4326. return annotation;
  4327. switch (expr->getOperator())
  4328. {
  4329. case no_split:
  4330. {
  4331. IHqlExpression * input = expr->queryChild(0);
  4332. if (input->getOperator() == no_split)
  4333. return transform(input);
  4334. OwnedHqlExpr transformed = NewHqlTransformer::createTransformed(expr);
  4335. if (transformed->hasProperty(balancedAtom) && isUnbalanced(expr))
  4336. return removeProperty(transformed, balancedAtom);
  4337. return transformed.getClear();
  4338. }
  4339. case no_writespill:
  4340. {
  4341. HqlExprArray args;
  4342. transformChildren(expr, args);
  4343. return createValue(no_output, makeVoidType(), args);
  4344. }
  4345. case no_commonspill:
  4346. return transform(expr->queryChild(0));
  4347. case no_readspill:
  4348. {
  4349. OwnedHqlExpr ds = transform(expr->queryChild(0));
  4350. HqlExprArray args;
  4351. args.append(*transform(expr->queryChild(1)));
  4352. args.append(*LINK(ds->queryRecord()));
  4353. ForEachChildFrom(i, expr, 2)
  4354. {
  4355. IHqlExpression * cur = expr->queryChild(i);
  4356. args.append(*transform(cur));
  4357. }
  4358. IHqlExpression * recordCountAttr = queryRecordCountInfo(expr);
  4359. if (recordCountAttr)
  4360. args.append(*LINK(recordCountAttr));
  4361. return createDataset(no_table, args);
  4362. }
  4363. }
  4364. return NewHqlTransformer::createTransformed(expr);
  4365. }
  4366. IHqlExpression * convertSpillsToActivities(IHqlExpression * expr)
  4367. {
  4368. SpillActivityTransformer transformer;
  4369. transformer.analyse(expr, 0);
  4370. return transformer.transformRoot(expr);
  4371. }