OpenMPOpt.cpp 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171
  1. //===-- IPO/OpenMPOpt.cpp - Collection of OpenMP specific optimizations ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // OpenMP specific optimizations:
  10. //
  11. // - Deduplication of runtime calls, e.g., omp_get_thread_num.
  12. // - Replacing globalized device memory with stack memory.
  13. // - Replacing globalized device memory with shared memory.
  14. // - Parallel region merging.
  15. // - Transforming generic-mode device kernels to SPMD mode.
  16. // - Specializing the state machine for generic-mode device kernels.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/Transforms/IPO/OpenMPOpt.h"
  20. #include "llvm/ADT/EnumeratedArray.h"
  21. #include "llvm/ADT/PostOrderIterator.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Analysis/CallGraph.h"
  26. #include "llvm/Analysis/CallGraphSCCPass.h"
  27. #include "llvm/Analysis/MemoryLocation.h"
  28. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/Frontend/OpenMP/OMPConstants.h"
  31. #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
  32. #include "llvm/IR/Assumptions.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DiagnosticInfo.h"
  35. #include "llvm/IR/GlobalValue.h"
  36. #include "llvm/IR/GlobalVariable.h"
  37. #include "llvm/IR/Instruction.h"
  38. #include "llvm/IR/Instructions.h"
  39. #include "llvm/IR/IntrinsicInst.h"
  40. #include "llvm/IR/IntrinsicsAMDGPU.h"
  41. #include "llvm/IR/IntrinsicsNVPTX.h"
  42. #include "llvm/IR/LLVMContext.h"
  43. #include "llvm/InitializePasses.h"
  44. #include "llvm/Support/CommandLine.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Transforms/IPO.h"
  47. #include "llvm/Transforms/IPO/Attributor.h"
  48. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  49. #include "llvm/Transforms/Utils/CallGraphUpdater.h"
  50. #include "llvm/Transforms/Utils/CodeExtractor.h"
  51. #include <algorithm>
  52. using namespace llvm;
  53. using namespace omp;
  54. #define DEBUG_TYPE "openmp-opt"
  55. static cl::opt<bool> DisableOpenMPOptimizations(
  56. "openmp-opt-disable", cl::ZeroOrMore,
  57. cl::desc("Disable OpenMP specific optimizations."), cl::Hidden,
  58. cl::init(false));
  59. static cl::opt<bool> EnableParallelRegionMerging(
  60. "openmp-opt-enable-merging", cl::ZeroOrMore,
  61. cl::desc("Enable the OpenMP region merging optimization."), cl::Hidden,
  62. cl::init(false));
  63. static cl::opt<bool>
  64. DisableInternalization("openmp-opt-disable-internalization", cl::ZeroOrMore,
  65. cl::desc("Disable function internalization."),
  66. cl::Hidden, cl::init(false));
  67. static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false),
  68. cl::Hidden);
  69. static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels",
  70. cl::init(false), cl::Hidden);
  71. static cl::opt<bool> HideMemoryTransferLatency(
  72. "openmp-hide-memory-transfer-latency",
  73. cl::desc("[WIP] Tries to hide the latency of host to device memory"
  74. " transfers"),
  75. cl::Hidden, cl::init(false));
  76. static cl::opt<bool> DisableOpenMPOptDeglobalization(
  77. "openmp-opt-disable-deglobalization", cl::ZeroOrMore,
  78. cl::desc("Disable OpenMP optimizations involving deglobalization."),
  79. cl::Hidden, cl::init(false));
  80. static cl::opt<bool> DisableOpenMPOptSPMDization(
  81. "openmp-opt-disable-spmdization", cl::ZeroOrMore,
  82. cl::desc("Disable OpenMP optimizations involving SPMD-ization."),
  83. cl::Hidden, cl::init(false));
  84. static cl::opt<bool> DisableOpenMPOptFolding(
  85. "openmp-opt-disable-folding", cl::ZeroOrMore,
  86. cl::desc("Disable OpenMP optimizations involving folding."), cl::Hidden,
  87. cl::init(false));
  88. static cl::opt<bool> DisableOpenMPOptStateMachineRewrite(
  89. "openmp-opt-disable-state-machine-rewrite", cl::ZeroOrMore,
  90. cl::desc("Disable OpenMP optimizations that replace the state machine."),
  91. cl::Hidden, cl::init(false));
  92. static cl::opt<bool> DisableOpenMPOptBarrierElimination(
  93. "openmp-opt-disable-barrier-elimination", cl::ZeroOrMore,
  94. cl::desc("Disable OpenMP optimizations that eliminate barriers."),
  95. cl::Hidden, cl::init(false));
  96. static cl::opt<bool> PrintModuleAfterOptimizations(
  97. "openmp-opt-print-module", cl::ZeroOrMore,
  98. cl::desc("Print the current module after OpenMP optimizations."),
  99. cl::Hidden, cl::init(false));
  100. static cl::opt<bool> AlwaysInlineDeviceFunctions(
  101. "openmp-opt-inline-device", cl::ZeroOrMore,
  102. cl::desc("Inline all applicible functions on the device."), cl::Hidden,
  103. cl::init(false));
  104. static cl::opt<bool>
  105. EnableVerboseRemarks("openmp-opt-verbose-remarks", cl::ZeroOrMore,
  106. cl::desc("Enables more verbose remarks."), cl::Hidden,
  107. cl::init(false));
  108. static cl::opt<unsigned>
  109. SetFixpointIterations("openmp-opt-max-iterations", cl::Hidden,
  110. cl::desc("Maximal number of attributor iterations."),
  111. cl::init(256));
  112. STATISTIC(NumOpenMPRuntimeCallsDeduplicated,
  113. "Number of OpenMP runtime calls deduplicated");
  114. STATISTIC(NumOpenMPParallelRegionsDeleted,
  115. "Number of OpenMP parallel regions deleted");
  116. STATISTIC(NumOpenMPRuntimeFunctionsIdentified,
  117. "Number of OpenMP runtime functions identified");
  118. STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified,
  119. "Number of OpenMP runtime function uses identified");
  120. STATISTIC(NumOpenMPTargetRegionKernels,
  121. "Number of OpenMP target region entry points (=kernels) identified");
  122. STATISTIC(NumOpenMPTargetRegionKernelsSPMD,
  123. "Number of OpenMP target region entry points (=kernels) executed in "
  124. "SPMD-mode instead of generic-mode");
  125. STATISTIC(NumOpenMPTargetRegionKernelsWithoutStateMachine,
  126. "Number of OpenMP target region entry points (=kernels) executed in "
  127. "generic-mode without a state machines");
  128. STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback,
  129. "Number of OpenMP target region entry points (=kernels) executed in "
  130. "generic-mode with customized state machines with fallback");
  131. STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback,
  132. "Number of OpenMP target region entry points (=kernels) executed in "
  133. "generic-mode with customized state machines without fallback");
  134. STATISTIC(
  135. NumOpenMPParallelRegionsReplacedInGPUStateMachine,
  136. "Number of OpenMP parallel regions replaced with ID in GPU state machines");
  137. STATISTIC(NumOpenMPParallelRegionsMerged,
  138. "Number of OpenMP parallel regions merged");
  139. STATISTIC(NumBytesMovedToSharedMemory,
  140. "Amount of memory pushed to shared memory");
  141. STATISTIC(NumBarriersEliminated, "Number of redundant barriers eliminated");
  142. #if !defined(NDEBUG)
  143. static constexpr auto TAG = "[" DEBUG_TYPE "]";
  144. #endif
  145. namespace {
  146. struct AAHeapToShared;
  147. struct AAICVTracker;
  148. /// OpenMP specific information. For now, stores RFIs and ICVs also needed for
  149. /// Attributor runs.
  150. struct OMPInformationCache : public InformationCache {
  151. OMPInformationCache(Module &M, AnalysisGetter &AG,
  152. BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC,
  153. KernelSet &Kernels)
  154. : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M),
  155. Kernels(Kernels) {
  156. OMPBuilder.initialize();
  157. initializeRuntimeFunctions();
  158. initializeInternalControlVars();
  159. }
  160. /// Generic information that describes an internal control variable.
  161. struct InternalControlVarInfo {
  162. /// The kind, as described by InternalControlVar enum.
  163. InternalControlVar Kind;
  164. /// The name of the ICV.
  165. StringRef Name;
  166. /// Environment variable associated with this ICV.
  167. StringRef EnvVarName;
  168. /// Initial value kind.
  169. ICVInitValue InitKind;
  170. /// Initial value.
  171. ConstantInt *InitValue;
  172. /// Setter RTL function associated with this ICV.
  173. RuntimeFunction Setter;
  174. /// Getter RTL function associated with this ICV.
  175. RuntimeFunction Getter;
  176. /// RTL Function corresponding to the override clause of this ICV
  177. RuntimeFunction Clause;
  178. };
  179. /// Generic information that describes a runtime function
  180. struct RuntimeFunctionInfo {
  181. /// The kind, as described by the RuntimeFunction enum.
  182. RuntimeFunction Kind;
  183. /// The name of the function.
  184. StringRef Name;
  185. /// Flag to indicate a variadic function.
  186. bool IsVarArg;
  187. /// The return type of the function.
  188. Type *ReturnType;
  189. /// The argument types of the function.
  190. SmallVector<Type *, 8> ArgumentTypes;
  191. /// The declaration if available.
  192. Function *Declaration = nullptr;
  193. /// Uses of this runtime function per function containing the use.
  194. using UseVector = SmallVector<Use *, 16>;
  195. /// Clear UsesMap for runtime function.
  196. void clearUsesMap() { UsesMap.clear(); }
  197. /// Boolean conversion that is true if the runtime function was found.
  198. operator bool() const { return Declaration; }
  199. /// Return the vector of uses in function \p F.
  200. UseVector &getOrCreateUseVector(Function *F) {
  201. std::shared_ptr<UseVector> &UV = UsesMap[F];
  202. if (!UV)
  203. UV = std::make_shared<UseVector>();
  204. return *UV;
  205. }
  206. /// Return the vector of uses in function \p F or `nullptr` if there are
  207. /// none.
  208. const UseVector *getUseVector(Function &F) const {
  209. auto I = UsesMap.find(&F);
  210. if (I != UsesMap.end())
  211. return I->second.get();
  212. return nullptr;
  213. }
  214. /// Return how many functions contain uses of this runtime function.
  215. size_t getNumFunctionsWithUses() const { return UsesMap.size(); }
  216. /// Return the number of arguments (or the minimal number for variadic
  217. /// functions).
  218. size_t getNumArgs() const { return ArgumentTypes.size(); }
  219. /// Run the callback \p CB on each use and forget the use if the result is
  220. /// true. The callback will be fed the function in which the use was
  221. /// encountered as second argument.
  222. void foreachUse(SmallVectorImpl<Function *> &SCC,
  223. function_ref<bool(Use &, Function &)> CB) {
  224. for (Function *F : SCC)
  225. foreachUse(CB, F);
  226. }
  227. /// Run the callback \p CB on each use within the function \p F and forget
  228. /// the use if the result is true.
  229. void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) {
  230. SmallVector<unsigned, 8> ToBeDeleted;
  231. ToBeDeleted.clear();
  232. unsigned Idx = 0;
  233. UseVector &UV = getOrCreateUseVector(F);
  234. for (Use *U : UV) {
  235. if (CB(*U, *F))
  236. ToBeDeleted.push_back(Idx);
  237. ++Idx;
  238. }
  239. // Remove the to-be-deleted indices in reverse order as prior
  240. // modifications will not modify the smaller indices.
  241. while (!ToBeDeleted.empty()) {
  242. unsigned Idx = ToBeDeleted.pop_back_val();
  243. UV[Idx] = UV.back();
  244. UV.pop_back();
  245. }
  246. }
  247. private:
  248. /// Map from functions to all uses of this runtime function contained in
  249. /// them.
  250. DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap;
  251. public:
  252. /// Iterators for the uses of this runtime function.
  253. decltype(UsesMap)::iterator begin() { return UsesMap.begin(); }
  254. decltype(UsesMap)::iterator end() { return UsesMap.end(); }
  255. };
  256. /// An OpenMP-IR-Builder instance
  257. OpenMPIRBuilder OMPBuilder;
  258. /// Map from runtime function kind to the runtime function description.
  259. EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction,
  260. RuntimeFunction::OMPRTL___last>
  261. RFIs;
  262. /// Map from function declarations/definitions to their runtime enum type.
  263. DenseMap<Function *, RuntimeFunction> RuntimeFunctionIDMap;
  264. /// Map from ICV kind to the ICV description.
  265. EnumeratedArray<InternalControlVarInfo, InternalControlVar,
  266. InternalControlVar::ICV___last>
  267. ICVs;
  268. /// Helper to initialize all internal control variable information for those
  269. /// defined in OMPKinds.def.
  270. void initializeInternalControlVars() {
  271. #define ICV_RT_SET(_Name, RTL) \
  272. { \
  273. auto &ICV = ICVs[_Name]; \
  274. ICV.Setter = RTL; \
  275. }
  276. #define ICV_RT_GET(Name, RTL) \
  277. { \
  278. auto &ICV = ICVs[Name]; \
  279. ICV.Getter = RTL; \
  280. }
  281. #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init) \
  282. { \
  283. auto &ICV = ICVs[Enum]; \
  284. ICV.Name = _Name; \
  285. ICV.Kind = Enum; \
  286. ICV.InitKind = Init; \
  287. ICV.EnvVarName = _EnvVarName; \
  288. switch (ICV.InitKind) { \
  289. case ICV_IMPLEMENTATION_DEFINED: \
  290. ICV.InitValue = nullptr; \
  291. break; \
  292. case ICV_ZERO: \
  293. ICV.InitValue = ConstantInt::get( \
  294. Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0); \
  295. break; \
  296. case ICV_FALSE: \
  297. ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext()); \
  298. break; \
  299. case ICV_LAST: \
  300. break; \
  301. } \
  302. }
  303. #include "llvm/Frontend/OpenMP/OMPKinds.def"
  304. }
  305. /// Returns true if the function declaration \p F matches the runtime
  306. /// function types, that is, return type \p RTFRetType, and argument types
  307. /// \p RTFArgTypes.
  308. static bool declMatchesRTFTypes(Function *F, Type *RTFRetType,
  309. SmallVector<Type *, 8> &RTFArgTypes) {
  310. // TODO: We should output information to the user (under debug output
  311. // and via remarks).
  312. if (!F)
  313. return false;
  314. if (F->getReturnType() != RTFRetType)
  315. return false;
  316. if (F->arg_size() != RTFArgTypes.size())
  317. return false;
  318. auto *RTFTyIt = RTFArgTypes.begin();
  319. for (Argument &Arg : F->args()) {
  320. if (Arg.getType() != *RTFTyIt)
  321. return false;
  322. ++RTFTyIt;
  323. }
  324. return true;
  325. }
  326. // Helper to collect all uses of the declaration in the UsesMap.
  327. unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) {
  328. unsigned NumUses = 0;
  329. if (!RFI.Declaration)
  330. return NumUses;
  331. OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration);
  332. if (CollectStats) {
  333. NumOpenMPRuntimeFunctionsIdentified += 1;
  334. NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses();
  335. }
  336. // TODO: We directly convert uses into proper calls and unknown uses.
  337. for (Use &U : RFI.Declaration->uses()) {
  338. if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) {
  339. if (ModuleSlice.count(UserI->getFunction())) {
  340. RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U);
  341. ++NumUses;
  342. }
  343. } else {
  344. RFI.getOrCreateUseVector(nullptr).push_back(&U);
  345. ++NumUses;
  346. }
  347. }
  348. return NumUses;
  349. }
  350. // Helper function to recollect uses of a runtime function.
  351. void recollectUsesForFunction(RuntimeFunction RTF) {
  352. auto &RFI = RFIs[RTF];
  353. RFI.clearUsesMap();
  354. collectUses(RFI, /*CollectStats*/ false);
  355. }
  356. // Helper function to recollect uses of all runtime functions.
  357. void recollectUses() {
  358. for (int Idx = 0; Idx < RFIs.size(); ++Idx)
  359. recollectUsesForFunction(static_cast<RuntimeFunction>(Idx));
  360. }
  361. // Helper function to inherit the calling convention of the function callee.
  362. void setCallingConvention(FunctionCallee Callee, CallInst *CI) {
  363. if (Function *Fn = dyn_cast<Function>(Callee.getCallee()))
  364. CI->setCallingConv(Fn->getCallingConv());
  365. }
  366. /// Helper to initialize all runtime function information for those defined
  367. /// in OpenMPKinds.def.
  368. void initializeRuntimeFunctions() {
  369. Module &M = *((*ModuleSlice.begin())->getParent());
  370. // Helper macros for handling __VA_ARGS__ in OMP_RTL
  371. #define OMP_TYPE(VarName, ...) \
  372. Type *VarName = OMPBuilder.VarName; \
  373. (void)VarName;
  374. #define OMP_ARRAY_TYPE(VarName, ...) \
  375. ArrayType *VarName##Ty = OMPBuilder.VarName##Ty; \
  376. (void)VarName##Ty; \
  377. PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy; \
  378. (void)VarName##PtrTy;
  379. #define OMP_FUNCTION_TYPE(VarName, ...) \
  380. FunctionType *VarName = OMPBuilder.VarName; \
  381. (void)VarName; \
  382. PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \
  383. (void)VarName##Ptr;
  384. #define OMP_STRUCT_TYPE(VarName, ...) \
  385. StructType *VarName = OMPBuilder.VarName; \
  386. (void)VarName; \
  387. PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \
  388. (void)VarName##Ptr;
  389. #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...) \
  390. { \
  391. SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__}); \
  392. Function *F = M.getFunction(_Name); \
  393. RTLFunctions.insert(F); \
  394. if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) { \
  395. RuntimeFunctionIDMap[F] = _Enum; \
  396. auto &RFI = RFIs[_Enum]; \
  397. RFI.Kind = _Enum; \
  398. RFI.Name = _Name; \
  399. RFI.IsVarArg = _IsVarArg; \
  400. RFI.ReturnType = OMPBuilder._ReturnType; \
  401. RFI.ArgumentTypes = std::move(ArgsTypes); \
  402. RFI.Declaration = F; \
  403. unsigned NumUses = collectUses(RFI); \
  404. (void)NumUses; \
  405. LLVM_DEBUG({ \
  406. dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not") \
  407. << " found\n"; \
  408. if (RFI.Declaration) \
  409. dbgs() << TAG << "-> got " << NumUses << " uses in " \
  410. << RFI.getNumFunctionsWithUses() \
  411. << " different functions.\n"; \
  412. }); \
  413. } \
  414. }
  415. #include "llvm/Frontend/OpenMP/OMPKinds.def"
  416. // Remove the `noinline` attribute from `__kmpc`, `_OMP::` and `omp_`
  417. // functions, except if `optnone` is present.
  418. if (isOpenMPDevice(M)) {
  419. for (Function &F : M) {
  420. for (StringRef Prefix : {"__kmpc", "_ZN4_OMP", "omp_"})
  421. if (F.hasFnAttribute(Attribute::NoInline) &&
  422. F.getName().startswith(Prefix) &&
  423. !F.hasFnAttribute(Attribute::OptimizeNone))
  424. F.removeFnAttr(Attribute::NoInline);
  425. }
  426. }
  427. // TODO: We should attach the attributes defined in OMPKinds.def.
  428. }
  429. /// Collection of known kernels (\see Kernel) in the module.
  430. KernelSet &Kernels;
  431. /// Collection of known OpenMP runtime functions..
  432. DenseSet<const Function *> RTLFunctions;
  433. };
  434. template <typename Ty, bool InsertInvalidates = true>
  435. struct BooleanStateWithSetVector : public BooleanState {
  436. bool contains(const Ty &Elem) const { return Set.contains(Elem); }
  437. bool insert(const Ty &Elem) {
  438. if (InsertInvalidates)
  439. BooleanState::indicatePessimisticFixpoint();
  440. return Set.insert(Elem);
  441. }
  442. const Ty &operator[](int Idx) const { return Set[Idx]; }
  443. bool operator==(const BooleanStateWithSetVector &RHS) const {
  444. return BooleanState::operator==(RHS) && Set == RHS.Set;
  445. }
  446. bool operator!=(const BooleanStateWithSetVector &RHS) const {
  447. return !(*this == RHS);
  448. }
  449. bool empty() const { return Set.empty(); }
  450. size_t size() const { return Set.size(); }
  451. /// "Clamp" this state with \p RHS.
  452. BooleanStateWithSetVector &operator^=(const BooleanStateWithSetVector &RHS) {
  453. BooleanState::operator^=(RHS);
  454. Set.insert(RHS.Set.begin(), RHS.Set.end());
  455. return *this;
  456. }
  457. private:
  458. /// A set to keep track of elements.
  459. SetVector<Ty> Set;
  460. public:
  461. typename decltype(Set)::iterator begin() { return Set.begin(); }
  462. typename decltype(Set)::iterator end() { return Set.end(); }
  463. typename decltype(Set)::const_iterator begin() const { return Set.begin(); }
  464. typename decltype(Set)::const_iterator end() const { return Set.end(); }
  465. };
  466. template <typename Ty, bool InsertInvalidates = true>
  467. using BooleanStateWithPtrSetVector =
  468. BooleanStateWithSetVector<Ty *, InsertInvalidates>;
  469. struct KernelInfoState : AbstractState {
  470. /// Flag to track if we reached a fixpoint.
  471. bool IsAtFixpoint = false;
  472. /// The parallel regions (identified by the outlined parallel functions) that
  473. /// can be reached from the associated function.
  474. BooleanStateWithPtrSetVector<Function, /* InsertInvalidates */ false>
  475. ReachedKnownParallelRegions;
  476. /// State to track what parallel region we might reach.
  477. BooleanStateWithPtrSetVector<CallBase> ReachedUnknownParallelRegions;
  478. /// State to track if we are in SPMD-mode, assumed or know, and why we decided
  479. /// we cannot be. If it is assumed, then RequiresFullRuntime should also be
  480. /// false.
  481. BooleanStateWithPtrSetVector<Instruction, false> SPMDCompatibilityTracker;
  482. /// The __kmpc_target_init call in this kernel, if any. If we find more than
  483. /// one we abort as the kernel is malformed.
  484. CallBase *KernelInitCB = nullptr;
  485. /// The __kmpc_target_deinit call in this kernel, if any. If we find more than
  486. /// one we abort as the kernel is malformed.
  487. CallBase *KernelDeinitCB = nullptr;
  488. /// Flag to indicate if the associated function is a kernel entry.
  489. bool IsKernelEntry = false;
  490. /// State to track what kernel entries can reach the associated function.
  491. BooleanStateWithPtrSetVector<Function, false> ReachingKernelEntries;
  492. /// State to indicate if we can track parallel level of the associated
  493. /// function. We will give up tracking if we encounter unknown caller or the
  494. /// caller is __kmpc_parallel_51.
  495. BooleanStateWithSetVector<uint8_t> ParallelLevels;
  496. /// Abstract State interface
  497. ///{
  498. KernelInfoState() {}
  499. KernelInfoState(bool BestState) {
  500. if (!BestState)
  501. indicatePessimisticFixpoint();
  502. }
  503. /// See AbstractState::isValidState(...)
  504. bool isValidState() const override { return true; }
  505. /// See AbstractState::isAtFixpoint(...)
  506. bool isAtFixpoint() const override { return IsAtFixpoint; }
  507. /// See AbstractState::indicatePessimisticFixpoint(...)
  508. ChangeStatus indicatePessimisticFixpoint() override {
  509. IsAtFixpoint = true;
  510. ReachingKernelEntries.indicatePessimisticFixpoint();
  511. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  512. ReachedKnownParallelRegions.indicatePessimisticFixpoint();
  513. ReachedUnknownParallelRegions.indicatePessimisticFixpoint();
  514. return ChangeStatus::CHANGED;
  515. }
  516. /// See AbstractState::indicateOptimisticFixpoint(...)
  517. ChangeStatus indicateOptimisticFixpoint() override {
  518. IsAtFixpoint = true;
  519. ReachingKernelEntries.indicateOptimisticFixpoint();
  520. SPMDCompatibilityTracker.indicateOptimisticFixpoint();
  521. ReachedKnownParallelRegions.indicateOptimisticFixpoint();
  522. ReachedUnknownParallelRegions.indicateOptimisticFixpoint();
  523. return ChangeStatus::UNCHANGED;
  524. }
  525. /// Return the assumed state
  526. KernelInfoState &getAssumed() { return *this; }
  527. const KernelInfoState &getAssumed() const { return *this; }
  528. bool operator==(const KernelInfoState &RHS) const {
  529. if (SPMDCompatibilityTracker != RHS.SPMDCompatibilityTracker)
  530. return false;
  531. if (ReachedKnownParallelRegions != RHS.ReachedKnownParallelRegions)
  532. return false;
  533. if (ReachedUnknownParallelRegions != RHS.ReachedUnknownParallelRegions)
  534. return false;
  535. if (ReachingKernelEntries != RHS.ReachingKernelEntries)
  536. return false;
  537. return true;
  538. }
  539. /// Returns true if this kernel contains any OpenMP parallel regions.
  540. bool mayContainParallelRegion() {
  541. return !ReachedKnownParallelRegions.empty() ||
  542. !ReachedUnknownParallelRegions.empty();
  543. }
  544. /// Return empty set as the best state of potential values.
  545. static KernelInfoState getBestState() { return KernelInfoState(true); }
  546. static KernelInfoState getBestState(KernelInfoState &KIS) {
  547. return getBestState();
  548. }
  549. /// Return full set as the worst state of potential values.
  550. static KernelInfoState getWorstState() { return KernelInfoState(false); }
  551. /// "Clamp" this state with \p KIS.
  552. KernelInfoState operator^=(const KernelInfoState &KIS) {
  553. // Do not merge two different _init and _deinit call sites.
  554. if (KIS.KernelInitCB) {
  555. if (KernelInitCB && KernelInitCB != KIS.KernelInitCB)
  556. llvm_unreachable("Kernel that calls another kernel violates OpenMP-Opt "
  557. "assumptions.");
  558. KernelInitCB = KIS.KernelInitCB;
  559. }
  560. if (KIS.KernelDeinitCB) {
  561. if (KernelDeinitCB && KernelDeinitCB != KIS.KernelDeinitCB)
  562. llvm_unreachable("Kernel that calls another kernel violates OpenMP-Opt "
  563. "assumptions.");
  564. KernelDeinitCB = KIS.KernelDeinitCB;
  565. }
  566. SPMDCompatibilityTracker ^= KIS.SPMDCompatibilityTracker;
  567. ReachedKnownParallelRegions ^= KIS.ReachedKnownParallelRegions;
  568. ReachedUnknownParallelRegions ^= KIS.ReachedUnknownParallelRegions;
  569. return *this;
  570. }
  571. KernelInfoState operator&=(const KernelInfoState &KIS) {
  572. return (*this ^= KIS);
  573. }
  574. ///}
  575. };
  576. /// Used to map the values physically (in the IR) stored in an offload
  577. /// array, to a vector in memory.
  578. struct OffloadArray {
  579. /// Physical array (in the IR).
  580. AllocaInst *Array = nullptr;
  581. /// Mapped values.
  582. SmallVector<Value *, 8> StoredValues;
  583. /// Last stores made in the offload array.
  584. SmallVector<StoreInst *, 8> LastAccesses;
  585. OffloadArray() = default;
  586. /// Initializes the OffloadArray with the values stored in \p Array before
  587. /// instruction \p Before is reached. Returns false if the initialization
  588. /// fails.
  589. /// This MUST be used immediately after the construction of the object.
  590. bool initialize(AllocaInst &Array, Instruction &Before) {
  591. if (!Array.getAllocatedType()->isArrayTy())
  592. return false;
  593. if (!getValues(Array, Before))
  594. return false;
  595. this->Array = &Array;
  596. return true;
  597. }
  598. static const unsigned DeviceIDArgNum = 1;
  599. static const unsigned BasePtrsArgNum = 3;
  600. static const unsigned PtrsArgNum = 4;
  601. static const unsigned SizesArgNum = 5;
  602. private:
  603. /// Traverses the BasicBlock where \p Array is, collecting the stores made to
  604. /// \p Array, leaving StoredValues with the values stored before the
  605. /// instruction \p Before is reached.
  606. bool getValues(AllocaInst &Array, Instruction &Before) {
  607. // Initialize container.
  608. const uint64_t NumValues = Array.getAllocatedType()->getArrayNumElements();
  609. StoredValues.assign(NumValues, nullptr);
  610. LastAccesses.assign(NumValues, nullptr);
  611. // TODO: This assumes the instruction \p Before is in the same
  612. // BasicBlock as Array. Make it general, for any control flow graph.
  613. BasicBlock *BB = Array.getParent();
  614. if (BB != Before.getParent())
  615. return false;
  616. const DataLayout &DL = Array.getModule()->getDataLayout();
  617. const unsigned int PointerSize = DL.getPointerSize();
  618. for (Instruction &I : *BB) {
  619. if (&I == &Before)
  620. break;
  621. if (!isa<StoreInst>(&I))
  622. continue;
  623. auto *S = cast<StoreInst>(&I);
  624. int64_t Offset = -1;
  625. auto *Dst =
  626. GetPointerBaseWithConstantOffset(S->getPointerOperand(), Offset, DL);
  627. if (Dst == &Array) {
  628. int64_t Idx = Offset / PointerSize;
  629. StoredValues[Idx] = getUnderlyingObject(S->getValueOperand());
  630. LastAccesses[Idx] = S;
  631. }
  632. }
  633. return isFilled();
  634. }
  635. /// Returns true if all values in StoredValues and
  636. /// LastAccesses are not nullptrs.
  637. bool isFilled() {
  638. const unsigned NumValues = StoredValues.size();
  639. for (unsigned I = 0; I < NumValues; ++I) {
  640. if (!StoredValues[I] || !LastAccesses[I])
  641. return false;
  642. }
  643. return true;
  644. }
  645. };
  646. struct OpenMPOpt {
  647. using OptimizationRemarkGetter =
  648. function_ref<OptimizationRemarkEmitter &(Function *)>;
  649. OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater,
  650. OptimizationRemarkGetter OREGetter,
  651. OMPInformationCache &OMPInfoCache, Attributor &A)
  652. : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater),
  653. OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {}
  654. /// Check if any remarks are enabled for openmp-opt
  655. bool remarksEnabled() {
  656. auto &Ctx = M.getContext();
  657. return Ctx.getDiagHandlerPtr()->isAnyRemarkEnabled(DEBUG_TYPE);
  658. }
  659. /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice.
  660. bool run(bool IsModulePass) {
  661. if (SCC.empty())
  662. return false;
  663. bool Changed = false;
  664. LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size()
  665. << " functions in a slice with "
  666. << OMPInfoCache.ModuleSlice.size() << " functions\n");
  667. if (IsModulePass) {
  668. Changed |= runAttributor(IsModulePass);
  669. // Recollect uses, in case Attributor deleted any.
  670. OMPInfoCache.recollectUses();
  671. // TODO: This should be folded into buildCustomStateMachine.
  672. Changed |= rewriteDeviceCodeStateMachine();
  673. if (remarksEnabled())
  674. analysisGlobalization();
  675. Changed |= eliminateBarriers();
  676. } else {
  677. if (PrintICVValues)
  678. printICVs();
  679. if (PrintOpenMPKernels)
  680. printKernels();
  681. Changed |= runAttributor(IsModulePass);
  682. // Recollect uses, in case Attributor deleted any.
  683. OMPInfoCache.recollectUses();
  684. Changed |= deleteParallelRegions();
  685. if (HideMemoryTransferLatency)
  686. Changed |= hideMemTransfersLatency();
  687. Changed |= deduplicateRuntimeCalls();
  688. if (EnableParallelRegionMerging) {
  689. if (mergeParallelRegions()) {
  690. deduplicateRuntimeCalls();
  691. Changed = true;
  692. }
  693. }
  694. Changed |= eliminateBarriers();
  695. }
  696. return Changed;
  697. }
  698. /// Print initial ICV values for testing.
  699. /// FIXME: This should be done from the Attributor once it is added.
  700. void printICVs() const {
  701. InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel,
  702. ICV_proc_bind};
  703. for (Function *F : OMPInfoCache.ModuleSlice) {
  704. for (auto ICV : ICVs) {
  705. auto ICVInfo = OMPInfoCache.ICVs[ICV];
  706. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  707. return ORA << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name)
  708. << " Value: "
  709. << (ICVInfo.InitValue
  710. ? toString(ICVInfo.InitValue->getValue(), 10, true)
  711. : "IMPLEMENTATION_DEFINED");
  712. };
  713. emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPICVTracker", Remark);
  714. }
  715. }
  716. }
  717. /// Print OpenMP GPU kernels for testing.
  718. void printKernels() const {
  719. for (Function *F : SCC) {
  720. if (!OMPInfoCache.Kernels.count(F))
  721. continue;
  722. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  723. return ORA << "OpenMP GPU kernel "
  724. << ore::NV("OpenMPGPUKernel", F->getName()) << "\n";
  725. };
  726. emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPGPU", Remark);
  727. }
  728. }
  729. /// Return the call if \p U is a callee use in a regular call. If \p RFI is
  730. /// given it has to be the callee or a nullptr is returned.
  731. static CallInst *getCallIfRegularCall(
  732. Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
  733. CallInst *CI = dyn_cast<CallInst>(U.getUser());
  734. if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() &&
  735. (!RFI ||
  736. (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration)))
  737. return CI;
  738. return nullptr;
  739. }
  740. /// Return the call if \p V is a regular call. If \p RFI is given it has to be
  741. /// the callee or a nullptr is returned.
  742. static CallInst *getCallIfRegularCall(
  743. Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
  744. CallInst *CI = dyn_cast<CallInst>(&V);
  745. if (CI && !CI->hasOperandBundles() &&
  746. (!RFI ||
  747. (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration)))
  748. return CI;
  749. return nullptr;
  750. }
  751. private:
  752. /// Merge parallel regions when it is safe.
  753. bool mergeParallelRegions() {
  754. const unsigned CallbackCalleeOperand = 2;
  755. const unsigned CallbackFirstArgOperand = 3;
  756. using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
  757. // Check if there are any __kmpc_fork_call calls to merge.
  758. OMPInformationCache::RuntimeFunctionInfo &RFI =
  759. OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
  760. if (!RFI.Declaration)
  761. return false;
  762. // Unmergable calls that prevent merging a parallel region.
  763. OMPInformationCache::RuntimeFunctionInfo UnmergableCallsInfo[] = {
  764. OMPInfoCache.RFIs[OMPRTL___kmpc_push_proc_bind],
  765. OMPInfoCache.RFIs[OMPRTL___kmpc_push_num_threads],
  766. };
  767. bool Changed = false;
  768. LoopInfo *LI = nullptr;
  769. DominatorTree *DT = nullptr;
  770. SmallDenseMap<BasicBlock *, SmallPtrSet<Instruction *, 4>> BB2PRMap;
  771. BasicBlock *StartBB = nullptr, *EndBB = nullptr;
  772. auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
  773. BasicBlock &ContinuationIP) {
  774. BasicBlock *CGStartBB = CodeGenIP.getBlock();
  775. BasicBlock *CGEndBB =
  776. SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI);
  777. assert(StartBB != nullptr && "StartBB should not be null");
  778. CGStartBB->getTerminator()->setSuccessor(0, StartBB);
  779. assert(EndBB != nullptr && "EndBB should not be null");
  780. EndBB->getTerminator()->setSuccessor(0, CGEndBB);
  781. };
  782. auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &,
  783. Value &Inner, Value *&ReplacementValue) -> InsertPointTy {
  784. ReplacementValue = &Inner;
  785. return CodeGenIP;
  786. };
  787. auto FiniCB = [&](InsertPointTy CodeGenIP) {};
  788. /// Create a sequential execution region within a merged parallel region,
  789. /// encapsulated in a master construct with a barrier for synchronization.
  790. auto CreateSequentialRegion = [&](Function *OuterFn,
  791. BasicBlock *OuterPredBB,
  792. Instruction *SeqStartI,
  793. Instruction *SeqEndI) {
  794. // Isolate the instructions of the sequential region to a separate
  795. // block.
  796. BasicBlock *ParentBB = SeqStartI->getParent();
  797. BasicBlock *SeqEndBB =
  798. SplitBlock(ParentBB, SeqEndI->getNextNode(), DT, LI);
  799. BasicBlock *SeqAfterBB =
  800. SplitBlock(SeqEndBB, &*SeqEndBB->getFirstInsertionPt(), DT, LI);
  801. BasicBlock *SeqStartBB =
  802. SplitBlock(ParentBB, SeqStartI, DT, LI, nullptr, "seq.par.merged");
  803. assert(ParentBB->getUniqueSuccessor() == SeqStartBB &&
  804. "Expected a different CFG");
  805. const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc();
  806. ParentBB->getTerminator()->eraseFromParent();
  807. auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
  808. BasicBlock &ContinuationIP) {
  809. BasicBlock *CGStartBB = CodeGenIP.getBlock();
  810. BasicBlock *CGEndBB =
  811. SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI);
  812. assert(SeqStartBB != nullptr && "SeqStartBB should not be null");
  813. CGStartBB->getTerminator()->setSuccessor(0, SeqStartBB);
  814. assert(SeqEndBB != nullptr && "SeqEndBB should not be null");
  815. SeqEndBB->getTerminator()->setSuccessor(0, CGEndBB);
  816. };
  817. auto FiniCB = [&](InsertPointTy CodeGenIP) {};
  818. // Find outputs from the sequential region to outside users and
  819. // broadcast their values to them.
  820. for (Instruction &I : *SeqStartBB) {
  821. SmallPtrSet<Instruction *, 4> OutsideUsers;
  822. for (User *Usr : I.users()) {
  823. Instruction &UsrI = *cast<Instruction>(Usr);
  824. // Ignore outputs to LT intrinsics, code extraction for the merged
  825. // parallel region will fix them.
  826. if (UsrI.isLifetimeStartOrEnd())
  827. continue;
  828. if (UsrI.getParent() != SeqStartBB)
  829. OutsideUsers.insert(&UsrI);
  830. }
  831. if (OutsideUsers.empty())
  832. continue;
  833. // Emit an alloca in the outer region to store the broadcasted
  834. // value.
  835. const DataLayout &DL = M.getDataLayout();
  836. AllocaInst *AllocaI = new AllocaInst(
  837. I.getType(), DL.getAllocaAddrSpace(), nullptr,
  838. I.getName() + ".seq.output.alloc", &OuterFn->front().front());
  839. // Emit a store instruction in the sequential BB to update the
  840. // value.
  841. new StoreInst(&I, AllocaI, SeqStartBB->getTerminator());
  842. // Emit a load instruction and replace the use of the output value
  843. // with it.
  844. for (Instruction *UsrI : OutsideUsers) {
  845. LoadInst *LoadI = new LoadInst(
  846. I.getType(), AllocaI, I.getName() + ".seq.output.load", UsrI);
  847. UsrI->replaceUsesOfWith(&I, LoadI);
  848. }
  849. }
  850. OpenMPIRBuilder::LocationDescription Loc(
  851. InsertPointTy(ParentBB, ParentBB->end()), DL);
  852. InsertPointTy SeqAfterIP =
  853. OMPInfoCache.OMPBuilder.createMaster(Loc, BodyGenCB, FiniCB);
  854. OMPInfoCache.OMPBuilder.createBarrier(SeqAfterIP, OMPD_parallel);
  855. BranchInst::Create(SeqAfterBB, SeqAfterIP.getBlock());
  856. LLVM_DEBUG(dbgs() << TAG << "After sequential inlining " << *OuterFn
  857. << "\n");
  858. };
  859. // Helper to merge the __kmpc_fork_call calls in MergableCIs. They are all
  860. // contained in BB and only separated by instructions that can be
  861. // redundantly executed in parallel. The block BB is split before the first
  862. // call (in MergableCIs) and after the last so the entire region we merge
  863. // into a single parallel region is contained in a single basic block
  864. // without any other instructions. We use the OpenMPIRBuilder to outline
  865. // that block and call the resulting function via __kmpc_fork_call.
  866. auto Merge = [&](const SmallVectorImpl<CallInst *> &MergableCIs,
  867. BasicBlock *BB) {
  868. // TODO: Change the interface to allow single CIs expanded, e.g, to
  869. // include an outer loop.
  870. assert(MergableCIs.size() > 1 && "Assumed multiple mergable CIs");
  871. auto Remark = [&](OptimizationRemark OR) {
  872. OR << "Parallel region merged with parallel region"
  873. << (MergableCIs.size() > 2 ? "s" : "") << " at ";
  874. for (auto *CI : llvm::drop_begin(MergableCIs)) {
  875. OR << ore::NV("OpenMPParallelMerge", CI->getDebugLoc());
  876. if (CI != MergableCIs.back())
  877. OR << ", ";
  878. }
  879. return OR << ".";
  880. };
  881. emitRemark<OptimizationRemark>(MergableCIs.front(), "OMP150", Remark);
  882. Function *OriginalFn = BB->getParent();
  883. LLVM_DEBUG(dbgs() << TAG << "Merge " << MergableCIs.size()
  884. << " parallel regions in " << OriginalFn->getName()
  885. << "\n");
  886. // Isolate the calls to merge in a separate block.
  887. EndBB = SplitBlock(BB, MergableCIs.back()->getNextNode(), DT, LI);
  888. BasicBlock *AfterBB =
  889. SplitBlock(EndBB, &*EndBB->getFirstInsertionPt(), DT, LI);
  890. StartBB = SplitBlock(BB, MergableCIs.front(), DT, LI, nullptr,
  891. "omp.par.merged");
  892. assert(BB->getUniqueSuccessor() == StartBB && "Expected a different CFG");
  893. const DebugLoc DL = BB->getTerminator()->getDebugLoc();
  894. BB->getTerminator()->eraseFromParent();
  895. // Create sequential regions for sequential instructions that are
  896. // in-between mergable parallel regions.
  897. for (auto *It = MergableCIs.begin(), *End = MergableCIs.end() - 1;
  898. It != End; ++It) {
  899. Instruction *ForkCI = *It;
  900. Instruction *NextForkCI = *(It + 1);
  901. // Continue if there are not in-between instructions.
  902. if (ForkCI->getNextNode() == NextForkCI)
  903. continue;
  904. CreateSequentialRegion(OriginalFn, BB, ForkCI->getNextNode(),
  905. NextForkCI->getPrevNode());
  906. }
  907. OpenMPIRBuilder::LocationDescription Loc(InsertPointTy(BB, BB->end()),
  908. DL);
  909. IRBuilder<>::InsertPoint AllocaIP(
  910. &OriginalFn->getEntryBlock(),
  911. OriginalFn->getEntryBlock().getFirstInsertionPt());
  912. // Create the merged parallel region with default proc binding, to
  913. // avoid overriding binding settings, and without explicit cancellation.
  914. InsertPointTy AfterIP = OMPInfoCache.OMPBuilder.createParallel(
  915. Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB, nullptr, nullptr,
  916. OMP_PROC_BIND_default, /* IsCancellable */ false);
  917. BranchInst::Create(AfterBB, AfterIP.getBlock());
  918. // Perform the actual outlining.
  919. OMPInfoCache.OMPBuilder.finalize(OriginalFn);
  920. Function *OutlinedFn = MergableCIs.front()->getCaller();
  921. // Replace the __kmpc_fork_call calls with direct calls to the outlined
  922. // callbacks.
  923. SmallVector<Value *, 8> Args;
  924. for (auto *CI : MergableCIs) {
  925. Value *Callee =
  926. CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts();
  927. FunctionType *FT =
  928. cast<FunctionType>(Callee->getType()->getPointerElementType());
  929. Args.clear();
  930. Args.push_back(OutlinedFn->getArg(0));
  931. Args.push_back(OutlinedFn->getArg(1));
  932. for (unsigned U = CallbackFirstArgOperand, E = CI->arg_size(); U < E;
  933. ++U)
  934. Args.push_back(CI->getArgOperand(U));
  935. CallInst *NewCI = CallInst::Create(FT, Callee, Args, "", CI);
  936. if (CI->getDebugLoc())
  937. NewCI->setDebugLoc(CI->getDebugLoc());
  938. // Forward parameter attributes from the callback to the callee.
  939. for (unsigned U = CallbackFirstArgOperand, E = CI->arg_size(); U < E;
  940. ++U)
  941. for (const Attribute &A : CI->getAttributes().getParamAttrs(U))
  942. NewCI->addParamAttr(
  943. U - (CallbackFirstArgOperand - CallbackCalleeOperand), A);
  944. // Emit an explicit barrier to replace the implicit fork-join barrier.
  945. if (CI != MergableCIs.back()) {
  946. // TODO: Remove barrier if the merged parallel region includes the
  947. // 'nowait' clause.
  948. OMPInfoCache.OMPBuilder.createBarrier(
  949. InsertPointTy(NewCI->getParent(),
  950. NewCI->getNextNode()->getIterator()),
  951. OMPD_parallel);
  952. }
  953. CI->eraseFromParent();
  954. }
  955. assert(OutlinedFn != OriginalFn && "Outlining failed");
  956. CGUpdater.registerOutlinedFunction(*OriginalFn, *OutlinedFn);
  957. CGUpdater.reanalyzeFunction(*OriginalFn);
  958. NumOpenMPParallelRegionsMerged += MergableCIs.size();
  959. return true;
  960. };
  961. // Helper function that identifes sequences of
  962. // __kmpc_fork_call uses in a basic block.
  963. auto DetectPRsCB = [&](Use &U, Function &F) {
  964. CallInst *CI = getCallIfRegularCall(U, &RFI);
  965. BB2PRMap[CI->getParent()].insert(CI);
  966. return false;
  967. };
  968. BB2PRMap.clear();
  969. RFI.foreachUse(SCC, DetectPRsCB);
  970. SmallVector<SmallVector<CallInst *, 4>, 4> MergableCIsVector;
  971. // Find mergable parallel regions within a basic block that are
  972. // safe to merge, that is any in-between instructions can safely
  973. // execute in parallel after merging.
  974. // TODO: support merging across basic-blocks.
  975. for (auto &It : BB2PRMap) {
  976. auto &CIs = It.getSecond();
  977. if (CIs.size() < 2)
  978. continue;
  979. BasicBlock *BB = It.getFirst();
  980. SmallVector<CallInst *, 4> MergableCIs;
  981. /// Returns true if the instruction is mergable, false otherwise.
  982. /// A terminator instruction is unmergable by definition since merging
  983. /// works within a BB. Instructions before the mergable region are
  984. /// mergable if they are not calls to OpenMP runtime functions that may
  985. /// set different execution parameters for subsequent parallel regions.
  986. /// Instructions in-between parallel regions are mergable if they are not
  987. /// calls to any non-intrinsic function since that may call a non-mergable
  988. /// OpenMP runtime function.
  989. auto IsMergable = [&](Instruction &I, bool IsBeforeMergableRegion) {
  990. // We do not merge across BBs, hence return false (unmergable) if the
  991. // instruction is a terminator.
  992. if (I.isTerminator())
  993. return false;
  994. if (!isa<CallInst>(&I))
  995. return true;
  996. CallInst *CI = cast<CallInst>(&I);
  997. if (IsBeforeMergableRegion) {
  998. Function *CalledFunction = CI->getCalledFunction();
  999. if (!CalledFunction)
  1000. return false;
  1001. // Return false (unmergable) if the call before the parallel
  1002. // region calls an explicit affinity (proc_bind) or number of
  1003. // threads (num_threads) compiler-generated function. Those settings
  1004. // may be incompatible with following parallel regions.
  1005. // TODO: ICV tracking to detect compatibility.
  1006. for (const auto &RFI : UnmergableCallsInfo) {
  1007. if (CalledFunction == RFI.Declaration)
  1008. return false;
  1009. }
  1010. } else {
  1011. // Return false (unmergable) if there is a call instruction
  1012. // in-between parallel regions when it is not an intrinsic. It
  1013. // may call an unmergable OpenMP runtime function in its callpath.
  1014. // TODO: Keep track of possible OpenMP calls in the callpath.
  1015. if (!isa<IntrinsicInst>(CI))
  1016. return false;
  1017. }
  1018. return true;
  1019. };
  1020. // Find maximal number of parallel region CIs that are safe to merge.
  1021. for (auto It = BB->begin(), End = BB->end(); It != End;) {
  1022. Instruction &I = *It;
  1023. ++It;
  1024. if (CIs.count(&I)) {
  1025. MergableCIs.push_back(cast<CallInst>(&I));
  1026. continue;
  1027. }
  1028. // Continue expanding if the instruction is mergable.
  1029. if (IsMergable(I, MergableCIs.empty()))
  1030. continue;
  1031. // Forward the instruction iterator to skip the next parallel region
  1032. // since there is an unmergable instruction which can affect it.
  1033. for (; It != End; ++It) {
  1034. Instruction &SkipI = *It;
  1035. if (CIs.count(&SkipI)) {
  1036. LLVM_DEBUG(dbgs() << TAG << "Skip parallel region " << SkipI
  1037. << " due to " << I << "\n");
  1038. ++It;
  1039. break;
  1040. }
  1041. }
  1042. // Store mergable regions found.
  1043. if (MergableCIs.size() > 1) {
  1044. MergableCIsVector.push_back(MergableCIs);
  1045. LLVM_DEBUG(dbgs() << TAG << "Found " << MergableCIs.size()
  1046. << " parallel regions in block " << BB->getName()
  1047. << " of function " << BB->getParent()->getName()
  1048. << "\n";);
  1049. }
  1050. MergableCIs.clear();
  1051. }
  1052. if (!MergableCIsVector.empty()) {
  1053. Changed = true;
  1054. for (auto &MergableCIs : MergableCIsVector)
  1055. Merge(MergableCIs, BB);
  1056. MergableCIsVector.clear();
  1057. }
  1058. }
  1059. if (Changed) {
  1060. /// Re-collect use for fork calls, emitted barrier calls, and
  1061. /// any emitted master/end_master calls.
  1062. OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_fork_call);
  1063. OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_barrier);
  1064. OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_master);
  1065. OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_end_master);
  1066. }
  1067. return Changed;
  1068. }
  1069. /// Try to delete parallel regions if possible.
  1070. bool deleteParallelRegions() {
  1071. const unsigned CallbackCalleeOperand = 2;
  1072. OMPInformationCache::RuntimeFunctionInfo &RFI =
  1073. OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
  1074. if (!RFI.Declaration)
  1075. return false;
  1076. bool Changed = false;
  1077. auto DeleteCallCB = [&](Use &U, Function &) {
  1078. CallInst *CI = getCallIfRegularCall(U);
  1079. if (!CI)
  1080. return false;
  1081. auto *Fn = dyn_cast<Function>(
  1082. CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts());
  1083. if (!Fn)
  1084. return false;
  1085. if (!Fn->onlyReadsMemory())
  1086. return false;
  1087. if (!Fn->hasFnAttribute(Attribute::WillReturn))
  1088. return false;
  1089. LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in "
  1090. << CI->getCaller()->getName() << "\n");
  1091. auto Remark = [&](OptimizationRemark OR) {
  1092. return OR << "Removing parallel region with no side-effects.";
  1093. };
  1094. emitRemark<OptimizationRemark>(CI, "OMP160", Remark);
  1095. CGUpdater.removeCallSite(*CI);
  1096. CI->eraseFromParent();
  1097. Changed = true;
  1098. ++NumOpenMPParallelRegionsDeleted;
  1099. return true;
  1100. };
  1101. RFI.foreachUse(SCC, DeleteCallCB);
  1102. return Changed;
  1103. }
  1104. /// Try to eliminate runtime calls by reusing existing ones.
  1105. bool deduplicateRuntimeCalls() {
  1106. bool Changed = false;
  1107. RuntimeFunction DeduplicableRuntimeCallIDs[] = {
  1108. OMPRTL_omp_get_num_threads,
  1109. OMPRTL_omp_in_parallel,
  1110. OMPRTL_omp_get_cancellation,
  1111. OMPRTL_omp_get_thread_limit,
  1112. OMPRTL_omp_get_supported_active_levels,
  1113. OMPRTL_omp_get_level,
  1114. OMPRTL_omp_get_ancestor_thread_num,
  1115. OMPRTL_omp_get_team_size,
  1116. OMPRTL_omp_get_active_level,
  1117. OMPRTL_omp_in_final,
  1118. OMPRTL_omp_get_proc_bind,
  1119. OMPRTL_omp_get_num_places,
  1120. OMPRTL_omp_get_num_procs,
  1121. OMPRTL_omp_get_place_num,
  1122. OMPRTL_omp_get_partition_num_places,
  1123. OMPRTL_omp_get_partition_place_nums};
  1124. // Global-tid is handled separately.
  1125. SmallSetVector<Value *, 16> GTIdArgs;
  1126. collectGlobalThreadIdArguments(GTIdArgs);
  1127. LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size()
  1128. << " global thread ID arguments\n");
  1129. for (Function *F : SCC) {
  1130. for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs)
  1131. Changed |= deduplicateRuntimeCalls(
  1132. *F, OMPInfoCache.RFIs[DeduplicableRuntimeCallID]);
  1133. // __kmpc_global_thread_num is special as we can replace it with an
  1134. // argument in enough cases to make it worth trying.
  1135. Value *GTIdArg = nullptr;
  1136. for (Argument &Arg : F->args())
  1137. if (GTIdArgs.count(&Arg)) {
  1138. GTIdArg = &Arg;
  1139. break;
  1140. }
  1141. Changed |= deduplicateRuntimeCalls(
  1142. *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg);
  1143. }
  1144. return Changed;
  1145. }
  1146. /// Tries to hide the latency of runtime calls that involve host to
  1147. /// device memory transfers by splitting them into their "issue" and "wait"
  1148. /// versions. The "issue" is moved upwards as much as possible. The "wait" is
  1149. /// moved downards as much as possible. The "issue" issues the memory transfer
  1150. /// asynchronously, returning a handle. The "wait" waits in the returned
  1151. /// handle for the memory transfer to finish.
  1152. bool hideMemTransfersLatency() {
  1153. auto &RFI = OMPInfoCache.RFIs[OMPRTL___tgt_target_data_begin_mapper];
  1154. bool Changed = false;
  1155. auto SplitMemTransfers = [&](Use &U, Function &Decl) {
  1156. auto *RTCall = getCallIfRegularCall(U, &RFI);
  1157. if (!RTCall)
  1158. return false;
  1159. OffloadArray OffloadArrays[3];
  1160. if (!getValuesInOffloadArrays(*RTCall, OffloadArrays))
  1161. return false;
  1162. LLVM_DEBUG(dumpValuesInOffloadArrays(OffloadArrays));
  1163. // TODO: Check if can be moved upwards.
  1164. bool WasSplit = false;
  1165. Instruction *WaitMovementPoint = canBeMovedDownwards(*RTCall);
  1166. if (WaitMovementPoint)
  1167. WasSplit = splitTargetDataBeginRTC(*RTCall, *WaitMovementPoint);
  1168. Changed |= WasSplit;
  1169. return WasSplit;
  1170. };
  1171. RFI.foreachUse(SCC, SplitMemTransfers);
  1172. return Changed;
  1173. }
  1174. /// Eliminates redundant, aligned barriers in OpenMP offloaded kernels.
  1175. /// TODO: Make this an AA and expand it to work across blocks and functions.
  1176. bool eliminateBarriers() {
  1177. bool Changed = false;
  1178. if (DisableOpenMPOptBarrierElimination)
  1179. return /*Changed=*/false;
  1180. if (OMPInfoCache.Kernels.empty())
  1181. return /*Changed=*/false;
  1182. enum ImplicitBarrierType { IBT_ENTRY, IBT_EXIT };
  1183. class BarrierInfo {
  1184. Instruction *I;
  1185. enum ImplicitBarrierType Type;
  1186. public:
  1187. BarrierInfo(enum ImplicitBarrierType Type) : I(nullptr), Type(Type) {}
  1188. BarrierInfo(Instruction &I) : I(&I) {}
  1189. bool isImplicit() { return !I; }
  1190. bool isImplicitEntry() { return isImplicit() && Type == IBT_ENTRY; }
  1191. bool isImplicitExit() { return isImplicit() && Type == IBT_EXIT; }
  1192. Instruction *getInstruction() { return I; }
  1193. };
  1194. for (Function *Kernel : OMPInfoCache.Kernels) {
  1195. for (BasicBlock &BB : *Kernel) {
  1196. SmallVector<BarrierInfo, 8> BarriersInBlock;
  1197. SmallPtrSet<Instruction *, 8> BarriersToBeDeleted;
  1198. // Add the kernel entry implicit barrier.
  1199. if (&Kernel->getEntryBlock() == &BB)
  1200. BarriersInBlock.push_back(IBT_ENTRY);
  1201. // Find implicit and explicit aligned barriers in the same basic block.
  1202. for (Instruction &I : BB) {
  1203. if (isa<ReturnInst>(I)) {
  1204. // Add the implicit barrier when exiting the kernel.
  1205. BarriersInBlock.push_back(IBT_EXIT);
  1206. continue;
  1207. }
  1208. CallBase *CB = dyn_cast<CallBase>(&I);
  1209. if (!CB)
  1210. continue;
  1211. auto IsAlignBarrierCB = [&](CallBase &CB) {
  1212. switch (CB.getIntrinsicID()) {
  1213. case Intrinsic::nvvm_barrier0:
  1214. case Intrinsic::nvvm_barrier0_and:
  1215. case Intrinsic::nvvm_barrier0_or:
  1216. case Intrinsic::nvvm_barrier0_popc:
  1217. return true;
  1218. default:
  1219. break;
  1220. }
  1221. return hasAssumption(CB,
  1222. KnownAssumptionString("ompx_aligned_barrier"));
  1223. };
  1224. if (IsAlignBarrierCB(*CB)) {
  1225. // Add an explicit aligned barrier.
  1226. BarriersInBlock.push_back(I);
  1227. }
  1228. }
  1229. if (BarriersInBlock.size() <= 1)
  1230. continue;
  1231. // A barrier in a barrier pair is removeable if all instructions
  1232. // between the barriers in the pair are side-effect free modulo the
  1233. // barrier operation.
  1234. auto IsBarrierRemoveable = [&Kernel](BarrierInfo *StartBI,
  1235. BarrierInfo *EndBI) {
  1236. assert(
  1237. !StartBI->isImplicitExit() &&
  1238. "Expected start barrier to be other than a kernel exit barrier");
  1239. assert(
  1240. !EndBI->isImplicitEntry() &&
  1241. "Expected end barrier to be other than a kernel entry barrier");
  1242. // If StarBI instructions is null then this the implicit
  1243. // kernel entry barrier, so iterate from the first instruction in the
  1244. // entry block.
  1245. Instruction *I = (StartBI->isImplicitEntry())
  1246. ? &Kernel->getEntryBlock().front()
  1247. : StartBI->getInstruction()->getNextNode();
  1248. assert(I && "Expected non-null start instruction");
  1249. Instruction *E = (EndBI->isImplicitExit())
  1250. ? I->getParent()->getTerminator()
  1251. : EndBI->getInstruction();
  1252. assert(E && "Expected non-null end instruction");
  1253. for (; I != E; I = I->getNextNode()) {
  1254. if (!I->mayHaveSideEffects() && !I->mayReadFromMemory())
  1255. continue;
  1256. auto IsPotentiallyAffectedByBarrier =
  1257. [](Optional<MemoryLocation> Loc) {
  1258. const Value *Obj = (Loc && Loc->Ptr)
  1259. ? getUnderlyingObject(Loc->Ptr)
  1260. : nullptr;
  1261. if (!Obj) {
  1262. LLVM_DEBUG(
  1263. dbgs()
  1264. << "Access to unknown location requires barriers\n");
  1265. return true;
  1266. }
  1267. if (isa<UndefValue>(Obj))
  1268. return false;
  1269. if (isa<AllocaInst>(Obj))
  1270. return false;
  1271. if (auto *GV = dyn_cast<GlobalVariable>(Obj)) {
  1272. if (GV->isConstant())
  1273. return false;
  1274. if (GV->isThreadLocal())
  1275. return false;
  1276. if (GV->getAddressSpace() == (int)AddressSpace::Local)
  1277. return false;
  1278. if (GV->getAddressSpace() == (int)AddressSpace::Constant)
  1279. return false;
  1280. }
  1281. LLVM_DEBUG(dbgs() << "Access to '" << *Obj
  1282. << "' requires barriers\n");
  1283. return true;
  1284. };
  1285. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
  1286. Optional<MemoryLocation> Loc = MemoryLocation::getForDest(MI);
  1287. if (IsPotentiallyAffectedByBarrier(Loc))
  1288. return false;
  1289. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
  1290. Optional<MemoryLocation> Loc =
  1291. MemoryLocation::getForSource(MTI);
  1292. if (IsPotentiallyAffectedByBarrier(Loc))
  1293. return false;
  1294. }
  1295. continue;
  1296. }
  1297. if (auto *LI = dyn_cast<LoadInst>(I))
  1298. if (LI->hasMetadata(LLVMContext::MD_invariant_load))
  1299. continue;
  1300. Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
  1301. if (IsPotentiallyAffectedByBarrier(Loc))
  1302. return false;
  1303. }
  1304. return true;
  1305. };
  1306. // Iterate barrier pairs and remove an explicit barrier if analysis
  1307. // deems it removeable.
  1308. for (auto *It = BarriersInBlock.begin(),
  1309. *End = BarriersInBlock.end() - 1;
  1310. It != End; ++It) {
  1311. BarrierInfo *StartBI = It;
  1312. BarrierInfo *EndBI = (It + 1);
  1313. // Cannot remove when both are implicit barriers, continue.
  1314. if (StartBI->isImplicit() && EndBI->isImplicit())
  1315. continue;
  1316. if (!IsBarrierRemoveable(StartBI, EndBI))
  1317. continue;
  1318. assert(!(StartBI->isImplicit() && EndBI->isImplicit()) &&
  1319. "Expected at least one explicit barrier to remove.");
  1320. // Remove an explicit barrier, check first, then second.
  1321. if (!StartBI->isImplicit()) {
  1322. LLVM_DEBUG(dbgs() << "Remove start barrier "
  1323. << *StartBI->getInstruction() << "\n");
  1324. BarriersToBeDeleted.insert(StartBI->getInstruction());
  1325. } else {
  1326. LLVM_DEBUG(dbgs() << "Remove end barrier "
  1327. << *EndBI->getInstruction() << "\n");
  1328. BarriersToBeDeleted.insert(EndBI->getInstruction());
  1329. }
  1330. }
  1331. if (BarriersToBeDeleted.empty())
  1332. continue;
  1333. Changed = true;
  1334. for (Instruction *I : BarriersToBeDeleted) {
  1335. ++NumBarriersEliminated;
  1336. auto Remark = [&](OptimizationRemark OR) {
  1337. return OR << "Redundant barrier eliminated.";
  1338. };
  1339. if (EnableVerboseRemarks)
  1340. emitRemark<OptimizationRemark>(I, "OMP190", Remark);
  1341. I->eraseFromParent();
  1342. }
  1343. }
  1344. }
  1345. return Changed;
  1346. }
  1347. void analysisGlobalization() {
  1348. auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
  1349. auto CheckGlobalization = [&](Use &U, Function &Decl) {
  1350. if (CallInst *CI = getCallIfRegularCall(U, &RFI)) {
  1351. auto Remark = [&](OptimizationRemarkMissed ORM) {
  1352. return ORM
  1353. << "Found thread data sharing on the GPU. "
  1354. << "Expect degraded performance due to data globalization.";
  1355. };
  1356. emitRemark<OptimizationRemarkMissed>(CI, "OMP112", Remark);
  1357. }
  1358. return false;
  1359. };
  1360. RFI.foreachUse(SCC, CheckGlobalization);
  1361. }
  1362. /// Maps the values stored in the offload arrays passed as arguments to
  1363. /// \p RuntimeCall into the offload arrays in \p OAs.
  1364. bool getValuesInOffloadArrays(CallInst &RuntimeCall,
  1365. MutableArrayRef<OffloadArray> OAs) {
  1366. assert(OAs.size() == 3 && "Need space for three offload arrays!");
  1367. // A runtime call that involves memory offloading looks something like:
  1368. // call void @__tgt_target_data_begin_mapper(arg0, arg1,
  1369. // i8** %offload_baseptrs, i8** %offload_ptrs, i64* %offload_sizes,
  1370. // ...)
  1371. // So, the idea is to access the allocas that allocate space for these
  1372. // offload arrays, offload_baseptrs, offload_ptrs, offload_sizes.
  1373. // Therefore:
  1374. // i8** %offload_baseptrs.
  1375. Value *BasePtrsArg =
  1376. RuntimeCall.getArgOperand(OffloadArray::BasePtrsArgNum);
  1377. // i8** %offload_ptrs.
  1378. Value *PtrsArg = RuntimeCall.getArgOperand(OffloadArray::PtrsArgNum);
  1379. // i8** %offload_sizes.
  1380. Value *SizesArg = RuntimeCall.getArgOperand(OffloadArray::SizesArgNum);
  1381. // Get values stored in **offload_baseptrs.
  1382. auto *V = getUnderlyingObject(BasePtrsArg);
  1383. if (!isa<AllocaInst>(V))
  1384. return false;
  1385. auto *BasePtrsArray = cast<AllocaInst>(V);
  1386. if (!OAs[0].initialize(*BasePtrsArray, RuntimeCall))
  1387. return false;
  1388. // Get values stored in **offload_baseptrs.
  1389. V = getUnderlyingObject(PtrsArg);
  1390. if (!isa<AllocaInst>(V))
  1391. return false;
  1392. auto *PtrsArray = cast<AllocaInst>(V);
  1393. if (!OAs[1].initialize(*PtrsArray, RuntimeCall))
  1394. return false;
  1395. // Get values stored in **offload_sizes.
  1396. V = getUnderlyingObject(SizesArg);
  1397. // If it's a [constant] global array don't analyze it.
  1398. if (isa<GlobalValue>(V))
  1399. return isa<Constant>(V);
  1400. if (!isa<AllocaInst>(V))
  1401. return false;
  1402. auto *SizesArray = cast<AllocaInst>(V);
  1403. if (!OAs[2].initialize(*SizesArray, RuntimeCall))
  1404. return false;
  1405. return true;
  1406. }
  1407. /// Prints the values in the OffloadArrays \p OAs using LLVM_DEBUG.
  1408. /// For now this is a way to test that the function getValuesInOffloadArrays
  1409. /// is working properly.
  1410. /// TODO: Move this to a unittest when unittests are available for OpenMPOpt.
  1411. void dumpValuesInOffloadArrays(ArrayRef<OffloadArray> OAs) {
  1412. assert(OAs.size() == 3 && "There are three offload arrays to debug!");
  1413. LLVM_DEBUG(dbgs() << TAG << " Successfully got offload values:\n");
  1414. std::string ValuesStr;
  1415. raw_string_ostream Printer(ValuesStr);
  1416. std::string Separator = " --- ";
  1417. for (auto *BP : OAs[0].StoredValues) {
  1418. BP->print(Printer);
  1419. Printer << Separator;
  1420. }
  1421. LLVM_DEBUG(dbgs() << "\t\toffload_baseptrs: " << Printer.str() << "\n");
  1422. ValuesStr.clear();
  1423. for (auto *P : OAs[1].StoredValues) {
  1424. P->print(Printer);
  1425. Printer << Separator;
  1426. }
  1427. LLVM_DEBUG(dbgs() << "\t\toffload_ptrs: " << Printer.str() << "\n");
  1428. ValuesStr.clear();
  1429. for (auto *S : OAs[2].StoredValues) {
  1430. S->print(Printer);
  1431. Printer << Separator;
  1432. }
  1433. LLVM_DEBUG(dbgs() << "\t\toffload_sizes: " << Printer.str() << "\n");
  1434. }
  1435. /// Returns the instruction where the "wait" counterpart \p RuntimeCall can be
  1436. /// moved. Returns nullptr if the movement is not possible, or not worth it.
  1437. Instruction *canBeMovedDownwards(CallInst &RuntimeCall) {
  1438. // FIXME: This traverses only the BasicBlock where RuntimeCall is.
  1439. // Make it traverse the CFG.
  1440. Instruction *CurrentI = &RuntimeCall;
  1441. bool IsWorthIt = false;
  1442. while ((CurrentI = CurrentI->getNextNode())) {
  1443. // TODO: Once we detect the regions to be offloaded we should use the
  1444. // alias analysis manager to check if CurrentI may modify one of
  1445. // the offloaded regions.
  1446. if (CurrentI->mayHaveSideEffects() || CurrentI->mayReadFromMemory()) {
  1447. if (IsWorthIt)
  1448. return CurrentI;
  1449. return nullptr;
  1450. }
  1451. // FIXME: For now if we move it over anything without side effect
  1452. // is worth it.
  1453. IsWorthIt = true;
  1454. }
  1455. // Return end of BasicBlock.
  1456. return RuntimeCall.getParent()->getTerminator();
  1457. }
  1458. /// Splits \p RuntimeCall into its "issue" and "wait" counterparts.
  1459. bool splitTargetDataBeginRTC(CallInst &RuntimeCall,
  1460. Instruction &WaitMovementPoint) {
  1461. // Create stack allocated handle (__tgt_async_info) at the beginning of the
  1462. // function. Used for storing information of the async transfer, allowing to
  1463. // wait on it later.
  1464. auto &IRBuilder = OMPInfoCache.OMPBuilder;
  1465. auto *F = RuntimeCall.getCaller();
  1466. Instruction *FirstInst = &(F->getEntryBlock().front());
  1467. AllocaInst *Handle = new AllocaInst(
  1468. IRBuilder.AsyncInfo, F->getAddressSpace(), "handle", FirstInst);
  1469. // Add "issue" runtime call declaration:
  1470. // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32,
  1471. // i8**, i8**, i64*, i64*)
  1472. FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction(
  1473. M, OMPRTL___tgt_target_data_begin_mapper_issue);
  1474. // Change RuntimeCall call site for its asynchronous version.
  1475. SmallVector<Value *, 16> Args;
  1476. for (auto &Arg : RuntimeCall.args())
  1477. Args.push_back(Arg.get());
  1478. Args.push_back(Handle);
  1479. CallInst *IssueCallsite =
  1480. CallInst::Create(IssueDecl, Args, /*NameStr=*/"", &RuntimeCall);
  1481. OMPInfoCache.setCallingConvention(IssueDecl, IssueCallsite);
  1482. RuntimeCall.eraseFromParent();
  1483. // Add "wait" runtime call declaration:
  1484. // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info)
  1485. FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction(
  1486. M, OMPRTL___tgt_target_data_begin_mapper_wait);
  1487. Value *WaitParams[2] = {
  1488. IssueCallsite->getArgOperand(
  1489. OffloadArray::DeviceIDArgNum), // device_id.
  1490. Handle // handle to wait on.
  1491. };
  1492. CallInst *WaitCallsite = CallInst::Create(
  1493. WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint);
  1494. OMPInfoCache.setCallingConvention(WaitDecl, WaitCallsite);
  1495. return true;
  1496. }
  1497. static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent,
  1498. bool GlobalOnly, bool &SingleChoice) {
  1499. if (CurrentIdent == NextIdent)
  1500. return CurrentIdent;
  1501. // TODO: Figure out how to actually combine multiple debug locations. For
  1502. // now we just keep an existing one if there is a single choice.
  1503. if (!GlobalOnly || isa<GlobalValue>(NextIdent)) {
  1504. SingleChoice = !CurrentIdent;
  1505. return NextIdent;
  1506. }
  1507. return nullptr;
  1508. }
  1509. /// Return an `struct ident_t*` value that represents the ones used in the
  1510. /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
  1511. /// return a local `struct ident_t*`. For now, if we cannot find a suitable
  1512. /// return value we create one from scratch. We also do not yet combine
  1513. /// information, e.g., the source locations, see combinedIdentStruct.
  1514. Value *
  1515. getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI,
  1516. Function &F, bool GlobalOnly) {
  1517. bool SingleChoice = true;
  1518. Value *Ident = nullptr;
  1519. auto CombineIdentStruct = [&](Use &U, Function &Caller) {
  1520. CallInst *CI = getCallIfRegularCall(U, &RFI);
  1521. if (!CI || &F != &Caller)
  1522. return false;
  1523. Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
  1524. /* GlobalOnly */ true, SingleChoice);
  1525. return false;
  1526. };
  1527. RFI.foreachUse(SCC, CombineIdentStruct);
  1528. if (!Ident || !SingleChoice) {
  1529. // The IRBuilder uses the insertion block to get to the module, this is
  1530. // unfortunate but we work around it for now.
  1531. if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock())
  1532. OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
  1533. &F.getEntryBlock(), F.getEntryBlock().begin()));
  1534. // Create a fallback location if non was found.
  1535. // TODO: Use the debug locations of the calls instead.
  1536. uint32_t SrcLocStrSize;
  1537. Constant *Loc =
  1538. OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr(SrcLocStrSize);
  1539. Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc, SrcLocStrSize);
  1540. }
  1541. return Ident;
  1542. }
  1543. /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or
  1544. /// \p ReplVal if given.
  1545. bool deduplicateRuntimeCalls(Function &F,
  1546. OMPInformationCache::RuntimeFunctionInfo &RFI,
  1547. Value *ReplVal = nullptr) {
  1548. auto *UV = RFI.getUseVector(F);
  1549. if (!UV || UV->size() + (ReplVal != nullptr) < 2)
  1550. return false;
  1551. LLVM_DEBUG(
  1552. dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name
  1553. << (ReplVal ? " with an existing value\n" : "\n") << "\n");
  1554. assert((!ReplVal || (isa<Argument>(ReplVal) &&
  1555. cast<Argument>(ReplVal)->getParent() == &F)) &&
  1556. "Unexpected replacement value!");
  1557. // TODO: Use dominance to find a good position instead.
  1558. auto CanBeMoved = [this](CallBase &CB) {
  1559. unsigned NumArgs = CB.arg_size();
  1560. if (NumArgs == 0)
  1561. return true;
  1562. if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr)
  1563. return false;
  1564. for (unsigned U = 1; U < NumArgs; ++U)
  1565. if (isa<Instruction>(CB.getArgOperand(U)))
  1566. return false;
  1567. return true;
  1568. };
  1569. if (!ReplVal) {
  1570. for (Use *U : *UV)
  1571. if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
  1572. if (!CanBeMoved(*CI))
  1573. continue;
  1574. // If the function is a kernel, dedup will move
  1575. // the runtime call right after the kernel init callsite. Otherwise,
  1576. // it will move it to the beginning of the caller function.
  1577. if (isKernel(F)) {
  1578. auto &KernelInitRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
  1579. auto *KernelInitUV = KernelInitRFI.getUseVector(F);
  1580. if (KernelInitUV->empty())
  1581. continue;
  1582. assert(KernelInitUV->size() == 1 &&
  1583. "Expected a single __kmpc_target_init in kernel\n");
  1584. CallInst *KernelInitCI =
  1585. getCallIfRegularCall(*KernelInitUV->front(), &KernelInitRFI);
  1586. assert(KernelInitCI &&
  1587. "Expected a call to __kmpc_target_init in kernel\n");
  1588. CI->moveAfter(KernelInitCI);
  1589. } else
  1590. CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
  1591. ReplVal = CI;
  1592. break;
  1593. }
  1594. if (!ReplVal)
  1595. return false;
  1596. }
  1597. // If we use a call as a replacement value we need to make sure the ident is
  1598. // valid at the new location. For now we just pick a global one, either
  1599. // existing and used by one of the calls, or created from scratch.
  1600. if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
  1601. if (!CI->arg_empty() &&
  1602. CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) {
  1603. Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
  1604. /* GlobalOnly */ true);
  1605. CI->setArgOperand(0, Ident);
  1606. }
  1607. }
  1608. bool Changed = false;
  1609. auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
  1610. CallInst *CI = getCallIfRegularCall(U, &RFI);
  1611. if (!CI || CI == ReplVal || &F != &Caller)
  1612. return false;
  1613. assert(CI->getCaller() == &F && "Unexpected call!");
  1614. auto Remark = [&](OptimizationRemark OR) {
  1615. return OR << "OpenMP runtime call "
  1616. << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated.";
  1617. };
  1618. if (CI->getDebugLoc())
  1619. emitRemark<OptimizationRemark>(CI, "OMP170", Remark);
  1620. else
  1621. emitRemark<OptimizationRemark>(&F, "OMP170", Remark);
  1622. CGUpdater.removeCallSite(*CI);
  1623. CI->replaceAllUsesWith(ReplVal);
  1624. CI->eraseFromParent();
  1625. ++NumOpenMPRuntimeCallsDeduplicated;
  1626. Changed = true;
  1627. return true;
  1628. };
  1629. RFI.foreachUse(SCC, ReplaceAndDeleteCB);
  1630. return Changed;
  1631. }
  1632. /// Collect arguments that represent the global thread id in \p GTIdArgs.
  1633. void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
  1634. // TODO: Below we basically perform a fixpoint iteration with a pessimistic
  1635. // initialization. We could define an AbstractAttribute instead and
  1636. // run the Attributor here once it can be run as an SCC pass.
  1637. // Helper to check the argument \p ArgNo at all call sites of \p F for
  1638. // a GTId.
  1639. auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
  1640. if (!F.hasLocalLinkage())
  1641. return false;
  1642. for (Use &U : F.uses()) {
  1643. if (CallInst *CI = getCallIfRegularCall(U)) {
  1644. Value *ArgOp = CI->getArgOperand(ArgNo);
  1645. if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
  1646. getCallIfRegularCall(
  1647. *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]))
  1648. continue;
  1649. }
  1650. return false;
  1651. }
  1652. return true;
  1653. };
  1654. // Helper to identify uses of a GTId as GTId arguments.
  1655. auto AddUserArgs = [&](Value &GTId) {
  1656. for (Use &U : GTId.uses())
  1657. if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
  1658. if (CI->isArgOperand(&U))
  1659. if (Function *Callee = CI->getCalledFunction())
  1660. if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
  1661. GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
  1662. };
  1663. // The argument users of __kmpc_global_thread_num calls are GTIds.
  1664. OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI =
  1665. OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num];
  1666. GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) {
  1667. if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI))
  1668. AddUserArgs(*CI);
  1669. return false;
  1670. });
  1671. // Transitively search for more arguments by looking at the users of the
  1672. // ones we know already. During the search the GTIdArgs vector is extended
  1673. // so we cannot cache the size nor can we use a range based for.
  1674. for (unsigned U = 0; U < GTIdArgs.size(); ++U)
  1675. AddUserArgs(*GTIdArgs[U]);
  1676. }
  1677. /// Kernel (=GPU) optimizations and utility functions
  1678. ///
  1679. ///{{
  1680. /// Check if \p F is a kernel, hence entry point for target offloading.
  1681. bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); }
  1682. /// Cache to remember the unique kernel for a function.
  1683. DenseMap<Function *, Optional<Kernel>> UniqueKernelMap;
  1684. /// Find the unique kernel that will execute \p F, if any.
  1685. Kernel getUniqueKernelFor(Function &F);
  1686. /// Find the unique kernel that will execute \p I, if any.
  1687. Kernel getUniqueKernelFor(Instruction &I) {
  1688. return getUniqueKernelFor(*I.getFunction());
  1689. }
  1690. /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in
  1691. /// the cases we can avoid taking the address of a function.
  1692. bool rewriteDeviceCodeStateMachine();
  1693. ///
  1694. ///}}
  1695. /// Emit a remark generically
  1696. ///
  1697. /// This template function can be used to generically emit a remark. The
  1698. /// RemarkKind should be one of the following:
  1699. /// - OptimizationRemark to indicate a successful optimization attempt
  1700. /// - OptimizationRemarkMissed to report a failed optimization attempt
  1701. /// - OptimizationRemarkAnalysis to provide additional information about an
  1702. /// optimization attempt
  1703. ///
  1704. /// The remark is built using a callback function provided by the caller that
  1705. /// takes a RemarkKind as input and returns a RemarkKind.
  1706. template <typename RemarkKind, typename RemarkCallBack>
  1707. void emitRemark(Instruction *I, StringRef RemarkName,
  1708. RemarkCallBack &&RemarkCB) const {
  1709. Function *F = I->getParent()->getParent();
  1710. auto &ORE = OREGetter(F);
  1711. if (RemarkName.startswith("OMP"))
  1712. ORE.emit([&]() {
  1713. return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I))
  1714. << " [" << RemarkName << "]";
  1715. });
  1716. else
  1717. ORE.emit(
  1718. [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)); });
  1719. }
  1720. /// Emit a remark on a function.
  1721. template <typename RemarkKind, typename RemarkCallBack>
  1722. void emitRemark(Function *F, StringRef RemarkName,
  1723. RemarkCallBack &&RemarkCB) const {
  1724. auto &ORE = OREGetter(F);
  1725. if (RemarkName.startswith("OMP"))
  1726. ORE.emit([&]() {
  1727. return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F))
  1728. << " [" << RemarkName << "]";
  1729. });
  1730. else
  1731. ORE.emit(
  1732. [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)); });
  1733. }
  1734. /// RAII struct to temporarily change an RTL function's linkage to external.
  1735. /// This prevents it from being mistakenly removed by other optimizations.
  1736. struct ExternalizationRAII {
  1737. ExternalizationRAII(OMPInformationCache &OMPInfoCache,
  1738. RuntimeFunction RFKind)
  1739. : Declaration(OMPInfoCache.RFIs[RFKind].Declaration) {
  1740. if (!Declaration)
  1741. return;
  1742. LinkageType = Declaration->getLinkage();
  1743. Declaration->setLinkage(GlobalValue::ExternalLinkage);
  1744. }
  1745. ~ExternalizationRAII() {
  1746. if (!Declaration)
  1747. return;
  1748. Declaration->setLinkage(LinkageType);
  1749. }
  1750. Function *Declaration;
  1751. GlobalValue::LinkageTypes LinkageType;
  1752. };
  1753. /// The underlying module.
  1754. Module &M;
  1755. /// The SCC we are operating on.
  1756. SmallVectorImpl<Function *> &SCC;
  1757. /// Callback to update the call graph, the first argument is a removed call,
  1758. /// the second an optional replacement call.
  1759. CallGraphUpdater &CGUpdater;
  1760. /// Callback to get an OptimizationRemarkEmitter from a Function *
  1761. OptimizationRemarkGetter OREGetter;
  1762. /// OpenMP-specific information cache. Also Used for Attributor runs.
  1763. OMPInformationCache &OMPInfoCache;
  1764. /// Attributor instance.
  1765. Attributor &A;
  1766. /// Helper function to run Attributor on SCC.
  1767. bool runAttributor(bool IsModulePass) {
  1768. if (SCC.empty())
  1769. return false;
  1770. // Temporarily make these function have external linkage so the Attributor
  1771. // doesn't remove them when we try to look them up later.
  1772. ExternalizationRAII Parallel(OMPInfoCache, OMPRTL___kmpc_kernel_parallel);
  1773. ExternalizationRAII EndParallel(OMPInfoCache,
  1774. OMPRTL___kmpc_kernel_end_parallel);
  1775. ExternalizationRAII BarrierSPMD(OMPInfoCache,
  1776. OMPRTL___kmpc_barrier_simple_spmd);
  1777. ExternalizationRAII BarrierGeneric(OMPInfoCache,
  1778. OMPRTL___kmpc_barrier_simple_generic);
  1779. ExternalizationRAII ThreadId(OMPInfoCache,
  1780. OMPRTL___kmpc_get_hardware_thread_id_in_block);
  1781. ExternalizationRAII NumThreads(
  1782. OMPInfoCache, OMPRTL___kmpc_get_hardware_num_threads_in_block);
  1783. ExternalizationRAII WarpSize(OMPInfoCache, OMPRTL___kmpc_get_warp_size);
  1784. registerAAs(IsModulePass);
  1785. ChangeStatus Changed = A.run();
  1786. LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size()
  1787. << " functions, result: " << Changed << ".\n");
  1788. return Changed == ChangeStatus::CHANGED;
  1789. }
  1790. void registerFoldRuntimeCall(RuntimeFunction RF);
  1791. /// Populate the Attributor with abstract attribute opportunities in the
  1792. /// function.
  1793. void registerAAs(bool IsModulePass);
  1794. };
  1795. Kernel OpenMPOpt::getUniqueKernelFor(Function &F) {
  1796. if (!OMPInfoCache.ModuleSlice.count(&F))
  1797. return nullptr;
  1798. // Use a scope to keep the lifetime of the CachedKernel short.
  1799. {
  1800. Optional<Kernel> &CachedKernel = UniqueKernelMap[&F];
  1801. if (CachedKernel)
  1802. return *CachedKernel;
  1803. // TODO: We should use an AA to create an (optimistic and callback
  1804. // call-aware) call graph. For now we stick to simple patterns that
  1805. // are less powerful, basically the worst fixpoint.
  1806. if (isKernel(F)) {
  1807. CachedKernel = Kernel(&F);
  1808. return *CachedKernel;
  1809. }
  1810. CachedKernel = nullptr;
  1811. if (!F.hasLocalLinkage()) {
  1812. // See https://openmp.llvm.org/remarks/OptimizationRemarks.html
  1813. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  1814. return ORA << "Potentially unknown OpenMP target region caller.";
  1815. };
  1816. emitRemark<OptimizationRemarkAnalysis>(&F, "OMP100", Remark);
  1817. return nullptr;
  1818. }
  1819. }
  1820. auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel {
  1821. if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
  1822. // Allow use in equality comparisons.
  1823. if (Cmp->isEquality())
  1824. return getUniqueKernelFor(*Cmp);
  1825. return nullptr;
  1826. }
  1827. if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
  1828. // Allow direct calls.
  1829. if (CB->isCallee(&U))
  1830. return getUniqueKernelFor(*CB);
  1831. OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
  1832. OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
  1833. // Allow the use in __kmpc_parallel_51 calls.
  1834. if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI))
  1835. return getUniqueKernelFor(*CB);
  1836. return nullptr;
  1837. }
  1838. // Disallow every other use.
  1839. return nullptr;
  1840. };
  1841. // TODO: In the future we want to track more than just a unique kernel.
  1842. SmallPtrSet<Kernel, 2> PotentialKernels;
  1843. OMPInformationCache::foreachUse(F, [&](const Use &U) {
  1844. PotentialKernels.insert(GetUniqueKernelForUse(U));
  1845. });
  1846. Kernel K = nullptr;
  1847. if (PotentialKernels.size() == 1)
  1848. K = *PotentialKernels.begin();
  1849. // Cache the result.
  1850. UniqueKernelMap[&F] = K;
  1851. return K;
  1852. }
  1853. bool OpenMPOpt::rewriteDeviceCodeStateMachine() {
  1854. OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
  1855. OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
  1856. bool Changed = false;
  1857. if (!KernelParallelRFI)
  1858. return Changed;
  1859. // If we have disabled state machine changes, exit
  1860. if (DisableOpenMPOptStateMachineRewrite)
  1861. return Changed;
  1862. for (Function *F : SCC) {
  1863. // Check if the function is a use in a __kmpc_parallel_51 call at
  1864. // all.
  1865. bool UnknownUse = false;
  1866. bool KernelParallelUse = false;
  1867. unsigned NumDirectCalls = 0;
  1868. SmallVector<Use *, 2> ToBeReplacedStateMachineUses;
  1869. OMPInformationCache::foreachUse(*F, [&](Use &U) {
  1870. if (auto *CB = dyn_cast<CallBase>(U.getUser()))
  1871. if (CB->isCallee(&U)) {
  1872. ++NumDirectCalls;
  1873. return;
  1874. }
  1875. if (isa<ICmpInst>(U.getUser())) {
  1876. ToBeReplacedStateMachineUses.push_back(&U);
  1877. return;
  1878. }
  1879. // Find wrapper functions that represent parallel kernels.
  1880. CallInst *CI =
  1881. OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI);
  1882. const unsigned int WrapperFunctionArgNo = 6;
  1883. if (!KernelParallelUse && CI &&
  1884. CI->getArgOperandNo(&U) == WrapperFunctionArgNo) {
  1885. KernelParallelUse = true;
  1886. ToBeReplacedStateMachineUses.push_back(&U);
  1887. return;
  1888. }
  1889. UnknownUse = true;
  1890. });
  1891. // Do not emit a remark if we haven't seen a __kmpc_parallel_51
  1892. // use.
  1893. if (!KernelParallelUse)
  1894. continue;
  1895. // If this ever hits, we should investigate.
  1896. // TODO: Checking the number of uses is not a necessary restriction and
  1897. // should be lifted.
  1898. if (UnknownUse || NumDirectCalls != 1 ||
  1899. ToBeReplacedStateMachineUses.size() > 2) {
  1900. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  1901. return ORA << "Parallel region is used in "
  1902. << (UnknownUse ? "unknown" : "unexpected")
  1903. << " ways. Will not attempt to rewrite the state machine.";
  1904. };
  1905. emitRemark<OptimizationRemarkAnalysis>(F, "OMP101", Remark);
  1906. continue;
  1907. }
  1908. // Even if we have __kmpc_parallel_51 calls, we (for now) give
  1909. // up if the function is not called from a unique kernel.
  1910. Kernel K = getUniqueKernelFor(*F);
  1911. if (!K) {
  1912. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  1913. return ORA << "Parallel region is not called from a unique kernel. "
  1914. "Will not attempt to rewrite the state machine.";
  1915. };
  1916. emitRemark<OptimizationRemarkAnalysis>(F, "OMP102", Remark);
  1917. continue;
  1918. }
  1919. // We now know F is a parallel body function called only from the kernel K.
  1920. // We also identified the state machine uses in which we replace the
  1921. // function pointer by a new global symbol for identification purposes. This
  1922. // ensures only direct calls to the function are left.
  1923. Module &M = *F->getParent();
  1924. Type *Int8Ty = Type::getInt8Ty(M.getContext());
  1925. auto *ID = new GlobalVariable(
  1926. M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage,
  1927. UndefValue::get(Int8Ty), F->getName() + ".ID");
  1928. for (Use *U : ToBeReplacedStateMachineUses)
  1929. U->set(ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1930. ID, U->get()->getType()));
  1931. ++NumOpenMPParallelRegionsReplacedInGPUStateMachine;
  1932. Changed = true;
  1933. }
  1934. return Changed;
  1935. }
  1936. /// Abstract Attribute for tracking ICV values.
  1937. struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> {
  1938. using Base = StateWrapper<BooleanState, AbstractAttribute>;
  1939. AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
  1940. void initialize(Attributor &A) override {
  1941. Function *F = getAnchorScope();
  1942. if (!F || !A.isFunctionIPOAmendable(*F))
  1943. indicatePessimisticFixpoint();
  1944. }
  1945. /// Returns true if value is assumed to be tracked.
  1946. bool isAssumedTracked() const { return getAssumed(); }
  1947. /// Returns true if value is known to be tracked.
  1948. bool isKnownTracked() const { return getAssumed(); }
  1949. /// Create an abstract attribute biew for the position \p IRP.
  1950. static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A);
  1951. /// Return the value with which \p I can be replaced for specific \p ICV.
  1952. virtual Optional<Value *> getReplacementValue(InternalControlVar ICV,
  1953. const Instruction *I,
  1954. Attributor &A) const {
  1955. return None;
  1956. }
  1957. /// Return an assumed unique ICV value if a single candidate is found. If
  1958. /// there cannot be one, return a nullptr. If it is not clear yet, return the
  1959. /// Optional::NoneType.
  1960. virtual Optional<Value *>
  1961. getUniqueReplacementValue(InternalControlVar ICV) const = 0;
  1962. // Currently only nthreads is being tracked.
  1963. // this array will only grow with time.
  1964. InternalControlVar TrackableICVs[1] = {ICV_nthreads};
  1965. /// See AbstractAttribute::getName()
  1966. const std::string getName() const override { return "AAICVTracker"; }
  1967. /// See AbstractAttribute::getIdAddr()
  1968. const char *getIdAddr() const override { return &ID; }
  1969. /// This function should return true if the type of the \p AA is AAICVTracker
  1970. static bool classof(const AbstractAttribute *AA) {
  1971. return (AA->getIdAddr() == &ID);
  1972. }
  1973. static const char ID;
  1974. };
  1975. struct AAICVTrackerFunction : public AAICVTracker {
  1976. AAICVTrackerFunction(const IRPosition &IRP, Attributor &A)
  1977. : AAICVTracker(IRP, A) {}
  1978. // FIXME: come up with better string.
  1979. const std::string getAsStr() const override { return "ICVTrackerFunction"; }
  1980. // FIXME: come up with some stats.
  1981. void trackStatistics() const override {}
  1982. /// We don't manifest anything for this AA.
  1983. ChangeStatus manifest(Attributor &A) override {
  1984. return ChangeStatus::UNCHANGED;
  1985. }
  1986. // Map of ICV to their values at specific program point.
  1987. EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar,
  1988. InternalControlVar::ICV___last>
  1989. ICVReplacementValuesMap;
  1990. ChangeStatus updateImpl(Attributor &A) override {
  1991. ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
  1992. Function *F = getAnchorScope();
  1993. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  1994. for (InternalControlVar ICV : TrackableICVs) {
  1995. auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
  1996. auto &ValuesMap = ICVReplacementValuesMap[ICV];
  1997. auto TrackValues = [&](Use &U, Function &) {
  1998. CallInst *CI = OpenMPOpt::getCallIfRegularCall(U);
  1999. if (!CI)
  2000. return false;
  2001. // FIXME: handle setters with more that 1 arguments.
  2002. /// Track new value.
  2003. if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second)
  2004. HasChanged = ChangeStatus::CHANGED;
  2005. return false;
  2006. };
  2007. auto CallCheck = [&](Instruction &I) {
  2008. Optional<Value *> ReplVal = getValueForCall(A, I, ICV);
  2009. if (ReplVal.hasValue() &&
  2010. ValuesMap.insert(std::make_pair(&I, *ReplVal)).second)
  2011. HasChanged = ChangeStatus::CHANGED;
  2012. return true;
  2013. };
  2014. // Track all changes of an ICV.
  2015. SetterRFI.foreachUse(TrackValues, F);
  2016. bool UsedAssumedInformation = false;
  2017. A.checkForAllInstructions(CallCheck, *this, {Instruction::Call},
  2018. UsedAssumedInformation,
  2019. /* CheckBBLivenessOnly */ true);
  2020. /// TODO: Figure out a way to avoid adding entry in
  2021. /// ICVReplacementValuesMap
  2022. Instruction *Entry = &F->getEntryBlock().front();
  2023. if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry))
  2024. ValuesMap.insert(std::make_pair(Entry, nullptr));
  2025. }
  2026. return HasChanged;
  2027. }
  2028. /// Helper to check if \p I is a call and get the value for it if it is
  2029. /// unique.
  2030. Optional<Value *> getValueForCall(Attributor &A, const Instruction &I,
  2031. InternalControlVar &ICV) const {
  2032. const auto *CB = dyn_cast<CallBase>(&I);
  2033. if (!CB || CB->hasFnAttr("no_openmp") ||
  2034. CB->hasFnAttr("no_openmp_routines"))
  2035. return None;
  2036. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2037. auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter];
  2038. auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
  2039. Function *CalledFunction = CB->getCalledFunction();
  2040. // Indirect call, assume ICV changes.
  2041. if (CalledFunction == nullptr)
  2042. return nullptr;
  2043. if (CalledFunction == GetterRFI.Declaration)
  2044. return None;
  2045. if (CalledFunction == SetterRFI.Declaration) {
  2046. if (ICVReplacementValuesMap[ICV].count(&I))
  2047. return ICVReplacementValuesMap[ICV].lookup(&I);
  2048. return nullptr;
  2049. }
  2050. // Since we don't know, assume it changes the ICV.
  2051. if (CalledFunction->isDeclaration())
  2052. return nullptr;
  2053. const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
  2054. *this, IRPosition::callsite_returned(*CB), DepClassTy::REQUIRED);
  2055. if (ICVTrackingAA.isAssumedTracked()) {
  2056. Optional<Value *> URV = ICVTrackingAA.getUniqueReplacementValue(ICV);
  2057. if (!URV || (*URV && AA::isValidAtPosition(**URV, I, OMPInfoCache)))
  2058. return URV;
  2059. }
  2060. // If we don't know, assume it changes.
  2061. return nullptr;
  2062. }
  2063. // We don't check unique value for a function, so return None.
  2064. Optional<Value *>
  2065. getUniqueReplacementValue(InternalControlVar ICV) const override {
  2066. return None;
  2067. }
  2068. /// Return the value with which \p I can be replaced for specific \p ICV.
  2069. Optional<Value *> getReplacementValue(InternalControlVar ICV,
  2070. const Instruction *I,
  2071. Attributor &A) const override {
  2072. const auto &ValuesMap = ICVReplacementValuesMap[ICV];
  2073. if (ValuesMap.count(I))
  2074. return ValuesMap.lookup(I);
  2075. SmallVector<const Instruction *, 16> Worklist;
  2076. SmallPtrSet<const Instruction *, 16> Visited;
  2077. Worklist.push_back(I);
  2078. Optional<Value *> ReplVal;
  2079. while (!Worklist.empty()) {
  2080. const Instruction *CurrInst = Worklist.pop_back_val();
  2081. if (!Visited.insert(CurrInst).second)
  2082. continue;
  2083. const BasicBlock *CurrBB = CurrInst->getParent();
  2084. // Go up and look for all potential setters/calls that might change the
  2085. // ICV.
  2086. while ((CurrInst = CurrInst->getPrevNode())) {
  2087. if (ValuesMap.count(CurrInst)) {
  2088. Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
  2089. // Unknown value, track new.
  2090. if (!ReplVal.hasValue()) {
  2091. ReplVal = NewReplVal;
  2092. break;
  2093. }
  2094. // If we found a new value, we can't know the icv value anymore.
  2095. if (NewReplVal.hasValue())
  2096. if (ReplVal != NewReplVal)
  2097. return nullptr;
  2098. break;
  2099. }
  2100. Optional<Value *> NewReplVal = getValueForCall(A, *CurrInst, ICV);
  2101. if (!NewReplVal.hasValue())
  2102. continue;
  2103. // Unknown value, track new.
  2104. if (!ReplVal.hasValue()) {
  2105. ReplVal = NewReplVal;
  2106. break;
  2107. }
  2108. // if (NewReplVal.hasValue())
  2109. // We found a new value, we can't know the icv value anymore.
  2110. if (ReplVal != NewReplVal)
  2111. return nullptr;
  2112. }
  2113. // If we are in the same BB and we have a value, we are done.
  2114. if (CurrBB == I->getParent() && ReplVal.hasValue())
  2115. return ReplVal;
  2116. // Go through all predecessors and add terminators for analysis.
  2117. for (const BasicBlock *Pred : predecessors(CurrBB))
  2118. if (const Instruction *Terminator = Pred->getTerminator())
  2119. Worklist.push_back(Terminator);
  2120. }
  2121. return ReplVal;
  2122. }
  2123. };
  2124. struct AAICVTrackerFunctionReturned : AAICVTracker {
  2125. AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A)
  2126. : AAICVTracker(IRP, A) {}
  2127. // FIXME: come up with better string.
  2128. const std::string getAsStr() const override {
  2129. return "ICVTrackerFunctionReturned";
  2130. }
  2131. // FIXME: come up with some stats.
  2132. void trackStatistics() const override {}
  2133. /// We don't manifest anything for this AA.
  2134. ChangeStatus manifest(Attributor &A) override {
  2135. return ChangeStatus::UNCHANGED;
  2136. }
  2137. // Map of ICV to their values at specific program point.
  2138. EnumeratedArray<Optional<Value *>, InternalControlVar,
  2139. InternalControlVar::ICV___last>
  2140. ICVReplacementValuesMap;
  2141. /// Return the value with which \p I can be replaced for specific \p ICV.
  2142. Optional<Value *>
  2143. getUniqueReplacementValue(InternalControlVar ICV) const override {
  2144. return ICVReplacementValuesMap[ICV];
  2145. }
  2146. ChangeStatus updateImpl(Attributor &A) override {
  2147. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  2148. const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
  2149. *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
  2150. if (!ICVTrackingAA.isAssumedTracked())
  2151. return indicatePessimisticFixpoint();
  2152. for (InternalControlVar ICV : TrackableICVs) {
  2153. Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
  2154. Optional<Value *> UniqueICVValue;
  2155. auto CheckReturnInst = [&](Instruction &I) {
  2156. Optional<Value *> NewReplVal =
  2157. ICVTrackingAA.getReplacementValue(ICV, &I, A);
  2158. // If we found a second ICV value there is no unique returned value.
  2159. if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal)
  2160. return false;
  2161. UniqueICVValue = NewReplVal;
  2162. return true;
  2163. };
  2164. bool UsedAssumedInformation = false;
  2165. if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret},
  2166. UsedAssumedInformation,
  2167. /* CheckBBLivenessOnly */ true))
  2168. UniqueICVValue = nullptr;
  2169. if (UniqueICVValue == ReplVal)
  2170. continue;
  2171. ReplVal = UniqueICVValue;
  2172. Changed = ChangeStatus::CHANGED;
  2173. }
  2174. return Changed;
  2175. }
  2176. };
  2177. struct AAICVTrackerCallSite : AAICVTracker {
  2178. AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A)
  2179. : AAICVTracker(IRP, A) {}
  2180. void initialize(Attributor &A) override {
  2181. Function *F = getAnchorScope();
  2182. if (!F || !A.isFunctionIPOAmendable(*F))
  2183. indicatePessimisticFixpoint();
  2184. // We only initialize this AA for getters, so we need to know which ICV it
  2185. // gets.
  2186. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2187. for (InternalControlVar ICV : TrackableICVs) {
  2188. auto ICVInfo = OMPInfoCache.ICVs[ICV];
  2189. auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter];
  2190. if (Getter.Declaration == getAssociatedFunction()) {
  2191. AssociatedICV = ICVInfo.Kind;
  2192. return;
  2193. }
  2194. }
  2195. /// Unknown ICV.
  2196. indicatePessimisticFixpoint();
  2197. }
  2198. ChangeStatus manifest(Attributor &A) override {
  2199. if (!ReplVal.hasValue() || !ReplVal.getValue())
  2200. return ChangeStatus::UNCHANGED;
  2201. A.changeValueAfterManifest(*getCtxI(), **ReplVal);
  2202. A.deleteAfterManifest(*getCtxI());
  2203. return ChangeStatus::CHANGED;
  2204. }
  2205. // FIXME: come up with better string.
  2206. const std::string getAsStr() const override { return "ICVTrackerCallSite"; }
  2207. // FIXME: come up with some stats.
  2208. void trackStatistics() const override {}
  2209. InternalControlVar AssociatedICV;
  2210. Optional<Value *> ReplVal;
  2211. ChangeStatus updateImpl(Attributor &A) override {
  2212. const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
  2213. *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
  2214. // We don't have any information, so we assume it changes the ICV.
  2215. if (!ICVTrackingAA.isAssumedTracked())
  2216. return indicatePessimisticFixpoint();
  2217. Optional<Value *> NewReplVal =
  2218. ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A);
  2219. if (ReplVal == NewReplVal)
  2220. return ChangeStatus::UNCHANGED;
  2221. ReplVal = NewReplVal;
  2222. return ChangeStatus::CHANGED;
  2223. }
  2224. // Return the value with which associated value can be replaced for specific
  2225. // \p ICV.
  2226. Optional<Value *>
  2227. getUniqueReplacementValue(InternalControlVar ICV) const override {
  2228. return ReplVal;
  2229. }
  2230. };
  2231. struct AAICVTrackerCallSiteReturned : AAICVTracker {
  2232. AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A)
  2233. : AAICVTracker(IRP, A) {}
  2234. // FIXME: come up with better string.
  2235. const std::string getAsStr() const override {
  2236. return "ICVTrackerCallSiteReturned";
  2237. }
  2238. // FIXME: come up with some stats.
  2239. void trackStatistics() const override {}
  2240. /// We don't manifest anything for this AA.
  2241. ChangeStatus manifest(Attributor &A) override {
  2242. return ChangeStatus::UNCHANGED;
  2243. }
  2244. // Map of ICV to their values at specific program point.
  2245. EnumeratedArray<Optional<Value *>, InternalControlVar,
  2246. InternalControlVar::ICV___last>
  2247. ICVReplacementValuesMap;
  2248. /// Return the value with which associated value can be replaced for specific
  2249. /// \p ICV.
  2250. Optional<Value *>
  2251. getUniqueReplacementValue(InternalControlVar ICV) const override {
  2252. return ICVReplacementValuesMap[ICV];
  2253. }
  2254. ChangeStatus updateImpl(Attributor &A) override {
  2255. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  2256. const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
  2257. *this, IRPosition::returned(*getAssociatedFunction()),
  2258. DepClassTy::REQUIRED);
  2259. // We don't have any information, so we assume it changes the ICV.
  2260. if (!ICVTrackingAA.isAssumedTracked())
  2261. return indicatePessimisticFixpoint();
  2262. for (InternalControlVar ICV : TrackableICVs) {
  2263. Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
  2264. Optional<Value *> NewReplVal =
  2265. ICVTrackingAA.getUniqueReplacementValue(ICV);
  2266. if (ReplVal == NewReplVal)
  2267. continue;
  2268. ReplVal = NewReplVal;
  2269. Changed = ChangeStatus::CHANGED;
  2270. }
  2271. return Changed;
  2272. }
  2273. };
  2274. struct AAExecutionDomainFunction : public AAExecutionDomain {
  2275. AAExecutionDomainFunction(const IRPosition &IRP, Attributor &A)
  2276. : AAExecutionDomain(IRP, A) {}
  2277. const std::string getAsStr() const override {
  2278. return "[AAExecutionDomain] " + std::to_string(SingleThreadedBBs.size()) +
  2279. "/" + std::to_string(NumBBs) + " BBs thread 0 only.";
  2280. }
  2281. /// See AbstractAttribute::trackStatistics().
  2282. void trackStatistics() const override {}
  2283. void initialize(Attributor &A) override {
  2284. Function *F = getAnchorScope();
  2285. for (const auto &BB : *F)
  2286. SingleThreadedBBs.insert(&BB);
  2287. NumBBs = SingleThreadedBBs.size();
  2288. }
  2289. ChangeStatus manifest(Attributor &A) override {
  2290. LLVM_DEBUG({
  2291. for (const BasicBlock *BB : SingleThreadedBBs)
  2292. dbgs() << TAG << " Basic block @" << getAnchorScope()->getName() << " "
  2293. << BB->getName() << " is executed by a single thread.\n";
  2294. });
  2295. return ChangeStatus::UNCHANGED;
  2296. }
  2297. ChangeStatus updateImpl(Attributor &A) override;
  2298. /// Check if an instruction is executed by a single thread.
  2299. bool isExecutedByInitialThreadOnly(const Instruction &I) const override {
  2300. return isExecutedByInitialThreadOnly(*I.getParent());
  2301. }
  2302. bool isExecutedByInitialThreadOnly(const BasicBlock &BB) const override {
  2303. return isValidState() && SingleThreadedBBs.contains(&BB);
  2304. }
  2305. /// Set of basic blocks that are executed by a single thread.
  2306. SmallSetVector<const BasicBlock *, 16> SingleThreadedBBs;
  2307. /// Total number of basic blocks in this function.
  2308. long unsigned NumBBs;
  2309. };
  2310. ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) {
  2311. Function *F = getAnchorScope();
  2312. ReversePostOrderTraversal<Function *> RPOT(F);
  2313. auto NumSingleThreadedBBs = SingleThreadedBBs.size();
  2314. bool AllCallSitesKnown;
  2315. auto PredForCallSite = [&](AbstractCallSite ACS) {
  2316. const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
  2317. *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
  2318. DepClassTy::REQUIRED);
  2319. return ACS.isDirectCall() &&
  2320. ExecutionDomainAA.isExecutedByInitialThreadOnly(
  2321. *ACS.getInstruction());
  2322. };
  2323. if (!A.checkForAllCallSites(PredForCallSite, *this,
  2324. /* RequiresAllCallSites */ true,
  2325. AllCallSitesKnown))
  2326. SingleThreadedBBs.remove(&F->getEntryBlock());
  2327. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2328. auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
  2329. // Check if the edge into the successor block contains a condition that only
  2330. // lets the main thread execute it.
  2331. auto IsInitialThreadOnly = [&](BranchInst *Edge, BasicBlock *SuccessorBB) {
  2332. if (!Edge || !Edge->isConditional())
  2333. return false;
  2334. if (Edge->getSuccessor(0) != SuccessorBB)
  2335. return false;
  2336. auto *Cmp = dyn_cast<CmpInst>(Edge->getCondition());
  2337. if (!Cmp || !Cmp->isTrueWhenEqual() || !Cmp->isEquality())
  2338. return false;
  2339. ConstantInt *C = dyn_cast<ConstantInt>(Cmp->getOperand(1));
  2340. if (!C)
  2341. return false;
  2342. // Match: -1 == __kmpc_target_init (for non-SPMD kernels only!)
  2343. if (C->isAllOnesValue()) {
  2344. auto *CB = dyn_cast<CallBase>(Cmp->getOperand(0));
  2345. CB = CB ? OpenMPOpt::getCallIfRegularCall(*CB, &RFI) : nullptr;
  2346. if (!CB)
  2347. return false;
  2348. const int InitModeArgNo = 1;
  2349. auto *ModeCI = dyn_cast<ConstantInt>(CB->getOperand(InitModeArgNo));
  2350. return ModeCI && (ModeCI->getSExtValue() & OMP_TGT_EXEC_MODE_GENERIC);
  2351. }
  2352. if (C->isZero()) {
  2353. // Match: 0 == llvm.nvvm.read.ptx.sreg.tid.x()
  2354. if (auto *II = dyn_cast<IntrinsicInst>(Cmp->getOperand(0)))
  2355. if (II->getIntrinsicID() == Intrinsic::nvvm_read_ptx_sreg_tid_x)
  2356. return true;
  2357. // Match: 0 == llvm.amdgcn.workitem.id.x()
  2358. if (auto *II = dyn_cast<IntrinsicInst>(Cmp->getOperand(0)))
  2359. if (II->getIntrinsicID() == Intrinsic::amdgcn_workitem_id_x)
  2360. return true;
  2361. }
  2362. return false;
  2363. };
  2364. // Merge all the predecessor states into the current basic block. A basic
  2365. // block is executed by a single thread if all of its predecessors are.
  2366. auto MergePredecessorStates = [&](BasicBlock *BB) {
  2367. if (pred_empty(BB))
  2368. return SingleThreadedBBs.contains(BB);
  2369. bool IsInitialThread = true;
  2370. for (BasicBlock *PredBB : predecessors(BB)) {
  2371. if (!IsInitialThreadOnly(dyn_cast<BranchInst>(PredBB->getTerminator()),
  2372. BB))
  2373. IsInitialThread &= SingleThreadedBBs.contains(PredBB);
  2374. }
  2375. return IsInitialThread;
  2376. };
  2377. for (auto *BB : RPOT) {
  2378. if (!MergePredecessorStates(BB))
  2379. SingleThreadedBBs.remove(BB);
  2380. }
  2381. return (NumSingleThreadedBBs == SingleThreadedBBs.size())
  2382. ? ChangeStatus::UNCHANGED
  2383. : ChangeStatus::CHANGED;
  2384. }
  2385. /// Try to replace memory allocation calls called by a single thread with a
  2386. /// static buffer of shared memory.
  2387. struct AAHeapToShared : public StateWrapper<BooleanState, AbstractAttribute> {
  2388. using Base = StateWrapper<BooleanState, AbstractAttribute>;
  2389. AAHeapToShared(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
  2390. /// Create an abstract attribute view for the position \p IRP.
  2391. static AAHeapToShared &createForPosition(const IRPosition &IRP,
  2392. Attributor &A);
  2393. /// Returns true if HeapToShared conversion is assumed to be possible.
  2394. virtual bool isAssumedHeapToShared(CallBase &CB) const = 0;
  2395. /// Returns true if HeapToShared conversion is assumed and the CB is a
  2396. /// callsite to a free operation to be removed.
  2397. virtual bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const = 0;
  2398. /// See AbstractAttribute::getName().
  2399. const std::string getName() const override { return "AAHeapToShared"; }
  2400. /// See AbstractAttribute::getIdAddr().
  2401. const char *getIdAddr() const override { return &ID; }
  2402. /// This function should return true if the type of the \p AA is
  2403. /// AAHeapToShared.
  2404. static bool classof(const AbstractAttribute *AA) {
  2405. return (AA->getIdAddr() == &ID);
  2406. }
  2407. /// Unique ID (due to the unique address)
  2408. static const char ID;
  2409. };
  2410. struct AAHeapToSharedFunction : public AAHeapToShared {
  2411. AAHeapToSharedFunction(const IRPosition &IRP, Attributor &A)
  2412. : AAHeapToShared(IRP, A) {}
  2413. const std::string getAsStr() const override {
  2414. return "[AAHeapToShared] " + std::to_string(MallocCalls.size()) +
  2415. " malloc calls eligible.";
  2416. }
  2417. /// See AbstractAttribute::trackStatistics().
  2418. void trackStatistics() const override {}
  2419. /// This functions finds free calls that will be removed by the
  2420. /// HeapToShared transformation.
  2421. void findPotentialRemovedFreeCalls(Attributor &A) {
  2422. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2423. auto &FreeRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
  2424. PotentialRemovedFreeCalls.clear();
  2425. // Update free call users of found malloc calls.
  2426. for (CallBase *CB : MallocCalls) {
  2427. SmallVector<CallBase *, 4> FreeCalls;
  2428. for (auto *U : CB->users()) {
  2429. CallBase *C = dyn_cast<CallBase>(U);
  2430. if (C && C->getCalledFunction() == FreeRFI.Declaration)
  2431. FreeCalls.push_back(C);
  2432. }
  2433. if (FreeCalls.size() != 1)
  2434. continue;
  2435. PotentialRemovedFreeCalls.insert(FreeCalls.front());
  2436. }
  2437. }
  2438. void initialize(Attributor &A) override {
  2439. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2440. auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
  2441. for (User *U : RFI.Declaration->users())
  2442. if (CallBase *CB = dyn_cast<CallBase>(U))
  2443. MallocCalls.insert(CB);
  2444. findPotentialRemovedFreeCalls(A);
  2445. }
  2446. bool isAssumedHeapToShared(CallBase &CB) const override {
  2447. return isValidState() && MallocCalls.count(&CB);
  2448. }
  2449. bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const override {
  2450. return isValidState() && PotentialRemovedFreeCalls.count(&CB);
  2451. }
  2452. ChangeStatus manifest(Attributor &A) override {
  2453. if (MallocCalls.empty())
  2454. return ChangeStatus::UNCHANGED;
  2455. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2456. auto &FreeCall = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
  2457. Function *F = getAnchorScope();
  2458. auto *HS = A.lookupAAFor<AAHeapToStack>(IRPosition::function(*F), this,
  2459. DepClassTy::OPTIONAL);
  2460. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  2461. for (CallBase *CB : MallocCalls) {
  2462. // Skip replacing this if HeapToStack has already claimed it.
  2463. if (HS && HS->isAssumedHeapToStack(*CB))
  2464. continue;
  2465. // Find the unique free call to remove it.
  2466. SmallVector<CallBase *, 4> FreeCalls;
  2467. for (auto *U : CB->users()) {
  2468. CallBase *C = dyn_cast<CallBase>(U);
  2469. if (C && C->getCalledFunction() == FreeCall.Declaration)
  2470. FreeCalls.push_back(C);
  2471. }
  2472. if (FreeCalls.size() != 1)
  2473. continue;
  2474. auto *AllocSize = cast<ConstantInt>(CB->getArgOperand(0));
  2475. LLVM_DEBUG(dbgs() << TAG << "Replace globalization call " << *CB
  2476. << " with " << AllocSize->getZExtValue()
  2477. << " bytes of shared memory\n");
  2478. // Create a new shared memory buffer of the same size as the allocation
  2479. // and replace all the uses of the original allocation with it.
  2480. Module *M = CB->getModule();
  2481. Type *Int8Ty = Type::getInt8Ty(M->getContext());
  2482. Type *Int8ArrTy = ArrayType::get(Int8Ty, AllocSize->getZExtValue());
  2483. auto *SharedMem = new GlobalVariable(
  2484. *M, Int8ArrTy, /* IsConstant */ false, GlobalValue::InternalLinkage,
  2485. UndefValue::get(Int8ArrTy), CB->getName() + "_shared", nullptr,
  2486. GlobalValue::NotThreadLocal,
  2487. static_cast<unsigned>(AddressSpace::Shared));
  2488. auto *NewBuffer =
  2489. ConstantExpr::getPointerCast(SharedMem, Int8Ty->getPointerTo());
  2490. auto Remark = [&](OptimizationRemark OR) {
  2491. return OR << "Replaced globalized variable with "
  2492. << ore::NV("SharedMemory", AllocSize->getZExtValue())
  2493. << ((AllocSize->getZExtValue() != 1) ? " bytes " : " byte ")
  2494. << "of shared memory.";
  2495. };
  2496. A.emitRemark<OptimizationRemark>(CB, "OMP111", Remark);
  2497. MaybeAlign Alignment = CB->getRetAlign();
  2498. assert(Alignment &&
  2499. "HeapToShared on allocation without alignment attribute");
  2500. SharedMem->setAlignment(MaybeAlign(Alignment));
  2501. A.changeValueAfterManifest(*CB, *NewBuffer);
  2502. A.deleteAfterManifest(*CB);
  2503. A.deleteAfterManifest(*FreeCalls.front());
  2504. NumBytesMovedToSharedMemory += AllocSize->getZExtValue();
  2505. Changed = ChangeStatus::CHANGED;
  2506. }
  2507. return Changed;
  2508. }
  2509. ChangeStatus updateImpl(Attributor &A) override {
  2510. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2511. auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
  2512. Function *F = getAnchorScope();
  2513. auto NumMallocCalls = MallocCalls.size();
  2514. // Only consider malloc calls executed by a single thread with a constant.
  2515. for (User *U : RFI.Declaration->users()) {
  2516. const auto &ED = A.getAAFor<AAExecutionDomain>(
  2517. *this, IRPosition::function(*F), DepClassTy::REQUIRED);
  2518. if (CallBase *CB = dyn_cast<CallBase>(U))
  2519. if (!isa<ConstantInt>(CB->getArgOperand(0)) ||
  2520. !ED.isExecutedByInitialThreadOnly(*CB))
  2521. MallocCalls.remove(CB);
  2522. }
  2523. findPotentialRemovedFreeCalls(A);
  2524. if (NumMallocCalls != MallocCalls.size())
  2525. return ChangeStatus::CHANGED;
  2526. return ChangeStatus::UNCHANGED;
  2527. }
  2528. /// Collection of all malloc calls in a function.
  2529. SmallSetVector<CallBase *, 4> MallocCalls;
  2530. /// Collection of potentially removed free calls in a function.
  2531. SmallPtrSet<CallBase *, 4> PotentialRemovedFreeCalls;
  2532. };
  2533. struct AAKernelInfo : public StateWrapper<KernelInfoState, AbstractAttribute> {
  2534. using Base = StateWrapper<KernelInfoState, AbstractAttribute>;
  2535. AAKernelInfo(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
  2536. /// Statistics are tracked as part of manifest for now.
  2537. void trackStatistics() const override {}
  2538. /// See AbstractAttribute::getAsStr()
  2539. const std::string getAsStr() const override {
  2540. if (!isValidState())
  2541. return "<invalid>";
  2542. return std::string(SPMDCompatibilityTracker.isAssumed() ? "SPMD"
  2543. : "generic") +
  2544. std::string(SPMDCompatibilityTracker.isAtFixpoint() ? " [FIX]"
  2545. : "") +
  2546. std::string(" #PRs: ") +
  2547. (ReachedKnownParallelRegions.isValidState()
  2548. ? std::to_string(ReachedKnownParallelRegions.size())
  2549. : "<invalid>") +
  2550. ", #Unknown PRs: " +
  2551. (ReachedUnknownParallelRegions.isValidState()
  2552. ? std::to_string(ReachedUnknownParallelRegions.size())
  2553. : "<invalid>") +
  2554. ", #Reaching Kernels: " +
  2555. (ReachingKernelEntries.isValidState()
  2556. ? std::to_string(ReachingKernelEntries.size())
  2557. : "<invalid>");
  2558. }
  2559. /// Create an abstract attribute biew for the position \p IRP.
  2560. static AAKernelInfo &createForPosition(const IRPosition &IRP, Attributor &A);
  2561. /// See AbstractAttribute::getName()
  2562. const std::string getName() const override { return "AAKernelInfo"; }
  2563. /// See AbstractAttribute::getIdAddr()
  2564. const char *getIdAddr() const override { return &ID; }
  2565. /// This function should return true if the type of the \p AA is AAKernelInfo
  2566. static bool classof(const AbstractAttribute *AA) {
  2567. return (AA->getIdAddr() == &ID);
  2568. }
  2569. static const char ID;
  2570. };
  2571. /// The function kernel info abstract attribute, basically, what can we say
  2572. /// about a function with regards to the KernelInfoState.
  2573. struct AAKernelInfoFunction : AAKernelInfo {
  2574. AAKernelInfoFunction(const IRPosition &IRP, Attributor &A)
  2575. : AAKernelInfo(IRP, A) {}
  2576. SmallPtrSet<Instruction *, 4> GuardedInstructions;
  2577. SmallPtrSetImpl<Instruction *> &getGuardedInstructions() {
  2578. return GuardedInstructions;
  2579. }
  2580. /// See AbstractAttribute::initialize(...).
  2581. void initialize(Attributor &A) override {
  2582. // This is a high-level transform that might change the constant arguments
  2583. // of the init and dinit calls. We need to tell the Attributor about this
  2584. // to avoid other parts using the current constant value for simpliication.
  2585. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2586. Function *Fn = getAnchorScope();
  2587. if (!OMPInfoCache.Kernels.count(Fn))
  2588. return;
  2589. // Add itself to the reaching kernel and set IsKernelEntry.
  2590. ReachingKernelEntries.insert(Fn);
  2591. IsKernelEntry = true;
  2592. OMPInformationCache::RuntimeFunctionInfo &InitRFI =
  2593. OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
  2594. OMPInformationCache::RuntimeFunctionInfo &DeinitRFI =
  2595. OMPInfoCache.RFIs[OMPRTL___kmpc_target_deinit];
  2596. // For kernels we perform more initialization work, first we find the init
  2597. // and deinit calls.
  2598. auto StoreCallBase = [](Use &U,
  2599. OMPInformationCache::RuntimeFunctionInfo &RFI,
  2600. CallBase *&Storage) {
  2601. CallBase *CB = OpenMPOpt::getCallIfRegularCall(U, &RFI);
  2602. assert(CB &&
  2603. "Unexpected use of __kmpc_target_init or __kmpc_target_deinit!");
  2604. assert(!Storage &&
  2605. "Multiple uses of __kmpc_target_init or __kmpc_target_deinit!");
  2606. Storage = CB;
  2607. return false;
  2608. };
  2609. InitRFI.foreachUse(
  2610. [&](Use &U, Function &) {
  2611. StoreCallBase(U, InitRFI, KernelInitCB);
  2612. return false;
  2613. },
  2614. Fn);
  2615. DeinitRFI.foreachUse(
  2616. [&](Use &U, Function &) {
  2617. StoreCallBase(U, DeinitRFI, KernelDeinitCB);
  2618. return false;
  2619. },
  2620. Fn);
  2621. // Ignore kernels without initializers such as global constructors.
  2622. if (!KernelInitCB || !KernelDeinitCB) {
  2623. indicateOptimisticFixpoint();
  2624. return;
  2625. }
  2626. // For kernels we might need to initialize/finalize the IsSPMD state and
  2627. // we need to register a simplification callback so that the Attributor
  2628. // knows the constant arguments to __kmpc_target_init and
  2629. // __kmpc_target_deinit might actually change.
  2630. Attributor::SimplifictionCallbackTy StateMachineSimplifyCB =
  2631. [&](const IRPosition &IRP, const AbstractAttribute *AA,
  2632. bool &UsedAssumedInformation) -> Optional<Value *> {
  2633. // IRP represents the "use generic state machine" argument of an
  2634. // __kmpc_target_init call. We will answer this one with the internal
  2635. // state. As long as we are not in an invalid state, we will create a
  2636. // custom state machine so the value should be a `i1 false`. If we are
  2637. // in an invalid state, we won't change the value that is in the IR.
  2638. if (!ReachedKnownParallelRegions.isValidState())
  2639. return nullptr;
  2640. // If we have disabled state machine rewrites, don't make a custom one.
  2641. if (DisableOpenMPOptStateMachineRewrite)
  2642. return nullptr;
  2643. if (AA)
  2644. A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
  2645. UsedAssumedInformation = !isAtFixpoint();
  2646. auto *FalseVal =
  2647. ConstantInt::getBool(IRP.getAnchorValue().getContext(), false);
  2648. return FalseVal;
  2649. };
  2650. Attributor::SimplifictionCallbackTy ModeSimplifyCB =
  2651. [&](const IRPosition &IRP, const AbstractAttribute *AA,
  2652. bool &UsedAssumedInformation) -> Optional<Value *> {
  2653. // IRP represents the "SPMDCompatibilityTracker" argument of an
  2654. // __kmpc_target_init or
  2655. // __kmpc_target_deinit call. We will answer this one with the internal
  2656. // state.
  2657. if (!SPMDCompatibilityTracker.isValidState())
  2658. return nullptr;
  2659. if (!SPMDCompatibilityTracker.isAtFixpoint()) {
  2660. if (AA)
  2661. A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
  2662. UsedAssumedInformation = true;
  2663. } else {
  2664. UsedAssumedInformation = false;
  2665. }
  2666. auto *Val = ConstantInt::getSigned(
  2667. IntegerType::getInt8Ty(IRP.getAnchorValue().getContext()),
  2668. SPMDCompatibilityTracker.isAssumed() ? OMP_TGT_EXEC_MODE_SPMD
  2669. : OMP_TGT_EXEC_MODE_GENERIC);
  2670. return Val;
  2671. };
  2672. Attributor::SimplifictionCallbackTy IsGenericModeSimplifyCB =
  2673. [&](const IRPosition &IRP, const AbstractAttribute *AA,
  2674. bool &UsedAssumedInformation) -> Optional<Value *> {
  2675. // IRP represents the "RequiresFullRuntime" argument of an
  2676. // __kmpc_target_init or __kmpc_target_deinit call. We will answer this
  2677. // one with the internal state of the SPMDCompatibilityTracker, so if
  2678. // generic then true, if SPMD then false.
  2679. if (!SPMDCompatibilityTracker.isValidState())
  2680. return nullptr;
  2681. if (!SPMDCompatibilityTracker.isAtFixpoint()) {
  2682. if (AA)
  2683. A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
  2684. UsedAssumedInformation = true;
  2685. } else {
  2686. UsedAssumedInformation = false;
  2687. }
  2688. auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
  2689. !SPMDCompatibilityTracker.isAssumed());
  2690. return Val;
  2691. };
  2692. constexpr const int InitModeArgNo = 1;
  2693. constexpr const int DeinitModeArgNo = 1;
  2694. constexpr const int InitUseStateMachineArgNo = 2;
  2695. constexpr const int InitRequiresFullRuntimeArgNo = 3;
  2696. constexpr const int DeinitRequiresFullRuntimeArgNo = 2;
  2697. A.registerSimplificationCallback(
  2698. IRPosition::callsite_argument(*KernelInitCB, InitUseStateMachineArgNo),
  2699. StateMachineSimplifyCB);
  2700. A.registerSimplificationCallback(
  2701. IRPosition::callsite_argument(*KernelInitCB, InitModeArgNo),
  2702. ModeSimplifyCB);
  2703. A.registerSimplificationCallback(
  2704. IRPosition::callsite_argument(*KernelDeinitCB, DeinitModeArgNo),
  2705. ModeSimplifyCB);
  2706. A.registerSimplificationCallback(
  2707. IRPosition::callsite_argument(*KernelInitCB,
  2708. InitRequiresFullRuntimeArgNo),
  2709. IsGenericModeSimplifyCB);
  2710. A.registerSimplificationCallback(
  2711. IRPosition::callsite_argument(*KernelDeinitCB,
  2712. DeinitRequiresFullRuntimeArgNo),
  2713. IsGenericModeSimplifyCB);
  2714. // Check if we know we are in SPMD-mode already.
  2715. ConstantInt *ModeArg =
  2716. dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitModeArgNo));
  2717. if (ModeArg && (ModeArg->getSExtValue() & OMP_TGT_EXEC_MODE_SPMD))
  2718. SPMDCompatibilityTracker.indicateOptimisticFixpoint();
  2719. // This is a generic region but SPMDization is disabled so stop tracking.
  2720. else if (DisableOpenMPOptSPMDization)
  2721. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  2722. }
  2723. /// Sanitize the string \p S such that it is a suitable global symbol name.
  2724. static std::string sanitizeForGlobalName(std::string S) {
  2725. std::replace_if(
  2726. S.begin(), S.end(),
  2727. [](const char C) {
  2728. return !((C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') ||
  2729. (C >= '0' && C <= '9') || C == '_');
  2730. },
  2731. '.');
  2732. return S;
  2733. }
  2734. /// Modify the IR based on the KernelInfoState as the fixpoint iteration is
  2735. /// finished now.
  2736. ChangeStatus manifest(Attributor &A) override {
  2737. // If we are not looking at a kernel with __kmpc_target_init and
  2738. // __kmpc_target_deinit call we cannot actually manifest the information.
  2739. if (!KernelInitCB || !KernelDeinitCB)
  2740. return ChangeStatus::UNCHANGED;
  2741. // If we can we change the execution mode to SPMD-mode otherwise we build a
  2742. // custom state machine.
  2743. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  2744. if (!changeToSPMDMode(A, Changed))
  2745. return buildCustomStateMachine(A);
  2746. return Changed;
  2747. }
  2748. bool changeToSPMDMode(Attributor &A, ChangeStatus &Changed) {
  2749. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2750. if (!SPMDCompatibilityTracker.isAssumed()) {
  2751. for (Instruction *NonCompatibleI : SPMDCompatibilityTracker) {
  2752. if (!NonCompatibleI)
  2753. continue;
  2754. // Skip diagnostics on calls to known OpenMP runtime functions for now.
  2755. if (auto *CB = dyn_cast<CallBase>(NonCompatibleI))
  2756. if (OMPInfoCache.RTLFunctions.contains(CB->getCalledFunction()))
  2757. continue;
  2758. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  2759. ORA << "Value has potential side effects preventing SPMD-mode "
  2760. "execution";
  2761. if (isa<CallBase>(NonCompatibleI)) {
  2762. ORA << ". Add `__attribute__((assume(\"ompx_spmd_amenable\")))` to "
  2763. "the called function to override";
  2764. }
  2765. return ORA << ".";
  2766. };
  2767. A.emitRemark<OptimizationRemarkAnalysis>(NonCompatibleI, "OMP121",
  2768. Remark);
  2769. LLVM_DEBUG(dbgs() << TAG << "SPMD-incompatible side-effect: "
  2770. << *NonCompatibleI << "\n");
  2771. }
  2772. return false;
  2773. }
  2774. // Check if the kernel is already in SPMD mode, if so, return success.
  2775. Function *Kernel = getAnchorScope();
  2776. GlobalVariable *ExecMode = Kernel->getParent()->getGlobalVariable(
  2777. (Kernel->getName() + "_exec_mode").str());
  2778. assert(ExecMode && "Kernel without exec mode?");
  2779. assert(ExecMode->getInitializer() && "ExecMode doesn't have initializer!");
  2780. // Set the global exec mode flag to indicate SPMD-Generic mode.
  2781. assert(isa<ConstantInt>(ExecMode->getInitializer()) &&
  2782. "ExecMode is not an integer!");
  2783. const int8_t ExecModeVal =
  2784. cast<ConstantInt>(ExecMode->getInitializer())->getSExtValue();
  2785. if (ExecModeVal != OMP_TGT_EXEC_MODE_GENERIC)
  2786. return true;
  2787. // We will now unconditionally modify the IR, indicate a change.
  2788. Changed = ChangeStatus::CHANGED;
  2789. auto CreateGuardedRegion = [&](Instruction *RegionStartI,
  2790. Instruction *RegionEndI) {
  2791. LoopInfo *LI = nullptr;
  2792. DominatorTree *DT = nullptr;
  2793. MemorySSAUpdater *MSU = nullptr;
  2794. using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
  2795. BasicBlock *ParentBB = RegionStartI->getParent();
  2796. Function *Fn = ParentBB->getParent();
  2797. Module &M = *Fn->getParent();
  2798. // Create all the blocks and logic.
  2799. // ParentBB:
  2800. // goto RegionCheckTidBB
  2801. // RegionCheckTidBB:
  2802. // Tid = __kmpc_hardware_thread_id()
  2803. // if (Tid != 0)
  2804. // goto RegionBarrierBB
  2805. // RegionStartBB:
  2806. // <execute instructions guarded>
  2807. // goto RegionEndBB
  2808. // RegionEndBB:
  2809. // <store escaping values to shared mem>
  2810. // goto RegionBarrierBB
  2811. // RegionBarrierBB:
  2812. // __kmpc_simple_barrier_spmd()
  2813. // // second barrier is omitted if lacking escaping values.
  2814. // <load escaping values from shared mem>
  2815. // __kmpc_simple_barrier_spmd()
  2816. // goto RegionExitBB
  2817. // RegionExitBB:
  2818. // <execute rest of instructions>
  2819. BasicBlock *RegionEndBB = SplitBlock(ParentBB, RegionEndI->getNextNode(),
  2820. DT, LI, MSU, "region.guarded.end");
  2821. BasicBlock *RegionBarrierBB =
  2822. SplitBlock(RegionEndBB, &*RegionEndBB->getFirstInsertionPt(), DT, LI,
  2823. MSU, "region.barrier");
  2824. BasicBlock *RegionExitBB =
  2825. SplitBlock(RegionBarrierBB, &*RegionBarrierBB->getFirstInsertionPt(),
  2826. DT, LI, MSU, "region.exit");
  2827. BasicBlock *RegionStartBB =
  2828. SplitBlock(ParentBB, RegionStartI, DT, LI, MSU, "region.guarded");
  2829. assert(ParentBB->getUniqueSuccessor() == RegionStartBB &&
  2830. "Expected a different CFG");
  2831. BasicBlock *RegionCheckTidBB = SplitBlock(
  2832. ParentBB, ParentBB->getTerminator(), DT, LI, MSU, "region.check.tid");
  2833. // Register basic blocks with the Attributor.
  2834. A.registerManifestAddedBasicBlock(*RegionEndBB);
  2835. A.registerManifestAddedBasicBlock(*RegionBarrierBB);
  2836. A.registerManifestAddedBasicBlock(*RegionExitBB);
  2837. A.registerManifestAddedBasicBlock(*RegionStartBB);
  2838. A.registerManifestAddedBasicBlock(*RegionCheckTidBB);
  2839. bool HasBroadcastValues = false;
  2840. // Find escaping outputs from the guarded region to outside users and
  2841. // broadcast their values to them.
  2842. for (Instruction &I : *RegionStartBB) {
  2843. SmallPtrSet<Instruction *, 4> OutsideUsers;
  2844. for (User *Usr : I.users()) {
  2845. Instruction &UsrI = *cast<Instruction>(Usr);
  2846. if (UsrI.getParent() != RegionStartBB)
  2847. OutsideUsers.insert(&UsrI);
  2848. }
  2849. if (OutsideUsers.empty())
  2850. continue;
  2851. HasBroadcastValues = true;
  2852. // Emit a global variable in shared memory to store the broadcasted
  2853. // value.
  2854. auto *SharedMem = new GlobalVariable(
  2855. M, I.getType(), /* IsConstant */ false,
  2856. GlobalValue::InternalLinkage, UndefValue::get(I.getType()),
  2857. sanitizeForGlobalName(
  2858. (I.getName() + ".guarded.output.alloc").str()),
  2859. nullptr, GlobalValue::NotThreadLocal,
  2860. static_cast<unsigned>(AddressSpace::Shared));
  2861. // Emit a store instruction to update the value.
  2862. new StoreInst(&I, SharedMem, RegionEndBB->getTerminator());
  2863. LoadInst *LoadI = new LoadInst(I.getType(), SharedMem,
  2864. I.getName() + ".guarded.output.load",
  2865. RegionBarrierBB->getTerminator());
  2866. // Emit a load instruction and replace uses of the output value.
  2867. for (Instruction *UsrI : OutsideUsers)
  2868. UsrI->replaceUsesOfWith(&I, LoadI);
  2869. }
  2870. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  2871. // Go to tid check BB in ParentBB.
  2872. const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc();
  2873. ParentBB->getTerminator()->eraseFromParent();
  2874. OpenMPIRBuilder::LocationDescription Loc(
  2875. InsertPointTy(ParentBB, ParentBB->end()), DL);
  2876. OMPInfoCache.OMPBuilder.updateToLocation(Loc);
  2877. uint32_t SrcLocStrSize;
  2878. auto *SrcLocStr =
  2879. OMPInfoCache.OMPBuilder.getOrCreateSrcLocStr(Loc, SrcLocStrSize);
  2880. Value *Ident =
  2881. OMPInfoCache.OMPBuilder.getOrCreateIdent(SrcLocStr, SrcLocStrSize);
  2882. BranchInst::Create(RegionCheckTidBB, ParentBB)->setDebugLoc(DL);
  2883. // Add check for Tid in RegionCheckTidBB
  2884. RegionCheckTidBB->getTerminator()->eraseFromParent();
  2885. OpenMPIRBuilder::LocationDescription LocRegionCheckTid(
  2886. InsertPointTy(RegionCheckTidBB, RegionCheckTidBB->end()), DL);
  2887. OMPInfoCache.OMPBuilder.updateToLocation(LocRegionCheckTid);
  2888. FunctionCallee HardwareTidFn =
  2889. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  2890. M, OMPRTL___kmpc_get_hardware_thread_id_in_block);
  2891. CallInst *Tid =
  2892. OMPInfoCache.OMPBuilder.Builder.CreateCall(HardwareTidFn, {});
  2893. Tid->setDebugLoc(DL);
  2894. OMPInfoCache.setCallingConvention(HardwareTidFn, Tid);
  2895. Value *TidCheck = OMPInfoCache.OMPBuilder.Builder.CreateIsNull(Tid);
  2896. OMPInfoCache.OMPBuilder.Builder
  2897. .CreateCondBr(TidCheck, RegionStartBB, RegionBarrierBB)
  2898. ->setDebugLoc(DL);
  2899. // First barrier for synchronization, ensures main thread has updated
  2900. // values.
  2901. FunctionCallee BarrierFn =
  2902. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  2903. M, OMPRTL___kmpc_barrier_simple_spmd);
  2904. OMPInfoCache.OMPBuilder.updateToLocation(InsertPointTy(
  2905. RegionBarrierBB, RegionBarrierBB->getFirstInsertionPt()));
  2906. CallInst *Barrier =
  2907. OMPInfoCache.OMPBuilder.Builder.CreateCall(BarrierFn, {Ident, Tid});
  2908. Barrier->setDebugLoc(DL);
  2909. OMPInfoCache.setCallingConvention(BarrierFn, Barrier);
  2910. // Second barrier ensures workers have read broadcast values.
  2911. if (HasBroadcastValues) {
  2912. CallInst *Barrier = CallInst::Create(BarrierFn, {Ident, Tid}, "",
  2913. RegionBarrierBB->getTerminator());
  2914. Barrier->setDebugLoc(DL);
  2915. OMPInfoCache.setCallingConvention(BarrierFn, Barrier);
  2916. }
  2917. };
  2918. auto &AllocSharedRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
  2919. SmallPtrSet<BasicBlock *, 8> Visited;
  2920. for (Instruction *GuardedI : SPMDCompatibilityTracker) {
  2921. BasicBlock *BB = GuardedI->getParent();
  2922. if (!Visited.insert(BB).second)
  2923. continue;
  2924. SmallVector<std::pair<Instruction *, Instruction *>> Reorders;
  2925. Instruction *LastEffect = nullptr;
  2926. BasicBlock::reverse_iterator IP = BB->rbegin(), IPEnd = BB->rend();
  2927. while (++IP != IPEnd) {
  2928. if (!IP->mayHaveSideEffects() && !IP->mayReadFromMemory())
  2929. continue;
  2930. Instruction *I = &*IP;
  2931. if (OpenMPOpt::getCallIfRegularCall(*I, &AllocSharedRFI))
  2932. continue;
  2933. if (!I->user_empty() || !SPMDCompatibilityTracker.contains(I)) {
  2934. LastEffect = nullptr;
  2935. continue;
  2936. }
  2937. if (LastEffect)
  2938. Reorders.push_back({I, LastEffect});
  2939. LastEffect = &*IP;
  2940. }
  2941. for (auto &Reorder : Reorders)
  2942. Reorder.first->moveBefore(Reorder.second);
  2943. }
  2944. SmallVector<std::pair<Instruction *, Instruction *>, 4> GuardedRegions;
  2945. for (Instruction *GuardedI : SPMDCompatibilityTracker) {
  2946. BasicBlock *BB = GuardedI->getParent();
  2947. auto *CalleeAA = A.lookupAAFor<AAKernelInfo>(
  2948. IRPosition::function(*GuardedI->getFunction()), nullptr,
  2949. DepClassTy::NONE);
  2950. assert(CalleeAA != nullptr && "Expected Callee AAKernelInfo");
  2951. auto &CalleeAAFunction = *cast<AAKernelInfoFunction>(CalleeAA);
  2952. // Continue if instruction is already guarded.
  2953. if (CalleeAAFunction.getGuardedInstructions().contains(GuardedI))
  2954. continue;
  2955. Instruction *GuardedRegionStart = nullptr, *GuardedRegionEnd = nullptr;
  2956. for (Instruction &I : *BB) {
  2957. // If instruction I needs to be guarded update the guarded region
  2958. // bounds.
  2959. if (SPMDCompatibilityTracker.contains(&I)) {
  2960. CalleeAAFunction.getGuardedInstructions().insert(&I);
  2961. if (GuardedRegionStart)
  2962. GuardedRegionEnd = &I;
  2963. else
  2964. GuardedRegionStart = GuardedRegionEnd = &I;
  2965. continue;
  2966. }
  2967. // Instruction I does not need guarding, store
  2968. // any region found and reset bounds.
  2969. if (GuardedRegionStart) {
  2970. GuardedRegions.push_back(
  2971. std::make_pair(GuardedRegionStart, GuardedRegionEnd));
  2972. GuardedRegionStart = nullptr;
  2973. GuardedRegionEnd = nullptr;
  2974. }
  2975. }
  2976. }
  2977. for (auto &GR : GuardedRegions)
  2978. CreateGuardedRegion(GR.first, GR.second);
  2979. // Adjust the global exec mode flag that tells the runtime what mode this
  2980. // kernel is executed in.
  2981. assert(ExecModeVal == OMP_TGT_EXEC_MODE_GENERIC &&
  2982. "Initially non-SPMD kernel has SPMD exec mode!");
  2983. ExecMode->setInitializer(
  2984. ConstantInt::get(ExecMode->getInitializer()->getType(),
  2985. ExecModeVal | OMP_TGT_EXEC_MODE_GENERIC_SPMD));
  2986. // Next rewrite the init and deinit calls to indicate we use SPMD-mode now.
  2987. const int InitModeArgNo = 1;
  2988. const int DeinitModeArgNo = 1;
  2989. const int InitUseStateMachineArgNo = 2;
  2990. const int InitRequiresFullRuntimeArgNo = 3;
  2991. const int DeinitRequiresFullRuntimeArgNo = 2;
  2992. auto &Ctx = getAnchorValue().getContext();
  2993. A.changeUseAfterManifest(
  2994. KernelInitCB->getArgOperandUse(InitModeArgNo),
  2995. *ConstantInt::getSigned(IntegerType::getInt8Ty(Ctx),
  2996. OMP_TGT_EXEC_MODE_SPMD));
  2997. A.changeUseAfterManifest(
  2998. KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo),
  2999. *ConstantInt::getBool(Ctx, false));
  3000. A.changeUseAfterManifest(
  3001. KernelDeinitCB->getArgOperandUse(DeinitModeArgNo),
  3002. *ConstantInt::getSigned(IntegerType::getInt8Ty(Ctx),
  3003. OMP_TGT_EXEC_MODE_SPMD));
  3004. A.changeUseAfterManifest(
  3005. KernelInitCB->getArgOperandUse(InitRequiresFullRuntimeArgNo),
  3006. *ConstantInt::getBool(Ctx, false));
  3007. A.changeUseAfterManifest(
  3008. KernelDeinitCB->getArgOperandUse(DeinitRequiresFullRuntimeArgNo),
  3009. *ConstantInt::getBool(Ctx, false));
  3010. ++NumOpenMPTargetRegionKernelsSPMD;
  3011. auto Remark = [&](OptimizationRemark OR) {
  3012. return OR << "Transformed generic-mode kernel to SPMD-mode.";
  3013. };
  3014. A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP120", Remark);
  3015. return true;
  3016. };
  3017. ChangeStatus buildCustomStateMachine(Attributor &A) {
  3018. // If we have disabled state machine rewrites, don't make a custom one
  3019. if (DisableOpenMPOptStateMachineRewrite)
  3020. return ChangeStatus::UNCHANGED;
  3021. // Don't rewrite the state machine if we are not in a valid state.
  3022. if (!ReachedKnownParallelRegions.isValidState())
  3023. return ChangeStatus::UNCHANGED;
  3024. const int InitModeArgNo = 1;
  3025. const int InitUseStateMachineArgNo = 2;
  3026. // Check if the current configuration is non-SPMD and generic state machine.
  3027. // If we already have SPMD mode or a custom state machine we do not need to
  3028. // go any further. If it is anything but a constant something is weird and
  3029. // we give up.
  3030. ConstantInt *UseStateMachine = dyn_cast<ConstantInt>(
  3031. KernelInitCB->getArgOperand(InitUseStateMachineArgNo));
  3032. ConstantInt *Mode =
  3033. dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitModeArgNo));
  3034. // If we are stuck with generic mode, try to create a custom device (=GPU)
  3035. // state machine which is specialized for the parallel regions that are
  3036. // reachable by the kernel.
  3037. if (!UseStateMachine || UseStateMachine->isZero() || !Mode ||
  3038. (Mode->getSExtValue() & OMP_TGT_EXEC_MODE_SPMD))
  3039. return ChangeStatus::UNCHANGED;
  3040. // If not SPMD mode, indicate we use a custom state machine now.
  3041. auto &Ctx = getAnchorValue().getContext();
  3042. auto *FalseVal = ConstantInt::getBool(Ctx, false);
  3043. A.changeUseAfterManifest(
  3044. KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), *FalseVal);
  3045. // If we don't actually need a state machine we are done here. This can
  3046. // happen if there simply are no parallel regions. In the resulting kernel
  3047. // all worker threads will simply exit right away, leaving the main thread
  3048. // to do the work alone.
  3049. if (!mayContainParallelRegion()) {
  3050. ++NumOpenMPTargetRegionKernelsWithoutStateMachine;
  3051. auto Remark = [&](OptimizationRemark OR) {
  3052. return OR << "Removing unused state machine from generic-mode kernel.";
  3053. };
  3054. A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP130", Remark);
  3055. return ChangeStatus::CHANGED;
  3056. }
  3057. // Keep track in the statistics of our new shiny custom state machine.
  3058. if (ReachedUnknownParallelRegions.empty()) {
  3059. ++NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback;
  3060. auto Remark = [&](OptimizationRemark OR) {
  3061. return OR << "Rewriting generic-mode kernel with a customized state "
  3062. "machine.";
  3063. };
  3064. A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP131", Remark);
  3065. } else {
  3066. ++NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback;
  3067. auto Remark = [&](OptimizationRemarkAnalysis OR) {
  3068. return OR << "Generic-mode kernel is executed with a customized state "
  3069. "machine that requires a fallback.";
  3070. };
  3071. A.emitRemark<OptimizationRemarkAnalysis>(KernelInitCB, "OMP132", Remark);
  3072. // Tell the user why we ended up with a fallback.
  3073. for (CallBase *UnknownParallelRegionCB : ReachedUnknownParallelRegions) {
  3074. if (!UnknownParallelRegionCB)
  3075. continue;
  3076. auto Remark = [&](OptimizationRemarkAnalysis ORA) {
  3077. return ORA << "Call may contain unknown parallel regions. Use "
  3078. << "`__attribute__((assume(\"omp_no_parallelism\")))` to "
  3079. "override.";
  3080. };
  3081. A.emitRemark<OptimizationRemarkAnalysis>(UnknownParallelRegionCB,
  3082. "OMP133", Remark);
  3083. }
  3084. }
  3085. // Create all the blocks:
  3086. //
  3087. // InitCB = __kmpc_target_init(...)
  3088. // BlockHwSize =
  3089. // __kmpc_get_hardware_num_threads_in_block();
  3090. // WarpSize = __kmpc_get_warp_size();
  3091. // BlockSize = BlockHwSize - WarpSize;
  3092. // IsWorkerCheckBB: bool IsWorker = InitCB != -1;
  3093. // if (IsWorker) {
  3094. // if (InitCB >= BlockSize) return;
  3095. // SMBeginBB: __kmpc_barrier_simple_generic(...);
  3096. // void *WorkFn;
  3097. // bool Active = __kmpc_kernel_parallel(&WorkFn);
  3098. // if (!WorkFn) return;
  3099. // SMIsActiveCheckBB: if (Active) {
  3100. // SMIfCascadeCurrentBB: if (WorkFn == <ParFn0>)
  3101. // ParFn0(...);
  3102. // SMIfCascadeCurrentBB: else if (WorkFn == <ParFn1>)
  3103. // ParFn1(...);
  3104. // ...
  3105. // SMIfCascadeCurrentBB: else
  3106. // ((WorkFnTy*)WorkFn)(...);
  3107. // SMEndParallelBB: __kmpc_kernel_end_parallel(...);
  3108. // }
  3109. // SMDoneBB: __kmpc_barrier_simple_generic(...);
  3110. // goto SMBeginBB;
  3111. // }
  3112. // UserCodeEntryBB: // user code
  3113. // __kmpc_target_deinit(...)
  3114. //
  3115. Function *Kernel = getAssociatedFunction();
  3116. assert(Kernel && "Expected an associated function!");
  3117. BasicBlock *InitBB = KernelInitCB->getParent();
  3118. BasicBlock *UserCodeEntryBB = InitBB->splitBasicBlock(
  3119. KernelInitCB->getNextNode(), "thread.user_code.check");
  3120. BasicBlock *IsWorkerCheckBB =
  3121. BasicBlock::Create(Ctx, "is_worker_check", Kernel, UserCodeEntryBB);
  3122. BasicBlock *StateMachineBeginBB = BasicBlock::Create(
  3123. Ctx, "worker_state_machine.begin", Kernel, UserCodeEntryBB);
  3124. BasicBlock *StateMachineFinishedBB = BasicBlock::Create(
  3125. Ctx, "worker_state_machine.finished", Kernel, UserCodeEntryBB);
  3126. BasicBlock *StateMachineIsActiveCheckBB = BasicBlock::Create(
  3127. Ctx, "worker_state_machine.is_active.check", Kernel, UserCodeEntryBB);
  3128. BasicBlock *StateMachineIfCascadeCurrentBB =
  3129. BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
  3130. Kernel, UserCodeEntryBB);
  3131. BasicBlock *StateMachineEndParallelBB =
  3132. BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.end",
  3133. Kernel, UserCodeEntryBB);
  3134. BasicBlock *StateMachineDoneBarrierBB = BasicBlock::Create(
  3135. Ctx, "worker_state_machine.done.barrier", Kernel, UserCodeEntryBB);
  3136. A.registerManifestAddedBasicBlock(*InitBB);
  3137. A.registerManifestAddedBasicBlock(*UserCodeEntryBB);
  3138. A.registerManifestAddedBasicBlock(*IsWorkerCheckBB);
  3139. A.registerManifestAddedBasicBlock(*StateMachineBeginBB);
  3140. A.registerManifestAddedBasicBlock(*StateMachineFinishedBB);
  3141. A.registerManifestAddedBasicBlock(*StateMachineIsActiveCheckBB);
  3142. A.registerManifestAddedBasicBlock(*StateMachineIfCascadeCurrentBB);
  3143. A.registerManifestAddedBasicBlock(*StateMachineEndParallelBB);
  3144. A.registerManifestAddedBasicBlock(*StateMachineDoneBarrierBB);
  3145. const DebugLoc &DLoc = KernelInitCB->getDebugLoc();
  3146. ReturnInst::Create(Ctx, StateMachineFinishedBB)->setDebugLoc(DLoc);
  3147. InitBB->getTerminator()->eraseFromParent();
  3148. Instruction *IsWorker =
  3149. ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_NE, KernelInitCB,
  3150. ConstantInt::get(KernelInitCB->getType(), -1),
  3151. "thread.is_worker", InitBB);
  3152. IsWorker->setDebugLoc(DLoc);
  3153. BranchInst::Create(IsWorkerCheckBB, UserCodeEntryBB, IsWorker, InitBB);
  3154. Module &M = *Kernel->getParent();
  3155. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  3156. FunctionCallee BlockHwSizeFn =
  3157. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  3158. M, OMPRTL___kmpc_get_hardware_num_threads_in_block);
  3159. FunctionCallee WarpSizeFn =
  3160. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  3161. M, OMPRTL___kmpc_get_warp_size);
  3162. CallInst *BlockHwSize =
  3163. CallInst::Create(BlockHwSizeFn, "block.hw_size", IsWorkerCheckBB);
  3164. OMPInfoCache.setCallingConvention(BlockHwSizeFn, BlockHwSize);
  3165. BlockHwSize->setDebugLoc(DLoc);
  3166. CallInst *WarpSize =
  3167. CallInst::Create(WarpSizeFn, "warp.size", IsWorkerCheckBB);
  3168. OMPInfoCache.setCallingConvention(WarpSizeFn, WarpSize);
  3169. WarpSize->setDebugLoc(DLoc);
  3170. Instruction *BlockSize = BinaryOperator::CreateSub(
  3171. BlockHwSize, WarpSize, "block.size", IsWorkerCheckBB);
  3172. BlockSize->setDebugLoc(DLoc);
  3173. Instruction *IsMainOrWorker = ICmpInst::Create(
  3174. ICmpInst::ICmp, llvm::CmpInst::ICMP_SLT, KernelInitCB, BlockSize,
  3175. "thread.is_main_or_worker", IsWorkerCheckBB);
  3176. IsMainOrWorker->setDebugLoc(DLoc);
  3177. BranchInst::Create(StateMachineBeginBB, StateMachineFinishedBB,
  3178. IsMainOrWorker, IsWorkerCheckBB);
  3179. // Create local storage for the work function pointer.
  3180. const DataLayout &DL = M.getDataLayout();
  3181. Type *VoidPtrTy = Type::getInt8PtrTy(Ctx);
  3182. Instruction *WorkFnAI =
  3183. new AllocaInst(VoidPtrTy, DL.getAllocaAddrSpace(), nullptr,
  3184. "worker.work_fn.addr", &Kernel->getEntryBlock().front());
  3185. WorkFnAI->setDebugLoc(DLoc);
  3186. OMPInfoCache.OMPBuilder.updateToLocation(
  3187. OpenMPIRBuilder::LocationDescription(
  3188. IRBuilder<>::InsertPoint(StateMachineBeginBB,
  3189. StateMachineBeginBB->end()),
  3190. DLoc));
  3191. Value *Ident = KernelInitCB->getArgOperand(0);
  3192. Value *GTid = KernelInitCB;
  3193. FunctionCallee BarrierFn =
  3194. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  3195. M, OMPRTL___kmpc_barrier_simple_generic);
  3196. CallInst *Barrier =
  3197. CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineBeginBB);
  3198. OMPInfoCache.setCallingConvention(BarrierFn, Barrier);
  3199. Barrier->setDebugLoc(DLoc);
  3200. if (WorkFnAI->getType()->getPointerAddressSpace() !=
  3201. (unsigned int)AddressSpace::Generic) {
  3202. WorkFnAI = new AddrSpaceCastInst(
  3203. WorkFnAI,
  3204. PointerType::getWithSamePointeeType(
  3205. cast<PointerType>(WorkFnAI->getType()),
  3206. (unsigned int)AddressSpace::Generic),
  3207. WorkFnAI->getName() + ".generic", StateMachineBeginBB);
  3208. WorkFnAI->setDebugLoc(DLoc);
  3209. }
  3210. FunctionCallee KernelParallelFn =
  3211. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  3212. M, OMPRTL___kmpc_kernel_parallel);
  3213. CallInst *IsActiveWorker = CallInst::Create(
  3214. KernelParallelFn, {WorkFnAI}, "worker.is_active", StateMachineBeginBB);
  3215. OMPInfoCache.setCallingConvention(KernelParallelFn, IsActiveWorker);
  3216. IsActiveWorker->setDebugLoc(DLoc);
  3217. Instruction *WorkFn = new LoadInst(VoidPtrTy, WorkFnAI, "worker.work_fn",
  3218. StateMachineBeginBB);
  3219. WorkFn->setDebugLoc(DLoc);
  3220. FunctionType *ParallelRegionFnTy = FunctionType::get(
  3221. Type::getVoidTy(Ctx), {Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)},
  3222. false);
  3223. Value *WorkFnCast = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
  3224. WorkFn, ParallelRegionFnTy->getPointerTo(), "worker.work_fn.addr_cast",
  3225. StateMachineBeginBB);
  3226. Instruction *IsDone =
  3227. ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFn,
  3228. Constant::getNullValue(VoidPtrTy), "worker.is_done",
  3229. StateMachineBeginBB);
  3230. IsDone->setDebugLoc(DLoc);
  3231. BranchInst::Create(StateMachineFinishedBB, StateMachineIsActiveCheckBB,
  3232. IsDone, StateMachineBeginBB)
  3233. ->setDebugLoc(DLoc);
  3234. BranchInst::Create(StateMachineIfCascadeCurrentBB,
  3235. StateMachineDoneBarrierBB, IsActiveWorker,
  3236. StateMachineIsActiveCheckBB)
  3237. ->setDebugLoc(DLoc);
  3238. Value *ZeroArg =
  3239. Constant::getNullValue(ParallelRegionFnTy->getParamType(0));
  3240. // Now that we have most of the CFG skeleton it is time for the if-cascade
  3241. // that checks the function pointer we got from the runtime against the
  3242. // parallel regions we expect, if there are any.
  3243. for (int I = 0, E = ReachedKnownParallelRegions.size(); I < E; ++I) {
  3244. auto *ParallelRegion = ReachedKnownParallelRegions[I];
  3245. BasicBlock *PRExecuteBB = BasicBlock::Create(
  3246. Ctx, "worker_state_machine.parallel_region.execute", Kernel,
  3247. StateMachineEndParallelBB);
  3248. CallInst::Create(ParallelRegion, {ZeroArg, GTid}, "", PRExecuteBB)
  3249. ->setDebugLoc(DLoc);
  3250. BranchInst::Create(StateMachineEndParallelBB, PRExecuteBB)
  3251. ->setDebugLoc(DLoc);
  3252. BasicBlock *PRNextBB =
  3253. BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
  3254. Kernel, StateMachineEndParallelBB);
  3255. // Check if we need to compare the pointer at all or if we can just
  3256. // call the parallel region function.
  3257. Value *IsPR;
  3258. if (I + 1 < E || !ReachedUnknownParallelRegions.empty()) {
  3259. Instruction *CmpI = ICmpInst::Create(
  3260. ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFnCast, ParallelRegion,
  3261. "worker.check_parallel_region", StateMachineIfCascadeCurrentBB);
  3262. CmpI->setDebugLoc(DLoc);
  3263. IsPR = CmpI;
  3264. } else {
  3265. IsPR = ConstantInt::getTrue(Ctx);
  3266. }
  3267. BranchInst::Create(PRExecuteBB, PRNextBB, IsPR,
  3268. StateMachineIfCascadeCurrentBB)
  3269. ->setDebugLoc(DLoc);
  3270. StateMachineIfCascadeCurrentBB = PRNextBB;
  3271. }
  3272. // At the end of the if-cascade we place the indirect function pointer call
  3273. // in case we might need it, that is if there can be parallel regions we
  3274. // have not handled in the if-cascade above.
  3275. if (!ReachedUnknownParallelRegions.empty()) {
  3276. StateMachineIfCascadeCurrentBB->setName(
  3277. "worker_state_machine.parallel_region.fallback.execute");
  3278. CallInst::Create(ParallelRegionFnTy, WorkFnCast, {ZeroArg, GTid}, "",
  3279. StateMachineIfCascadeCurrentBB)
  3280. ->setDebugLoc(DLoc);
  3281. }
  3282. BranchInst::Create(StateMachineEndParallelBB,
  3283. StateMachineIfCascadeCurrentBB)
  3284. ->setDebugLoc(DLoc);
  3285. FunctionCallee EndParallelFn =
  3286. OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
  3287. M, OMPRTL___kmpc_kernel_end_parallel);
  3288. CallInst *EndParallel =
  3289. CallInst::Create(EndParallelFn, {}, "", StateMachineEndParallelBB);
  3290. OMPInfoCache.setCallingConvention(EndParallelFn, EndParallel);
  3291. EndParallel->setDebugLoc(DLoc);
  3292. BranchInst::Create(StateMachineDoneBarrierBB, StateMachineEndParallelBB)
  3293. ->setDebugLoc(DLoc);
  3294. CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineDoneBarrierBB)
  3295. ->setDebugLoc(DLoc);
  3296. BranchInst::Create(StateMachineBeginBB, StateMachineDoneBarrierBB)
  3297. ->setDebugLoc(DLoc);
  3298. return ChangeStatus::CHANGED;
  3299. }
  3300. /// Fixpoint iteration update function. Will be called every time a dependence
  3301. /// changed its state (and in the beginning).
  3302. ChangeStatus updateImpl(Attributor &A) override {
  3303. KernelInfoState StateBefore = getState();
  3304. // Callback to check a read/write instruction.
  3305. auto CheckRWInst = [&](Instruction &I) {
  3306. // We handle calls later.
  3307. if (isa<CallBase>(I))
  3308. return true;
  3309. // We only care about write effects.
  3310. if (!I.mayWriteToMemory())
  3311. return true;
  3312. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  3313. SmallVector<const Value *> Objects;
  3314. getUnderlyingObjects(SI->getPointerOperand(), Objects);
  3315. if (llvm::all_of(Objects,
  3316. [](const Value *Obj) { return isa<AllocaInst>(Obj); }))
  3317. return true;
  3318. // Check for AAHeapToStack moved objects which must not be guarded.
  3319. auto &HS = A.getAAFor<AAHeapToStack>(
  3320. *this, IRPosition::function(*I.getFunction()),
  3321. DepClassTy::OPTIONAL);
  3322. if (llvm::all_of(Objects, [&HS](const Value *Obj) {
  3323. auto *CB = dyn_cast<CallBase>(Obj);
  3324. if (!CB)
  3325. return false;
  3326. return HS.isAssumedHeapToStack(*CB);
  3327. })) {
  3328. return true;
  3329. }
  3330. }
  3331. // Insert instruction that needs guarding.
  3332. SPMDCompatibilityTracker.insert(&I);
  3333. return true;
  3334. };
  3335. bool UsedAssumedInformationInCheckRWInst = false;
  3336. if (!SPMDCompatibilityTracker.isAtFixpoint())
  3337. if (!A.checkForAllReadWriteInstructions(
  3338. CheckRWInst, *this, UsedAssumedInformationInCheckRWInst))
  3339. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3340. bool UsedAssumedInformationFromReachingKernels = false;
  3341. if (!IsKernelEntry) {
  3342. updateParallelLevels(A);
  3343. bool AllReachingKernelsKnown = true;
  3344. updateReachingKernelEntries(A, AllReachingKernelsKnown);
  3345. UsedAssumedInformationFromReachingKernels = !AllReachingKernelsKnown;
  3346. if (!ParallelLevels.isValidState())
  3347. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3348. else if (!ReachingKernelEntries.isValidState())
  3349. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3350. else if (!SPMDCompatibilityTracker.empty()) {
  3351. // Check if all reaching kernels agree on the mode as we can otherwise
  3352. // not guard instructions. We might not be sure about the mode so we
  3353. // we cannot fix the internal spmd-zation state either.
  3354. int SPMD = 0, Generic = 0;
  3355. for (auto *Kernel : ReachingKernelEntries) {
  3356. auto &CBAA = A.getAAFor<AAKernelInfo>(
  3357. *this, IRPosition::function(*Kernel), DepClassTy::OPTIONAL);
  3358. if (CBAA.SPMDCompatibilityTracker.isValidState() &&
  3359. CBAA.SPMDCompatibilityTracker.isAssumed())
  3360. ++SPMD;
  3361. else
  3362. ++Generic;
  3363. if (!CBAA.SPMDCompatibilityTracker.isAtFixpoint())
  3364. UsedAssumedInformationFromReachingKernels = true;
  3365. }
  3366. if (SPMD != 0 && Generic != 0)
  3367. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3368. }
  3369. }
  3370. // Callback to check a call instruction.
  3371. bool AllParallelRegionStatesWereFixed = true;
  3372. bool AllSPMDStatesWereFixed = true;
  3373. auto CheckCallInst = [&](Instruction &I) {
  3374. auto &CB = cast<CallBase>(I);
  3375. auto &CBAA = A.getAAFor<AAKernelInfo>(
  3376. *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL);
  3377. getState() ^= CBAA.getState();
  3378. AllSPMDStatesWereFixed &= CBAA.SPMDCompatibilityTracker.isAtFixpoint();
  3379. AllParallelRegionStatesWereFixed &=
  3380. CBAA.ReachedKnownParallelRegions.isAtFixpoint();
  3381. AllParallelRegionStatesWereFixed &=
  3382. CBAA.ReachedUnknownParallelRegions.isAtFixpoint();
  3383. return true;
  3384. };
  3385. bool UsedAssumedInformationInCheckCallInst = false;
  3386. if (!A.checkForAllCallLikeInstructions(
  3387. CheckCallInst, *this, UsedAssumedInformationInCheckCallInst)) {
  3388. LLVM_DEBUG(dbgs() << TAG
  3389. << "Failed to visit all call-like instructions!\n";);
  3390. return indicatePessimisticFixpoint();
  3391. }
  3392. // If we haven't used any assumed information for the reached parallel
  3393. // region states we can fix it.
  3394. if (!UsedAssumedInformationInCheckCallInst &&
  3395. AllParallelRegionStatesWereFixed) {
  3396. ReachedKnownParallelRegions.indicateOptimisticFixpoint();
  3397. ReachedUnknownParallelRegions.indicateOptimisticFixpoint();
  3398. }
  3399. // If we are sure there are no parallel regions in the kernel we do not
  3400. // want SPMD mode.
  3401. if (IsKernelEntry && ReachedUnknownParallelRegions.isAtFixpoint() &&
  3402. ReachedKnownParallelRegions.isAtFixpoint() &&
  3403. ReachedUnknownParallelRegions.isValidState() &&
  3404. ReachedKnownParallelRegions.isValidState() &&
  3405. !mayContainParallelRegion())
  3406. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3407. // If we haven't used any assumed information for the SPMD state we can fix
  3408. // it.
  3409. if (!UsedAssumedInformationInCheckRWInst &&
  3410. !UsedAssumedInformationInCheckCallInst &&
  3411. !UsedAssumedInformationFromReachingKernels && AllSPMDStatesWereFixed)
  3412. SPMDCompatibilityTracker.indicateOptimisticFixpoint();
  3413. return StateBefore == getState() ? ChangeStatus::UNCHANGED
  3414. : ChangeStatus::CHANGED;
  3415. }
  3416. private:
  3417. /// Update info regarding reaching kernels.
  3418. void updateReachingKernelEntries(Attributor &A,
  3419. bool &AllReachingKernelsKnown) {
  3420. auto PredCallSite = [&](AbstractCallSite ACS) {
  3421. Function *Caller = ACS.getInstruction()->getFunction();
  3422. assert(Caller && "Caller is nullptr");
  3423. auto &CAA = A.getOrCreateAAFor<AAKernelInfo>(
  3424. IRPosition::function(*Caller), this, DepClassTy::REQUIRED);
  3425. if (CAA.ReachingKernelEntries.isValidState()) {
  3426. ReachingKernelEntries ^= CAA.ReachingKernelEntries;
  3427. return true;
  3428. }
  3429. // We lost track of the caller of the associated function, any kernel
  3430. // could reach now.
  3431. ReachingKernelEntries.indicatePessimisticFixpoint();
  3432. return true;
  3433. };
  3434. if (!A.checkForAllCallSites(PredCallSite, *this,
  3435. true /* RequireAllCallSites */,
  3436. AllReachingKernelsKnown))
  3437. ReachingKernelEntries.indicatePessimisticFixpoint();
  3438. }
  3439. /// Update info regarding parallel levels.
  3440. void updateParallelLevels(Attributor &A) {
  3441. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  3442. OMPInformationCache::RuntimeFunctionInfo &Parallel51RFI =
  3443. OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
  3444. auto PredCallSite = [&](AbstractCallSite ACS) {
  3445. Function *Caller = ACS.getInstruction()->getFunction();
  3446. assert(Caller && "Caller is nullptr");
  3447. auto &CAA =
  3448. A.getOrCreateAAFor<AAKernelInfo>(IRPosition::function(*Caller));
  3449. if (CAA.ParallelLevels.isValidState()) {
  3450. // Any function that is called by `__kmpc_parallel_51` will not be
  3451. // folded as the parallel level in the function is updated. In order to
  3452. // get it right, all the analysis would depend on the implentation. That
  3453. // said, if in the future any change to the implementation, the analysis
  3454. // could be wrong. As a consequence, we are just conservative here.
  3455. if (Caller == Parallel51RFI.Declaration) {
  3456. ParallelLevels.indicatePessimisticFixpoint();
  3457. return true;
  3458. }
  3459. ParallelLevels ^= CAA.ParallelLevels;
  3460. return true;
  3461. }
  3462. // We lost track of the caller of the associated function, any kernel
  3463. // could reach now.
  3464. ParallelLevels.indicatePessimisticFixpoint();
  3465. return true;
  3466. };
  3467. bool AllCallSitesKnown = true;
  3468. if (!A.checkForAllCallSites(PredCallSite, *this,
  3469. true /* RequireAllCallSites */,
  3470. AllCallSitesKnown))
  3471. ParallelLevels.indicatePessimisticFixpoint();
  3472. }
  3473. };
  3474. /// The call site kernel info abstract attribute, basically, what can we say
  3475. /// about a call site with regards to the KernelInfoState. For now this simply
  3476. /// forwards the information from the callee.
  3477. struct AAKernelInfoCallSite : AAKernelInfo {
  3478. AAKernelInfoCallSite(const IRPosition &IRP, Attributor &A)
  3479. : AAKernelInfo(IRP, A) {}
  3480. /// See AbstractAttribute::initialize(...).
  3481. void initialize(Attributor &A) override {
  3482. AAKernelInfo::initialize(A);
  3483. CallBase &CB = cast<CallBase>(getAssociatedValue());
  3484. Function *Callee = getAssociatedFunction();
  3485. auto &AssumptionAA = A.getAAFor<AAAssumptionInfo>(
  3486. *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL);
  3487. // Check for SPMD-mode assumptions.
  3488. if (AssumptionAA.hasAssumption("ompx_spmd_amenable")) {
  3489. SPMDCompatibilityTracker.indicateOptimisticFixpoint();
  3490. indicateOptimisticFixpoint();
  3491. }
  3492. // First weed out calls we do not care about, that is readonly/readnone
  3493. // calls, intrinsics, and "no_openmp" calls. Neither of these can reach a
  3494. // parallel region or anything else we are looking for.
  3495. if (!CB.mayWriteToMemory() || isa<IntrinsicInst>(CB)) {
  3496. indicateOptimisticFixpoint();
  3497. return;
  3498. }
  3499. // Next we check if we know the callee. If it is a known OpenMP function
  3500. // we will handle them explicitly in the switch below. If it is not, we
  3501. // will use an AAKernelInfo object on the callee to gather information and
  3502. // merge that into the current state. The latter happens in the updateImpl.
  3503. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  3504. const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
  3505. if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
  3506. // Unknown caller or declarations are not analyzable, we give up.
  3507. if (!Callee || !A.isFunctionIPOAmendable(*Callee)) {
  3508. // Unknown callees might contain parallel regions, except if they have
  3509. // an appropriate assumption attached.
  3510. if (!(AssumptionAA.hasAssumption("omp_no_openmp") ||
  3511. AssumptionAA.hasAssumption("omp_no_parallelism")))
  3512. ReachedUnknownParallelRegions.insert(&CB);
  3513. // If SPMDCompatibilityTracker is not fixed, we need to give up on the
  3514. // idea we can run something unknown in SPMD-mode.
  3515. if (!SPMDCompatibilityTracker.isAtFixpoint()) {
  3516. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3517. SPMDCompatibilityTracker.insert(&CB);
  3518. }
  3519. // We have updated the state for this unknown call properly, there won't
  3520. // be any change so we indicate a fixpoint.
  3521. indicateOptimisticFixpoint();
  3522. }
  3523. // If the callee is known and can be used in IPO, we will update the state
  3524. // based on the callee state in updateImpl.
  3525. return;
  3526. }
  3527. const unsigned int WrapperFunctionArgNo = 6;
  3528. RuntimeFunction RF = It->getSecond();
  3529. switch (RF) {
  3530. // All the functions we know are compatible with SPMD mode.
  3531. case OMPRTL___kmpc_is_spmd_exec_mode:
  3532. case OMPRTL___kmpc_distribute_static_fini:
  3533. case OMPRTL___kmpc_for_static_fini:
  3534. case OMPRTL___kmpc_global_thread_num:
  3535. case OMPRTL___kmpc_get_hardware_num_threads_in_block:
  3536. case OMPRTL___kmpc_get_hardware_num_blocks:
  3537. case OMPRTL___kmpc_single:
  3538. case OMPRTL___kmpc_end_single:
  3539. case OMPRTL___kmpc_master:
  3540. case OMPRTL___kmpc_end_master:
  3541. case OMPRTL___kmpc_barrier:
  3542. case OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2:
  3543. case OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2:
  3544. case OMPRTL___kmpc_nvptx_end_reduce_nowait:
  3545. break;
  3546. case OMPRTL___kmpc_distribute_static_init_4:
  3547. case OMPRTL___kmpc_distribute_static_init_4u:
  3548. case OMPRTL___kmpc_distribute_static_init_8:
  3549. case OMPRTL___kmpc_distribute_static_init_8u:
  3550. case OMPRTL___kmpc_for_static_init_4:
  3551. case OMPRTL___kmpc_for_static_init_4u:
  3552. case OMPRTL___kmpc_for_static_init_8:
  3553. case OMPRTL___kmpc_for_static_init_8u: {
  3554. // Check the schedule and allow static schedule in SPMD mode.
  3555. unsigned ScheduleArgOpNo = 2;
  3556. auto *ScheduleTypeCI =
  3557. dyn_cast<ConstantInt>(CB.getArgOperand(ScheduleArgOpNo));
  3558. unsigned ScheduleTypeVal =
  3559. ScheduleTypeCI ? ScheduleTypeCI->getZExtValue() : 0;
  3560. switch (OMPScheduleType(ScheduleTypeVal)) {
  3561. case OMPScheduleType::Static:
  3562. case OMPScheduleType::StaticChunked:
  3563. case OMPScheduleType::Distribute:
  3564. case OMPScheduleType::DistributeChunked:
  3565. break;
  3566. default:
  3567. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3568. SPMDCompatibilityTracker.insert(&CB);
  3569. break;
  3570. };
  3571. } break;
  3572. case OMPRTL___kmpc_target_init:
  3573. KernelInitCB = &CB;
  3574. break;
  3575. case OMPRTL___kmpc_target_deinit:
  3576. KernelDeinitCB = &CB;
  3577. break;
  3578. case OMPRTL___kmpc_parallel_51:
  3579. if (auto *ParallelRegion = dyn_cast<Function>(
  3580. CB.getArgOperand(WrapperFunctionArgNo)->stripPointerCasts())) {
  3581. ReachedKnownParallelRegions.insert(ParallelRegion);
  3582. break;
  3583. }
  3584. // The condition above should usually get the parallel region function
  3585. // pointer and record it. In the off chance it doesn't we assume the
  3586. // worst.
  3587. ReachedUnknownParallelRegions.insert(&CB);
  3588. break;
  3589. case OMPRTL___kmpc_omp_task:
  3590. // We do not look into tasks right now, just give up.
  3591. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3592. SPMDCompatibilityTracker.insert(&CB);
  3593. ReachedUnknownParallelRegions.insert(&CB);
  3594. break;
  3595. case OMPRTL___kmpc_alloc_shared:
  3596. case OMPRTL___kmpc_free_shared:
  3597. // Return without setting a fixpoint, to be resolved in updateImpl.
  3598. return;
  3599. default:
  3600. // Unknown OpenMP runtime calls cannot be executed in SPMD-mode,
  3601. // generally. However, they do not hide parallel regions.
  3602. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3603. SPMDCompatibilityTracker.insert(&CB);
  3604. break;
  3605. }
  3606. // All other OpenMP runtime calls will not reach parallel regions so they
  3607. // can be safely ignored for now. Since it is a known OpenMP runtime call we
  3608. // have now modeled all effects and there is no need for any update.
  3609. indicateOptimisticFixpoint();
  3610. }
  3611. ChangeStatus updateImpl(Attributor &A) override {
  3612. // TODO: Once we have call site specific value information we can provide
  3613. // call site specific liveness information and then it makes
  3614. // sense to specialize attributes for call sites arguments instead of
  3615. // redirecting requests to the callee argument.
  3616. Function *F = getAssociatedFunction();
  3617. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  3618. const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(F);
  3619. // If F is not a runtime function, propagate the AAKernelInfo of the callee.
  3620. if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
  3621. const IRPosition &FnPos = IRPosition::function(*F);
  3622. auto &FnAA = A.getAAFor<AAKernelInfo>(*this, FnPos, DepClassTy::REQUIRED);
  3623. if (getState() == FnAA.getState())
  3624. return ChangeStatus::UNCHANGED;
  3625. getState() = FnAA.getState();
  3626. return ChangeStatus::CHANGED;
  3627. }
  3628. // F is a runtime function that allocates or frees memory, check
  3629. // AAHeapToStack and AAHeapToShared.
  3630. KernelInfoState StateBefore = getState();
  3631. assert((It->getSecond() == OMPRTL___kmpc_alloc_shared ||
  3632. It->getSecond() == OMPRTL___kmpc_free_shared) &&
  3633. "Expected a __kmpc_alloc_shared or __kmpc_free_shared runtime call");
  3634. CallBase &CB = cast<CallBase>(getAssociatedValue());
  3635. auto &HeapToStackAA = A.getAAFor<AAHeapToStack>(
  3636. *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
  3637. auto &HeapToSharedAA = A.getAAFor<AAHeapToShared>(
  3638. *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
  3639. RuntimeFunction RF = It->getSecond();
  3640. switch (RF) {
  3641. // If neither HeapToStack nor HeapToShared assume the call is removed,
  3642. // assume SPMD incompatibility.
  3643. case OMPRTL___kmpc_alloc_shared:
  3644. if (!HeapToStackAA.isAssumedHeapToStack(CB) &&
  3645. !HeapToSharedAA.isAssumedHeapToShared(CB))
  3646. SPMDCompatibilityTracker.insert(&CB);
  3647. break;
  3648. case OMPRTL___kmpc_free_shared:
  3649. if (!HeapToStackAA.isAssumedHeapToStackRemovedFree(CB) &&
  3650. !HeapToSharedAA.isAssumedHeapToSharedRemovedFree(CB))
  3651. SPMDCompatibilityTracker.insert(&CB);
  3652. break;
  3653. default:
  3654. SPMDCompatibilityTracker.indicatePessimisticFixpoint();
  3655. SPMDCompatibilityTracker.insert(&CB);
  3656. }
  3657. return StateBefore == getState() ? ChangeStatus::UNCHANGED
  3658. : ChangeStatus::CHANGED;
  3659. }
  3660. };
  3661. struct AAFoldRuntimeCall
  3662. : public StateWrapper<BooleanState, AbstractAttribute> {
  3663. using Base = StateWrapper<BooleanState, AbstractAttribute>;
  3664. AAFoldRuntimeCall(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
  3665. /// Statistics are tracked as part of manifest for now.
  3666. void trackStatistics() const override {}
  3667. /// Create an abstract attribute biew for the position \p IRP.
  3668. static AAFoldRuntimeCall &createForPosition(const IRPosition &IRP,
  3669. Attributor &A);
  3670. /// See AbstractAttribute::getName()
  3671. const std::string getName() const override { return "AAFoldRuntimeCall"; }
  3672. /// See AbstractAttribute::getIdAddr()
  3673. const char *getIdAddr() const override { return &ID; }
  3674. /// This function should return true if the type of the \p AA is
  3675. /// AAFoldRuntimeCall
  3676. static bool classof(const AbstractAttribute *AA) {
  3677. return (AA->getIdAddr() == &ID);
  3678. }
  3679. static const char ID;
  3680. };
  3681. struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall {
  3682. AAFoldRuntimeCallCallSiteReturned(const IRPosition &IRP, Attributor &A)
  3683. : AAFoldRuntimeCall(IRP, A) {}
  3684. /// See AbstractAttribute::getAsStr()
  3685. const std::string getAsStr() const override {
  3686. if (!isValidState())
  3687. return "<invalid>";
  3688. std::string Str("simplified value: ");
  3689. if (!SimplifiedValue.hasValue())
  3690. return Str + std::string("none");
  3691. if (!SimplifiedValue.getValue())
  3692. return Str + std::string("nullptr");
  3693. if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue()))
  3694. return Str + std::to_string(CI->getSExtValue());
  3695. return Str + std::string("unknown");
  3696. }
  3697. void initialize(Attributor &A) override {
  3698. if (DisableOpenMPOptFolding)
  3699. indicatePessimisticFixpoint();
  3700. Function *Callee = getAssociatedFunction();
  3701. auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
  3702. const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
  3703. assert(It != OMPInfoCache.RuntimeFunctionIDMap.end() &&
  3704. "Expected a known OpenMP runtime function");
  3705. RFKind = It->getSecond();
  3706. CallBase &CB = cast<CallBase>(getAssociatedValue());
  3707. A.registerSimplificationCallback(
  3708. IRPosition::callsite_returned(CB),
  3709. [&](const IRPosition &IRP, const AbstractAttribute *AA,
  3710. bool &UsedAssumedInformation) -> Optional<Value *> {
  3711. assert((isValidState() || (SimplifiedValue.hasValue() &&
  3712. SimplifiedValue.getValue() == nullptr)) &&
  3713. "Unexpected invalid state!");
  3714. if (!isAtFixpoint()) {
  3715. UsedAssumedInformation = true;
  3716. if (AA)
  3717. A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
  3718. }
  3719. return SimplifiedValue;
  3720. });
  3721. }
  3722. ChangeStatus updateImpl(Attributor &A) override {
  3723. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  3724. switch (RFKind) {
  3725. case OMPRTL___kmpc_is_spmd_exec_mode:
  3726. Changed |= foldIsSPMDExecMode(A);
  3727. break;
  3728. case OMPRTL___kmpc_is_generic_main_thread_id:
  3729. Changed |= foldIsGenericMainThread(A);
  3730. break;
  3731. case OMPRTL___kmpc_parallel_level:
  3732. Changed |= foldParallelLevel(A);
  3733. break;
  3734. case OMPRTL___kmpc_get_hardware_num_threads_in_block:
  3735. Changed = Changed | foldKernelFnAttribute(A, "omp_target_thread_limit");
  3736. break;
  3737. case OMPRTL___kmpc_get_hardware_num_blocks:
  3738. Changed = Changed | foldKernelFnAttribute(A, "omp_target_num_teams");
  3739. break;
  3740. default:
  3741. llvm_unreachable("Unhandled OpenMP runtime function!");
  3742. }
  3743. return Changed;
  3744. }
  3745. ChangeStatus manifest(Attributor &A) override {
  3746. ChangeStatus Changed = ChangeStatus::UNCHANGED;
  3747. if (SimplifiedValue.hasValue() && SimplifiedValue.getValue()) {
  3748. Instruction &I = *getCtxI();
  3749. A.changeValueAfterManifest(I, **SimplifiedValue);
  3750. A.deleteAfterManifest(I);
  3751. CallBase *CB = dyn_cast<CallBase>(&I);
  3752. auto Remark = [&](OptimizationRemark OR) {
  3753. if (auto *C = dyn_cast<ConstantInt>(*SimplifiedValue))
  3754. return OR << "Replacing OpenMP runtime call "
  3755. << CB->getCalledFunction()->getName() << " with "
  3756. << ore::NV("FoldedValue", C->getZExtValue()) << ".";
  3757. return OR << "Replacing OpenMP runtime call "
  3758. << CB->getCalledFunction()->getName() << ".";
  3759. };
  3760. if (CB && EnableVerboseRemarks)
  3761. A.emitRemark<OptimizationRemark>(CB, "OMP180", Remark);
  3762. LLVM_DEBUG(dbgs() << TAG << "Replacing runtime call: " << I << " with "
  3763. << **SimplifiedValue << "\n");
  3764. Changed = ChangeStatus::CHANGED;
  3765. }
  3766. return Changed;
  3767. }
  3768. ChangeStatus indicatePessimisticFixpoint() override {
  3769. SimplifiedValue = nullptr;
  3770. return AAFoldRuntimeCall::indicatePessimisticFixpoint();
  3771. }
  3772. private:
  3773. /// Fold __kmpc_is_spmd_exec_mode into a constant if possible.
  3774. ChangeStatus foldIsSPMDExecMode(Attributor &A) {
  3775. Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
  3776. unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0;
  3777. unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0;
  3778. auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
  3779. *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
  3780. if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
  3781. return indicatePessimisticFixpoint();
  3782. for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
  3783. auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K),
  3784. DepClassTy::REQUIRED);
  3785. if (!AA.isValidState()) {
  3786. SimplifiedValue = nullptr;
  3787. return indicatePessimisticFixpoint();
  3788. }
  3789. if (AA.SPMDCompatibilityTracker.isAssumed()) {
  3790. if (AA.SPMDCompatibilityTracker.isAtFixpoint())
  3791. ++KnownSPMDCount;
  3792. else
  3793. ++AssumedSPMDCount;
  3794. } else {
  3795. if (AA.SPMDCompatibilityTracker.isAtFixpoint())
  3796. ++KnownNonSPMDCount;
  3797. else
  3798. ++AssumedNonSPMDCount;
  3799. }
  3800. }
  3801. if ((AssumedSPMDCount + KnownSPMDCount) &&
  3802. (AssumedNonSPMDCount + KnownNonSPMDCount))
  3803. return indicatePessimisticFixpoint();
  3804. auto &Ctx = getAnchorValue().getContext();
  3805. if (KnownSPMDCount || AssumedSPMDCount) {
  3806. assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 &&
  3807. "Expected only SPMD kernels!");
  3808. // All reaching kernels are in SPMD mode. Update all function calls to
  3809. // __kmpc_is_spmd_exec_mode to 1.
  3810. SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
  3811. } else if (KnownNonSPMDCount || AssumedNonSPMDCount) {
  3812. assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 &&
  3813. "Expected only non-SPMD kernels!");
  3814. // All reaching kernels are in non-SPMD mode. Update all function
  3815. // calls to __kmpc_is_spmd_exec_mode to 0.
  3816. SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), false);
  3817. } else {
  3818. // We have empty reaching kernels, therefore we cannot tell if the
  3819. // associated call site can be folded. At this moment, SimplifiedValue
  3820. // must be none.
  3821. assert(!SimplifiedValue.hasValue() && "SimplifiedValue should be none");
  3822. }
  3823. return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
  3824. : ChangeStatus::CHANGED;
  3825. }
  3826. /// Fold __kmpc_is_generic_main_thread_id into a constant if possible.
  3827. ChangeStatus foldIsGenericMainThread(Attributor &A) {
  3828. Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
  3829. CallBase &CB = cast<CallBase>(getAssociatedValue());
  3830. Function *F = CB.getFunction();
  3831. const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
  3832. *this, IRPosition::function(*F), DepClassTy::REQUIRED);
  3833. if (!ExecutionDomainAA.isValidState())
  3834. return indicatePessimisticFixpoint();
  3835. auto &Ctx = getAnchorValue().getContext();
  3836. if (ExecutionDomainAA.isExecutedByInitialThreadOnly(CB))
  3837. SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
  3838. else
  3839. return indicatePessimisticFixpoint();
  3840. return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
  3841. : ChangeStatus::CHANGED;
  3842. }
  3843. /// Fold __kmpc_parallel_level into a constant if possible.
  3844. ChangeStatus foldParallelLevel(Attributor &A) {
  3845. Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
  3846. auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
  3847. *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
  3848. if (!CallerKernelInfoAA.ParallelLevels.isValidState())
  3849. return indicatePessimisticFixpoint();
  3850. if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
  3851. return indicatePessimisticFixpoint();
  3852. if (CallerKernelInfoAA.ReachingKernelEntries.empty()) {
  3853. assert(!SimplifiedValue.hasValue() &&
  3854. "SimplifiedValue should keep none at this point");
  3855. return ChangeStatus::UNCHANGED;
  3856. }
  3857. unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0;
  3858. unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0;
  3859. for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
  3860. auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K),
  3861. DepClassTy::REQUIRED);
  3862. if (!AA.SPMDCompatibilityTracker.isValidState())
  3863. return indicatePessimisticFixpoint();
  3864. if (AA.SPMDCompatibilityTracker.isAssumed()) {
  3865. if (AA.SPMDCompatibilityTracker.isAtFixpoint())
  3866. ++KnownSPMDCount;
  3867. else
  3868. ++AssumedSPMDCount;
  3869. } else {
  3870. if (AA.SPMDCompatibilityTracker.isAtFixpoint())
  3871. ++KnownNonSPMDCount;
  3872. else
  3873. ++AssumedNonSPMDCount;
  3874. }
  3875. }
  3876. if ((AssumedSPMDCount + KnownSPMDCount) &&
  3877. (AssumedNonSPMDCount + KnownNonSPMDCount))
  3878. return indicatePessimisticFixpoint();
  3879. auto &Ctx = getAnchorValue().getContext();
  3880. // If the caller can only be reached by SPMD kernel entries, the parallel
  3881. // level is 1. Similarly, if the caller can only be reached by non-SPMD
  3882. // kernel entries, it is 0.
  3883. if (AssumedSPMDCount || KnownSPMDCount) {
  3884. assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 &&
  3885. "Expected only SPMD kernels!");
  3886. SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 1);
  3887. } else {
  3888. assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 &&
  3889. "Expected only non-SPMD kernels!");
  3890. SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 0);
  3891. }
  3892. return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
  3893. : ChangeStatus::CHANGED;
  3894. }
  3895. ChangeStatus foldKernelFnAttribute(Attributor &A, llvm::StringRef Attr) {
  3896. // Specialize only if all the calls agree with the attribute constant value
  3897. int32_t CurrentAttrValue = -1;
  3898. Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
  3899. auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
  3900. *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
  3901. if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
  3902. return indicatePessimisticFixpoint();
  3903. // Iterate over the kernels that reach this function
  3904. for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
  3905. int32_t NextAttrVal = -1;
  3906. if (K->hasFnAttribute(Attr))
  3907. NextAttrVal =
  3908. std::stoi(K->getFnAttribute(Attr).getValueAsString().str());
  3909. if (NextAttrVal == -1 ||
  3910. (CurrentAttrValue != -1 && CurrentAttrValue != NextAttrVal))
  3911. return indicatePessimisticFixpoint();
  3912. CurrentAttrValue = NextAttrVal;
  3913. }
  3914. if (CurrentAttrValue != -1) {
  3915. auto &Ctx = getAnchorValue().getContext();
  3916. SimplifiedValue =
  3917. ConstantInt::get(Type::getInt32Ty(Ctx), CurrentAttrValue);
  3918. }
  3919. return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
  3920. : ChangeStatus::CHANGED;
  3921. }
  3922. /// An optional value the associated value is assumed to fold to. That is, we
  3923. /// assume the associated value (which is a call) can be replaced by this
  3924. /// simplified value.
  3925. Optional<Value *> SimplifiedValue;
  3926. /// The runtime function kind of the callee of the associated call site.
  3927. RuntimeFunction RFKind;
  3928. };
  3929. } // namespace
  3930. /// Register folding callsite
  3931. void OpenMPOpt::registerFoldRuntimeCall(RuntimeFunction RF) {
  3932. auto &RFI = OMPInfoCache.RFIs[RF];
  3933. RFI.foreachUse(SCC, [&](Use &U, Function &F) {
  3934. CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &RFI);
  3935. if (!CI)
  3936. return false;
  3937. A.getOrCreateAAFor<AAFoldRuntimeCall>(
  3938. IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr,
  3939. DepClassTy::NONE, /* ForceUpdate */ false,
  3940. /* UpdateAfterInit */ false);
  3941. return false;
  3942. });
  3943. }
  3944. void OpenMPOpt::registerAAs(bool IsModulePass) {
  3945. if (SCC.empty())
  3946. return;
  3947. if (IsModulePass) {
  3948. // Ensure we create the AAKernelInfo AAs first and without triggering an
  3949. // update. This will make sure we register all value simplification
  3950. // callbacks before any other AA has the chance to create an AAValueSimplify
  3951. // or similar.
  3952. for (Function *Kernel : OMPInfoCache.Kernels)
  3953. A.getOrCreateAAFor<AAKernelInfo>(
  3954. IRPosition::function(*Kernel), /* QueryingAA */ nullptr,
  3955. DepClassTy::NONE, /* ForceUpdate */ false,
  3956. /* UpdateAfterInit */ false);
  3957. registerFoldRuntimeCall(OMPRTL___kmpc_is_generic_main_thread_id);
  3958. registerFoldRuntimeCall(OMPRTL___kmpc_is_spmd_exec_mode);
  3959. registerFoldRuntimeCall(OMPRTL___kmpc_parallel_level);
  3960. registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_threads_in_block);
  3961. registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_blocks);
  3962. }
  3963. // Create CallSite AA for all Getters.
  3964. for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) {
  3965. auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)];
  3966. auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter];
  3967. auto CreateAA = [&](Use &U, Function &Caller) {
  3968. CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI);
  3969. if (!CI)
  3970. return false;
  3971. auto &CB = cast<CallBase>(*CI);
  3972. IRPosition CBPos = IRPosition::callsite_function(CB);
  3973. A.getOrCreateAAFor<AAICVTracker>(CBPos);
  3974. return false;
  3975. };
  3976. GetterRFI.foreachUse(SCC, CreateAA);
  3977. }
  3978. auto &GlobalizationRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
  3979. auto CreateAA = [&](Use &U, Function &F) {
  3980. A.getOrCreateAAFor<AAHeapToShared>(IRPosition::function(F));
  3981. return false;
  3982. };
  3983. if (!DisableOpenMPOptDeglobalization)
  3984. GlobalizationRFI.foreachUse(SCC, CreateAA);
  3985. // Create an ExecutionDomain AA for every function and a HeapToStack AA for
  3986. // every function if there is a device kernel.
  3987. if (!isOpenMPDevice(M))
  3988. return;
  3989. for (auto *F : SCC) {
  3990. if (F->isDeclaration())
  3991. continue;
  3992. A.getOrCreateAAFor<AAExecutionDomain>(IRPosition::function(*F));
  3993. if (!DisableOpenMPOptDeglobalization)
  3994. A.getOrCreateAAFor<AAHeapToStack>(IRPosition::function(*F));
  3995. for (auto &I : instructions(*F)) {
  3996. if (auto *LI = dyn_cast<LoadInst>(&I)) {
  3997. bool UsedAssumedInformation = false;
  3998. A.getAssumedSimplified(IRPosition::value(*LI), /* AA */ nullptr,
  3999. UsedAssumedInformation);
  4000. } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
  4001. A.getOrCreateAAFor<AAIsDead>(IRPosition::value(*SI));
  4002. }
  4003. }
  4004. }
  4005. }
  4006. const char AAICVTracker::ID = 0;
  4007. const char AAKernelInfo::ID = 0;
  4008. const char AAExecutionDomain::ID = 0;
  4009. const char AAHeapToShared::ID = 0;
  4010. const char AAFoldRuntimeCall::ID = 0;
  4011. AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP,
  4012. Attributor &A) {
  4013. AAICVTracker *AA = nullptr;
  4014. switch (IRP.getPositionKind()) {
  4015. case IRPosition::IRP_INVALID:
  4016. case IRPosition::IRP_FLOAT:
  4017. case IRPosition::IRP_ARGUMENT:
  4018. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  4019. llvm_unreachable("ICVTracker can only be created for function position!");
  4020. case IRPosition::IRP_RETURNED:
  4021. AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A);
  4022. break;
  4023. case IRPosition::IRP_CALL_SITE_RETURNED:
  4024. AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A);
  4025. break;
  4026. case IRPosition::IRP_CALL_SITE:
  4027. AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A);
  4028. break;
  4029. case IRPosition::IRP_FUNCTION:
  4030. AA = new (A.Allocator) AAICVTrackerFunction(IRP, A);
  4031. break;
  4032. }
  4033. return *AA;
  4034. }
  4035. AAExecutionDomain &AAExecutionDomain::createForPosition(const IRPosition &IRP,
  4036. Attributor &A) {
  4037. AAExecutionDomainFunction *AA = nullptr;
  4038. switch (IRP.getPositionKind()) {
  4039. case IRPosition::IRP_INVALID:
  4040. case IRPosition::IRP_FLOAT:
  4041. case IRPosition::IRP_ARGUMENT:
  4042. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  4043. case IRPosition::IRP_RETURNED:
  4044. case IRPosition::IRP_CALL_SITE_RETURNED:
  4045. case IRPosition::IRP_CALL_SITE:
  4046. llvm_unreachable(
  4047. "AAExecutionDomain can only be created for function position!");
  4048. case IRPosition::IRP_FUNCTION:
  4049. AA = new (A.Allocator) AAExecutionDomainFunction(IRP, A);
  4050. break;
  4051. }
  4052. return *AA;
  4053. }
  4054. AAHeapToShared &AAHeapToShared::createForPosition(const IRPosition &IRP,
  4055. Attributor &A) {
  4056. AAHeapToSharedFunction *AA = nullptr;
  4057. switch (IRP.getPositionKind()) {
  4058. case IRPosition::IRP_INVALID:
  4059. case IRPosition::IRP_FLOAT:
  4060. case IRPosition::IRP_ARGUMENT:
  4061. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  4062. case IRPosition::IRP_RETURNED:
  4063. case IRPosition::IRP_CALL_SITE_RETURNED:
  4064. case IRPosition::IRP_CALL_SITE:
  4065. llvm_unreachable(
  4066. "AAHeapToShared can only be created for function position!");
  4067. case IRPosition::IRP_FUNCTION:
  4068. AA = new (A.Allocator) AAHeapToSharedFunction(IRP, A);
  4069. break;
  4070. }
  4071. return *AA;
  4072. }
  4073. AAKernelInfo &AAKernelInfo::createForPosition(const IRPosition &IRP,
  4074. Attributor &A) {
  4075. AAKernelInfo *AA = nullptr;
  4076. switch (IRP.getPositionKind()) {
  4077. case IRPosition::IRP_INVALID:
  4078. case IRPosition::IRP_FLOAT:
  4079. case IRPosition::IRP_ARGUMENT:
  4080. case IRPosition::IRP_RETURNED:
  4081. case IRPosition::IRP_CALL_SITE_RETURNED:
  4082. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  4083. llvm_unreachable("KernelInfo can only be created for function position!");
  4084. case IRPosition::IRP_CALL_SITE:
  4085. AA = new (A.Allocator) AAKernelInfoCallSite(IRP, A);
  4086. break;
  4087. case IRPosition::IRP_FUNCTION:
  4088. AA = new (A.Allocator) AAKernelInfoFunction(IRP, A);
  4089. break;
  4090. }
  4091. return *AA;
  4092. }
  4093. AAFoldRuntimeCall &AAFoldRuntimeCall::createForPosition(const IRPosition &IRP,
  4094. Attributor &A) {
  4095. AAFoldRuntimeCall *AA = nullptr;
  4096. switch (IRP.getPositionKind()) {
  4097. case IRPosition::IRP_INVALID:
  4098. case IRPosition::IRP_FLOAT:
  4099. case IRPosition::IRP_ARGUMENT:
  4100. case IRPosition::IRP_RETURNED:
  4101. case IRPosition::IRP_FUNCTION:
  4102. case IRPosition::IRP_CALL_SITE:
  4103. case IRPosition::IRP_CALL_SITE_ARGUMENT:
  4104. llvm_unreachable("KernelInfo can only be created for call site position!");
  4105. case IRPosition::IRP_CALL_SITE_RETURNED:
  4106. AA = new (A.Allocator) AAFoldRuntimeCallCallSiteReturned(IRP, A);
  4107. break;
  4108. }
  4109. return *AA;
  4110. }
  4111. PreservedAnalyses OpenMPOptPass::run(Module &M, ModuleAnalysisManager &AM) {
  4112. if (!containsOpenMP(M))
  4113. return PreservedAnalyses::all();
  4114. if (DisableOpenMPOptimizations)
  4115. return PreservedAnalyses::all();
  4116. FunctionAnalysisManager &FAM =
  4117. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  4118. KernelSet Kernels = getDeviceKernels(M);
  4119. auto IsCalled = [&](Function &F) {
  4120. if (Kernels.contains(&F))
  4121. return true;
  4122. for (const User *U : F.users())
  4123. if (!isa<BlockAddress>(U))
  4124. return true;
  4125. return false;
  4126. };
  4127. auto EmitRemark = [&](Function &F) {
  4128. auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  4129. ORE.emit([&]() {
  4130. OptimizationRemarkAnalysis ORA(DEBUG_TYPE, "OMP140", &F);
  4131. return ORA << "Could not internalize function. "
  4132. << "Some optimizations may not be possible. [OMP140]";
  4133. });
  4134. };
  4135. // Create internal copies of each function if this is a kernel Module. This
  4136. // allows iterprocedural passes to see every call edge.
  4137. DenseMap<Function *, Function *> InternalizedMap;
  4138. if (isOpenMPDevice(M)) {
  4139. SmallPtrSet<Function *, 16> InternalizeFns;
  4140. for (Function &F : M)
  4141. if (!F.isDeclaration() && !Kernels.contains(&F) && IsCalled(F) &&
  4142. !DisableInternalization) {
  4143. if (Attributor::isInternalizable(F)) {
  4144. InternalizeFns.insert(&F);
  4145. } else if (!F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::Cold)) {
  4146. EmitRemark(F);
  4147. }
  4148. }
  4149. Attributor::internalizeFunctions(InternalizeFns, InternalizedMap);
  4150. }
  4151. // Look at every function in the Module unless it was internalized.
  4152. SmallVector<Function *, 16> SCC;
  4153. for (Function &F : M)
  4154. if (!F.isDeclaration() && !InternalizedMap.lookup(&F))
  4155. SCC.push_back(&F);
  4156. if (SCC.empty())
  4157. return PreservedAnalyses::all();
  4158. AnalysisGetter AG(FAM);
  4159. auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
  4160. return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
  4161. };
  4162. BumpPtrAllocator Allocator;
  4163. CallGraphUpdater CGUpdater;
  4164. SetVector<Function *> Functions(SCC.begin(), SCC.end());
  4165. OMPInformationCache InfoCache(M, AG, Allocator, /*CGSCC*/ Functions, Kernels);
  4166. unsigned MaxFixpointIterations =
  4167. (isOpenMPDevice(M)) ? SetFixpointIterations : 32;
  4168. Attributor A(Functions, InfoCache, CGUpdater, nullptr, true, false,
  4169. MaxFixpointIterations, OREGetter, DEBUG_TYPE);
  4170. OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
  4171. bool Changed = OMPOpt.run(true);
  4172. // Optionally inline device functions for potentially better performance.
  4173. if (AlwaysInlineDeviceFunctions && isOpenMPDevice(M))
  4174. for (Function &F : M)
  4175. if (!F.isDeclaration() && !Kernels.contains(&F) &&
  4176. !F.hasFnAttribute(Attribute::NoInline))
  4177. F.addFnAttr(Attribute::AlwaysInline);
  4178. if (PrintModuleAfterOptimizations)
  4179. LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt Module Pass:\n" << M);
  4180. if (Changed)
  4181. return PreservedAnalyses::none();
  4182. return PreservedAnalyses::all();
  4183. }
  4184. PreservedAnalyses OpenMPOptCGSCCPass::run(LazyCallGraph::SCC &C,
  4185. CGSCCAnalysisManager &AM,
  4186. LazyCallGraph &CG,
  4187. CGSCCUpdateResult &UR) {
  4188. if (!containsOpenMP(*C.begin()->getFunction().getParent()))
  4189. return PreservedAnalyses::all();
  4190. if (DisableOpenMPOptimizations)
  4191. return PreservedAnalyses::all();
  4192. SmallVector<Function *, 16> SCC;
  4193. // If there are kernels in the module, we have to run on all SCC's.
  4194. for (LazyCallGraph::Node &N : C) {
  4195. Function *Fn = &N.getFunction();
  4196. SCC.push_back(Fn);
  4197. }
  4198. if (SCC.empty())
  4199. return PreservedAnalyses::all();
  4200. Module &M = *C.begin()->getFunction().getParent();
  4201. KernelSet Kernels = getDeviceKernels(M);
  4202. FunctionAnalysisManager &FAM =
  4203. AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
  4204. AnalysisGetter AG(FAM);
  4205. auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
  4206. return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
  4207. };
  4208. BumpPtrAllocator Allocator;
  4209. CallGraphUpdater CGUpdater;
  4210. CGUpdater.initialize(CG, C, AM, UR);
  4211. SetVector<Function *> Functions(SCC.begin(), SCC.end());
  4212. OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator,
  4213. /*CGSCC*/ Functions, Kernels);
  4214. unsigned MaxFixpointIterations =
  4215. (isOpenMPDevice(M)) ? SetFixpointIterations : 32;
  4216. Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
  4217. MaxFixpointIterations, OREGetter, DEBUG_TYPE);
  4218. OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
  4219. bool Changed = OMPOpt.run(false);
  4220. if (PrintModuleAfterOptimizations)
  4221. LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt CGSCC Pass:\n" << M);
  4222. if (Changed)
  4223. return PreservedAnalyses::none();
  4224. return PreservedAnalyses::all();
  4225. }
  4226. namespace {
  4227. struct OpenMPOptCGSCCLegacyPass : public CallGraphSCCPass {
  4228. CallGraphUpdater CGUpdater;
  4229. static char ID;
  4230. OpenMPOptCGSCCLegacyPass() : CallGraphSCCPass(ID) {
  4231. initializeOpenMPOptCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
  4232. }
  4233. void getAnalysisUsage(AnalysisUsage &AU) const override {
  4234. CallGraphSCCPass::getAnalysisUsage(AU);
  4235. }
  4236. bool runOnSCC(CallGraphSCC &CGSCC) override {
  4237. if (!containsOpenMP(CGSCC.getCallGraph().getModule()))
  4238. return false;
  4239. if (DisableOpenMPOptimizations || skipSCC(CGSCC))
  4240. return false;
  4241. SmallVector<Function *, 16> SCC;
  4242. // If there are kernels in the module, we have to run on all SCC's.
  4243. for (CallGraphNode *CGN : CGSCC) {
  4244. Function *Fn = CGN->getFunction();
  4245. if (!Fn || Fn->isDeclaration())
  4246. continue;
  4247. SCC.push_back(Fn);
  4248. }
  4249. if (SCC.empty())
  4250. return false;
  4251. Module &M = CGSCC.getCallGraph().getModule();
  4252. KernelSet Kernels = getDeviceKernels(M);
  4253. CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
  4254. CGUpdater.initialize(CG, CGSCC);
  4255. // Maintain a map of functions to avoid rebuilding the ORE
  4256. DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap;
  4257. auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & {
  4258. std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F];
  4259. if (!ORE)
  4260. ORE = std::make_unique<OptimizationRemarkEmitter>(F);
  4261. return *ORE;
  4262. };
  4263. AnalysisGetter AG;
  4264. SetVector<Function *> Functions(SCC.begin(), SCC.end());
  4265. BumpPtrAllocator Allocator;
  4266. OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG,
  4267. Allocator,
  4268. /*CGSCC*/ Functions, Kernels);
  4269. unsigned MaxFixpointIterations =
  4270. (isOpenMPDevice(M)) ? SetFixpointIterations : 32;
  4271. Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
  4272. MaxFixpointIterations, OREGetter, DEBUG_TYPE);
  4273. OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
  4274. bool Result = OMPOpt.run(false);
  4275. if (PrintModuleAfterOptimizations)
  4276. LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt CGSCC Pass:\n" << M);
  4277. return Result;
  4278. }
  4279. bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
  4280. };
  4281. } // end anonymous namespace
  4282. KernelSet llvm::omp::getDeviceKernels(Module &M) {
  4283. // TODO: Create a more cross-platform way of determining device kernels.
  4284. NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
  4285. KernelSet Kernels;
  4286. if (!MD)
  4287. return Kernels;
  4288. for (auto *Op : MD->operands()) {
  4289. if (Op->getNumOperands() < 2)
  4290. continue;
  4291. MDString *KindID = dyn_cast<MDString>(Op->getOperand(1));
  4292. if (!KindID || KindID->getString() != "kernel")
  4293. continue;
  4294. Function *KernelFn =
  4295. mdconst::dyn_extract_or_null<Function>(Op->getOperand(0));
  4296. if (!KernelFn)
  4297. continue;
  4298. ++NumOpenMPTargetRegionKernels;
  4299. Kernels.insert(KernelFn);
  4300. }
  4301. return Kernels;
  4302. }
  4303. bool llvm::omp::containsOpenMP(Module &M) {
  4304. Metadata *MD = M.getModuleFlag("openmp");
  4305. if (!MD)
  4306. return false;
  4307. return true;
  4308. }
  4309. bool llvm::omp::isOpenMPDevice(Module &M) {
  4310. Metadata *MD = M.getModuleFlag("openmp-device");
  4311. if (!MD)
  4312. return false;
  4313. return true;
  4314. }
  4315. char OpenMPOptCGSCCLegacyPass::ID = 0;
  4316. INITIALIZE_PASS_BEGIN(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
  4317. "OpenMP specific optimizations", false, false)
  4318. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  4319. INITIALIZE_PASS_END(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
  4320. "OpenMP specific optimizations", false, false)
  4321. Pass *llvm::createOpenMPOptCGSCCLegacyPass() {
  4322. return new OpenMPOptCGSCCLegacyPass();
  4323. }