hqlresource.cpp 155 KB

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