hqlresource.cpp 166 KB

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