SemaOpenMP.cpp 512 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static Expr *CheckMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// \brief Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
  45. };
  46. /// Attributes of the defaultmap clause.
  47. enum DefaultMapAttributes {
  48. DMA_unspecified, /// Default mapping is not specified.
  49. DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
  50. };
  51. /// \brief Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy final {
  54. public:
  55. struct DSAVarData final {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
  63. DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
  64. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  65. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  66. };
  67. typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
  68. OperatorOffsetTy;
  69. private:
  70. struct DSAInfo final {
  71. OpenMPClauseKind Attributes = OMPC_unknown;
  72. /// Pointer to a reference expression and a flag which shows that the
  73. /// variable is marked as lastprivate(true) or not (false).
  74. llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
  75. DeclRefExpr *PrivateCopy = nullptr;
  76. };
  77. typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
  78. typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
  79. typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
  80. typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
  81. /// Struct that associates a component with the clause kind where they are
  82. /// found.
  83. struct MappedExprComponentTy {
  84. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  85. OpenMPClauseKind Kind = OMPC_unknown;
  86. };
  87. typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
  88. MappedExprComponentsTy;
  89. typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
  90. CriticalsWithHintsTy;
  91. typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
  92. DoacrossDependMapTy;
  93. struct ReductionData {
  94. typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
  95. SourceRange ReductionRange;
  96. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  97. ReductionData() = default;
  98. void set(BinaryOperatorKind BO, SourceRange RR) {
  99. ReductionRange = RR;
  100. ReductionOp = BO;
  101. }
  102. void set(const Expr *RefExpr, SourceRange RR) {
  103. ReductionRange = RR;
  104. ReductionOp = RefExpr;
  105. }
  106. };
  107. typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
  108. struct SharingMapTy final {
  109. DeclSAMapTy SharingMap;
  110. DeclReductionMapTy ReductionMap;
  111. AlignedMapTy AlignedMap;
  112. MappedExprComponentsTy MappedExprComponents;
  113. LoopControlVariablesMapTy LCVMap;
  114. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  115. SourceLocation DefaultAttrLoc;
  116. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  117. SourceLocation DefaultMapAttrLoc;
  118. OpenMPDirectiveKind Directive = OMPD_unknown;
  119. DeclarationNameInfo DirectiveName;
  120. Scope *CurScope = nullptr;
  121. SourceLocation ConstructLoc;
  122. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  123. /// get the data (loop counters etc.) about enclosing loop-based construct.
  124. /// This data is required during codegen.
  125. DoacrossDependMapTy DoacrossDepends;
  126. /// \brief first argument (Expr *) contains optional argument of the
  127. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  128. /// clause, false otherwise.
  129. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
  130. bool NowaitRegion = false;
  131. bool CancelRegion = false;
  132. unsigned AssociatedLoops = 1;
  133. SourceLocation InnerTeamsRegionLoc;
  134. /// Reference to the taskgroup task_reduction reference expression.
  135. Expr *TaskgroupReductionRef = nullptr;
  136. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  137. Scope *CurScope, SourceLocation Loc)
  138. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  139. ConstructLoc(Loc) {}
  140. SharingMapTy() = default;
  141. };
  142. typedef SmallVector<SharingMapTy, 4> StackTy;
  143. /// \brief Stack of used declaration and their data-sharing attributes.
  144. DeclSAMapTy Threadprivates;
  145. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  146. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  147. /// \brief true, if check for DSA must be from parent directive, false, if
  148. /// from current directive.
  149. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  150. Sema &SemaRef;
  151. bool ForceCapturing = false;
  152. CriticalsWithHintsTy Criticals;
  153. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  154. DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
  155. /// \brief Checks if the variable is a local for OpenMP region.
  156. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  157. bool isStackEmpty() const {
  158. return Stack.empty() ||
  159. Stack.back().second != CurrentNonCapturingFunctionScope ||
  160. Stack.back().first.empty();
  161. }
  162. public:
  163. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  164. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  165. OpenMPClauseKind getClauseParsingMode() const {
  166. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  167. return ClauseKindMode;
  168. }
  169. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  170. bool isForceVarCapturing() const { return ForceCapturing; }
  171. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  172. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  173. Scope *CurScope, SourceLocation Loc) {
  174. if (Stack.empty() ||
  175. Stack.back().second != CurrentNonCapturingFunctionScope)
  176. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  177. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  178. Stack.back().first.back().DefaultAttrLoc = Loc;
  179. }
  180. void pop() {
  181. assert(!Stack.back().first.empty() &&
  182. "Data-sharing attributes stack is empty!");
  183. Stack.back().first.pop_back();
  184. }
  185. /// Start new OpenMP region stack in new non-capturing function.
  186. void pushFunction() {
  187. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  188. assert(!isa<CapturingScopeInfo>(CurFnScope));
  189. CurrentNonCapturingFunctionScope = CurFnScope;
  190. }
  191. /// Pop region stack for non-capturing function.
  192. void popFunction(const FunctionScopeInfo *OldFSI) {
  193. if (!Stack.empty() && Stack.back().second == OldFSI) {
  194. assert(Stack.back().first.empty());
  195. Stack.pop_back();
  196. }
  197. CurrentNonCapturingFunctionScope = nullptr;
  198. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  199. if (!isa<CapturingScopeInfo>(FSI)) {
  200. CurrentNonCapturingFunctionScope = FSI;
  201. break;
  202. }
  203. }
  204. }
  205. void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
  206. Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
  207. }
  208. const std::pair<OMPCriticalDirective *, llvm::APSInt>
  209. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  210. auto I = Criticals.find(Name.getAsString());
  211. if (I != Criticals.end())
  212. return I->second;
  213. return std::make_pair(nullptr, llvm::APSInt());
  214. }
  215. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  216. /// add it and return NULL; otherwise return previous occurrence's expression
  217. /// for diagnostics.
  218. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
  219. /// \brief Register specified variable as loop control variable.
  220. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
  221. /// \brief Check if the specified variable is a loop control variable for
  222. /// current region.
  223. /// \return The index of the loop control variable in the list of associated
  224. /// for-loops (from outer to inner).
  225. LCDeclInfo isLoopControlVariable(ValueDecl *D);
  226. /// \brief Check if the specified variable is a loop control variable for
  227. /// parent region.
  228. /// \return The index of the loop control variable in the list of associated
  229. /// for-loops (from outer to inner).
  230. LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
  231. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  232. /// parent directive.
  233. ValueDecl *getParentLoopControlVariable(unsigned I);
  234. /// \brief Adds explicit data sharing attribute to the specified declaration.
  235. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  236. DeclRefExpr *PrivateCopy = nullptr);
  237. /// Adds additional information for the reduction items with the reduction id
  238. /// represented as an operator.
  239. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  240. BinaryOperatorKind BOK);
  241. /// Adds additional information for the reduction items with the reduction id
  242. /// represented as reduction identifier.
  243. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  244. const Expr *ReductionRef);
  245. /// Returns the location and reduction operation from the innermost parent
  246. /// region for the given \p D.
  247. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  248. BinaryOperatorKind &BOK,
  249. Expr *&TaskgroupDescriptor);
  250. /// Returns the location and reduction operation from the innermost parent
  251. /// region for the given \p D.
  252. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  253. const Expr *&ReductionRef,
  254. Expr *&TaskgroupDescriptor);
  255. /// Return reduction reference expression for the current taskgroup.
  256. Expr *getTaskgroupReductionRef() const {
  257. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  258. "taskgroup reference expression requested for non taskgroup "
  259. "directive.");
  260. return Stack.back().first.back().TaskgroupReductionRef;
  261. }
  262. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  263. /// descriptor variable at the \p Level of OpenMP regions.
  264. bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
  265. return Stack.back().first[Level].TaskgroupReductionRef &&
  266. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  267. ->getDecl() == VD;
  268. }
  269. /// \brief Returns data sharing attributes from top of the stack for the
  270. /// specified declaration.
  271. DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  272. /// \brief Returns data-sharing attributes for the specified declaration.
  273. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
  274. /// \brief Checks if the specified variables has data-sharing attributes which
  275. /// match specified \a CPred predicate in any directive which matches \a DPred
  276. /// predicate.
  277. DSAVarData hasDSA(ValueDecl *D,
  278. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  279. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  280. bool FromParent);
  281. /// \brief Checks if the specified variables has data-sharing attributes which
  282. /// match specified \a CPred predicate in any innermost directive which
  283. /// matches \a DPred predicate.
  284. DSAVarData
  285. hasInnermostDSA(ValueDecl *D,
  286. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  287. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  288. bool FromParent);
  289. /// \brief Checks if the specified variables has explicit data-sharing
  290. /// attributes which match specified \a CPred predicate at the specified
  291. /// OpenMP region.
  292. bool hasExplicitDSA(ValueDecl *D,
  293. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  294. unsigned Level, bool NotLastprivate = false);
  295. /// \brief Returns true if the directive at level \Level matches in the
  296. /// specified \a DPred predicate.
  297. bool hasExplicitDirective(
  298. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  299. unsigned Level);
  300. /// \brief Finds a directive which matches specified \a DPred predicate.
  301. bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
  302. const DeclarationNameInfo &,
  303. SourceLocation)> &DPred,
  304. bool FromParent);
  305. /// \brief Returns currently analyzed directive.
  306. OpenMPDirectiveKind getCurrentDirective() const {
  307. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  308. }
  309. /// \brief Returns directive kind at specified level.
  310. OpenMPDirectiveKind getDirective(unsigned Level) const {
  311. assert(!isStackEmpty() && "No directive at specified level.");
  312. return Stack.back().first[Level].Directive;
  313. }
  314. /// \brief Returns parent directive.
  315. OpenMPDirectiveKind getParentDirective() const {
  316. if (isStackEmpty() || Stack.back().first.size() == 1)
  317. return OMPD_unknown;
  318. return std::next(Stack.back().first.rbegin())->Directive;
  319. }
  320. /// \brief Set default data sharing attribute to none.
  321. void setDefaultDSANone(SourceLocation Loc) {
  322. assert(!isStackEmpty());
  323. Stack.back().first.back().DefaultAttr = DSA_none;
  324. Stack.back().first.back().DefaultAttrLoc = Loc;
  325. }
  326. /// \brief Set default data sharing attribute to shared.
  327. void setDefaultDSAShared(SourceLocation Loc) {
  328. assert(!isStackEmpty());
  329. Stack.back().first.back().DefaultAttr = DSA_shared;
  330. Stack.back().first.back().DefaultAttrLoc = Loc;
  331. }
  332. /// Set default data mapping attribute to 'tofrom:scalar'.
  333. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  334. assert(!isStackEmpty());
  335. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  336. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  337. }
  338. DefaultDataSharingAttributes getDefaultDSA() const {
  339. return isStackEmpty() ? DSA_unspecified
  340. : Stack.back().first.back().DefaultAttr;
  341. }
  342. SourceLocation getDefaultDSALocation() const {
  343. return isStackEmpty() ? SourceLocation()
  344. : Stack.back().first.back().DefaultAttrLoc;
  345. }
  346. DefaultMapAttributes getDefaultDMA() const {
  347. return isStackEmpty() ? DMA_unspecified
  348. : Stack.back().first.back().DefaultMapAttr;
  349. }
  350. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  351. return Stack.back().first[Level].DefaultMapAttr;
  352. }
  353. SourceLocation getDefaultDMALocation() const {
  354. return isStackEmpty() ? SourceLocation()
  355. : Stack.back().first.back().DefaultMapAttrLoc;
  356. }
  357. /// \brief Checks if the specified variable is a threadprivate.
  358. bool isThreadPrivate(VarDecl *D) {
  359. DSAVarData DVar = getTopDSA(D, false);
  360. return isOpenMPThreadPrivate(DVar.CKind);
  361. }
  362. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  363. void setOrderedRegion(bool IsOrdered, Expr *Param) {
  364. assert(!isStackEmpty());
  365. Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
  366. Stack.back().first.back().OrderedRegion.setPointer(Param);
  367. }
  368. /// \brief Returns true, if parent region is ordered (has associated
  369. /// 'ordered' clause), false - otherwise.
  370. bool isParentOrderedRegion() const {
  371. if (isStackEmpty() || Stack.back().first.size() == 1)
  372. return false;
  373. return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
  374. }
  375. /// \brief Returns optional parameter for the ordered region.
  376. Expr *getParentOrderedRegionParam() const {
  377. if (isStackEmpty() || Stack.back().first.size() == 1)
  378. return nullptr;
  379. return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
  380. }
  381. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  382. void setNowaitRegion(bool IsNowait = true) {
  383. assert(!isStackEmpty());
  384. Stack.back().first.back().NowaitRegion = IsNowait;
  385. }
  386. /// \brief Returns true, if parent region is nowait (has associated
  387. /// 'nowait' clause), false - otherwise.
  388. bool isParentNowaitRegion() const {
  389. if (isStackEmpty() || Stack.back().first.size() == 1)
  390. return false;
  391. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  392. }
  393. /// \brief Marks parent region as cancel region.
  394. void setParentCancelRegion(bool Cancel = true) {
  395. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  396. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  397. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  398. }
  399. }
  400. /// \brief Return true if current region has inner cancel construct.
  401. bool isCancelRegion() const {
  402. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  403. }
  404. /// \brief Set collapse value for the region.
  405. void setAssociatedLoops(unsigned Val) {
  406. assert(!isStackEmpty());
  407. Stack.back().first.back().AssociatedLoops = Val;
  408. }
  409. /// \brief Return collapse value for region.
  410. unsigned getAssociatedLoops() const {
  411. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  412. }
  413. /// \brief Marks current target region as one with closely nested teams
  414. /// region.
  415. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  416. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  417. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  418. TeamsRegionLoc;
  419. }
  420. }
  421. /// \brief Returns true, if current region has closely nested teams region.
  422. bool hasInnerTeamsRegion() const {
  423. return getInnerTeamsRegionLoc().isValid();
  424. }
  425. /// \brief Returns location of the nested teams region (if any).
  426. SourceLocation getInnerTeamsRegionLoc() const {
  427. return isStackEmpty() ? SourceLocation()
  428. : Stack.back().first.back().InnerTeamsRegionLoc;
  429. }
  430. Scope *getCurScope() const {
  431. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  432. }
  433. Scope *getCurScope() {
  434. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  435. }
  436. SourceLocation getConstructLoc() {
  437. return isStackEmpty() ? SourceLocation()
  438. : Stack.back().first.back().ConstructLoc;
  439. }
  440. /// Do the check specified in \a Check to all component lists and return true
  441. /// if any issue is found.
  442. bool checkMappableExprComponentListsForDecl(
  443. ValueDecl *VD, bool CurrentRegionOnly,
  444. const llvm::function_ref<
  445. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  446. OpenMPClauseKind)> &Check) {
  447. if (isStackEmpty())
  448. return false;
  449. auto SI = Stack.back().first.rbegin();
  450. auto SE = Stack.back().first.rend();
  451. if (SI == SE)
  452. return false;
  453. if (CurrentRegionOnly) {
  454. SE = std::next(SI);
  455. } else {
  456. ++SI;
  457. }
  458. for (; SI != SE; ++SI) {
  459. auto MI = SI->MappedExprComponents.find(VD);
  460. if (MI != SI->MappedExprComponents.end())
  461. for (auto &L : MI->second.Components)
  462. if (Check(L, MI->second.Kind))
  463. return true;
  464. }
  465. return false;
  466. }
  467. /// Do the check specified in \a Check to all component lists at a given level
  468. /// and return true if any issue is found.
  469. bool checkMappableExprComponentListsForDeclAtLevel(
  470. ValueDecl *VD, unsigned Level,
  471. const llvm::function_ref<
  472. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  473. OpenMPClauseKind)> &Check) {
  474. if (isStackEmpty())
  475. return false;
  476. auto StartI = Stack.back().first.begin();
  477. auto EndI = Stack.back().first.end();
  478. if (std::distance(StartI, EndI) <= (int)Level)
  479. return false;
  480. std::advance(StartI, Level);
  481. auto MI = StartI->MappedExprComponents.find(VD);
  482. if (MI != StartI->MappedExprComponents.end())
  483. for (auto &L : MI->second.Components)
  484. if (Check(L, MI->second.Kind))
  485. return true;
  486. return false;
  487. }
  488. /// Create a new mappable expression component list associated with a given
  489. /// declaration and initialize it with the provided list of components.
  490. void addMappableExpressionComponents(
  491. ValueDecl *VD,
  492. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  493. OpenMPClauseKind WhereFoundClauseKind) {
  494. assert(!isStackEmpty() &&
  495. "Not expecting to retrieve components from a empty stack!");
  496. auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
  497. // Create new entry and append the new components there.
  498. MEC.Components.resize(MEC.Components.size() + 1);
  499. MEC.Components.back().append(Components.begin(), Components.end());
  500. MEC.Kind = WhereFoundClauseKind;
  501. }
  502. unsigned getNestingLevel() const {
  503. assert(!isStackEmpty());
  504. return Stack.back().first.size() - 1;
  505. }
  506. void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
  507. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  508. auto &StackElem = *std::next(Stack.back().first.rbegin());
  509. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  510. StackElem.DoacrossDepends.insert({C, OpsOffs});
  511. }
  512. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  513. getDoacrossDependClauses() const {
  514. assert(!isStackEmpty());
  515. auto &StackElem = Stack.back().first.back();
  516. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  517. auto &Ref = StackElem.DoacrossDepends;
  518. return llvm::make_range(Ref.begin(), Ref.end());
  519. }
  520. return llvm::make_range(StackElem.DoacrossDepends.end(),
  521. StackElem.DoacrossDepends.end());
  522. }
  523. };
  524. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  525. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  526. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  527. }
  528. } // namespace
  529. static Expr *getExprAsWritten(Expr *E) {
  530. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  531. E = ExprTemp->getSubExpr();
  532. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  533. E = MTE->GetTemporaryExpr();
  534. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  535. E = Binder->getSubExpr();
  536. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  537. E = ICE->getSubExprAsWritten();
  538. return E->IgnoreParens();
  539. }
  540. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  541. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  542. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  543. D = ME->getMemberDecl();
  544. auto *VD = dyn_cast<VarDecl>(D);
  545. auto *FD = dyn_cast<FieldDecl>(D);
  546. if (VD != nullptr) {
  547. VD = VD->getCanonicalDecl();
  548. D = VD;
  549. } else {
  550. assert(FD);
  551. FD = FD->getCanonicalDecl();
  552. D = FD;
  553. }
  554. return D;
  555. }
  556. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
  557. ValueDecl *D) {
  558. D = getCanonicalDecl(D);
  559. auto *VD = dyn_cast<VarDecl>(D);
  560. auto *FD = dyn_cast<FieldDecl>(D);
  561. DSAVarData DVar;
  562. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  563. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  564. // in a region but not in construct]
  565. // File-scope or namespace-scope variables referenced in called routines
  566. // in the region are shared unless they appear in a threadprivate
  567. // directive.
  568. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  569. DVar.CKind = OMPC_shared;
  570. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  571. // in a region but not in construct]
  572. // Variables with static storage duration that are declared in called
  573. // routines in the region are shared.
  574. if (VD && VD->hasGlobalStorage())
  575. DVar.CKind = OMPC_shared;
  576. // Non-static data members are shared by default.
  577. if (FD)
  578. DVar.CKind = OMPC_shared;
  579. return DVar;
  580. }
  581. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  582. // in a Construct, C/C++, predetermined, p.1]
  583. // Variables with automatic storage duration that are declared in a scope
  584. // inside the construct are private.
  585. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  586. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  587. DVar.CKind = OMPC_private;
  588. return DVar;
  589. }
  590. DVar.DKind = Iter->Directive;
  591. // Explicitly specified attributes and local variables with predetermined
  592. // attributes.
  593. if (Iter->SharingMap.count(D)) {
  594. DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
  595. DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
  596. DVar.CKind = Iter->SharingMap[D].Attributes;
  597. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  598. return DVar;
  599. }
  600. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  601. // in a Construct, C/C++, implicitly determined, p.1]
  602. // In a parallel or task construct, the data-sharing attributes of these
  603. // variables are determined by the default clause, if present.
  604. switch (Iter->DefaultAttr) {
  605. case DSA_shared:
  606. DVar.CKind = OMPC_shared;
  607. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  608. return DVar;
  609. case DSA_none:
  610. return DVar;
  611. case DSA_unspecified:
  612. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  613. // in a Construct, implicitly determined, p.2]
  614. // In a parallel construct, if no default clause is present, these
  615. // variables are shared.
  616. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  617. if (isOpenMPParallelDirective(DVar.DKind) ||
  618. isOpenMPTeamsDirective(DVar.DKind)) {
  619. DVar.CKind = OMPC_shared;
  620. return DVar;
  621. }
  622. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  623. // in a Construct, implicitly determined, p.4]
  624. // In a task construct, if no default clause is present, a variable that in
  625. // the enclosing context is determined to be shared by all implicit tasks
  626. // bound to the current team is shared.
  627. if (isOpenMPTaskingDirective(DVar.DKind)) {
  628. DSAVarData DVarTemp;
  629. auto I = Iter, E = Stack.back().first.rend();
  630. do {
  631. ++I;
  632. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  633. // Referenced in a Construct, implicitly determined, p.6]
  634. // In a task construct, if no default clause is present, a variable
  635. // whose data-sharing attribute is not determined by the rules above is
  636. // firstprivate.
  637. DVarTemp = getDSA(I, D);
  638. if (DVarTemp.CKind != OMPC_shared) {
  639. DVar.RefExpr = nullptr;
  640. DVar.CKind = OMPC_firstprivate;
  641. return DVar;
  642. }
  643. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  644. DVar.CKind =
  645. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  646. return DVar;
  647. }
  648. }
  649. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  650. // in a Construct, implicitly determined, p.3]
  651. // For constructs other than task, if no default clause is present, these
  652. // variables inherit their data-sharing attributes from the enclosing
  653. // context.
  654. return getDSA(++Iter, D);
  655. }
  656. Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
  657. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  658. D = getCanonicalDecl(D);
  659. auto &StackElem = Stack.back().first.back();
  660. auto It = StackElem.AlignedMap.find(D);
  661. if (It == StackElem.AlignedMap.end()) {
  662. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  663. StackElem.AlignedMap[D] = NewDE;
  664. return nullptr;
  665. } else {
  666. assert(It->second && "Unexpected nullptr expr in the aligned map");
  667. return It->second;
  668. }
  669. return nullptr;
  670. }
  671. void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
  672. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  673. D = getCanonicalDecl(D);
  674. auto &StackElem = Stack.back().first.back();
  675. StackElem.LCVMap.insert(
  676. {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
  677. }
  678. DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
  679. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  680. D = getCanonicalDecl(D);
  681. auto &StackElem = Stack.back().first.back();
  682. auto It = StackElem.LCVMap.find(D);
  683. if (It != StackElem.LCVMap.end())
  684. return It->second;
  685. return {0, nullptr};
  686. }
  687. DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
  688. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  689. "Data-sharing attributes stack is empty");
  690. D = getCanonicalDecl(D);
  691. auto &StackElem = *std::next(Stack.back().first.rbegin());
  692. auto It = StackElem.LCVMap.find(D);
  693. if (It != StackElem.LCVMap.end())
  694. return It->second;
  695. return {0, nullptr};
  696. }
  697. ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
  698. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  699. "Data-sharing attributes stack is empty");
  700. auto &StackElem = *std::next(Stack.back().first.rbegin());
  701. if (StackElem.LCVMap.size() < I)
  702. return nullptr;
  703. for (auto &Pair : StackElem.LCVMap)
  704. if (Pair.second.first == I)
  705. return Pair.first;
  706. return nullptr;
  707. }
  708. void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  709. DeclRefExpr *PrivateCopy) {
  710. D = getCanonicalDecl(D);
  711. if (A == OMPC_threadprivate) {
  712. auto &Data = Threadprivates[D];
  713. Data.Attributes = A;
  714. Data.RefExpr.setPointer(E);
  715. Data.PrivateCopy = nullptr;
  716. } else {
  717. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  718. auto &Data = Stack.back().first.back().SharingMap[D];
  719. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  720. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  721. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  722. (isLoopControlVariable(D).first && A == OMPC_private));
  723. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  724. Data.RefExpr.setInt(/*IntVal=*/true);
  725. return;
  726. }
  727. const bool IsLastprivate =
  728. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  729. Data.Attributes = A;
  730. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  731. Data.PrivateCopy = PrivateCopy;
  732. if (PrivateCopy) {
  733. auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  734. Data.Attributes = A;
  735. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  736. Data.PrivateCopy = nullptr;
  737. }
  738. }
  739. }
  740. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  741. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  742. StringRef Name, const AttrVec *Attrs = nullptr) {
  743. DeclContext *DC = SemaRef.CurContext;
  744. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  745. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  746. VarDecl *Decl =
  747. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  748. if (Attrs) {
  749. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  750. I != E; ++I)
  751. Decl->addAttr(*I);
  752. }
  753. Decl->setImplicit();
  754. return Decl;
  755. }
  756. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  757. SourceLocation Loc,
  758. bool RefersToCapture = false) {
  759. D->setReferenced();
  760. D->markUsed(S.Context);
  761. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  762. SourceLocation(), D, RefersToCapture, Loc, Ty,
  763. VK_LValue);
  764. }
  765. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  766. BinaryOperatorKind BOK) {
  767. D = getCanonicalDecl(D);
  768. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  769. assert(
  770. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  771. "Additional reduction info may be specified only for reduction items.");
  772. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  773. assert(ReductionData.ReductionRange.isInvalid() &&
  774. Stack.back().first.back().Directive == OMPD_taskgroup &&
  775. "Additional reduction info may be specified only once for reduction "
  776. "items.");
  777. ReductionData.set(BOK, SR);
  778. Expr *&TaskgroupReductionRef =
  779. Stack.back().first.back().TaskgroupReductionRef;
  780. if (!TaskgroupReductionRef) {
  781. auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
  782. SemaRef.Context.VoidPtrTy, ".task_red.");
  783. TaskgroupReductionRef =
  784. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  785. }
  786. }
  787. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  788. const Expr *ReductionRef) {
  789. D = getCanonicalDecl(D);
  790. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  791. assert(
  792. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  793. "Additional reduction info may be specified only for reduction items.");
  794. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  795. assert(ReductionData.ReductionRange.isInvalid() &&
  796. Stack.back().first.back().Directive == OMPD_taskgroup &&
  797. "Additional reduction info may be specified only once for reduction "
  798. "items.");
  799. ReductionData.set(ReductionRef, SR);
  800. Expr *&TaskgroupReductionRef =
  801. Stack.back().first.back().TaskgroupReductionRef;
  802. if (!TaskgroupReductionRef) {
  803. auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
  804. ".task_red.");
  805. TaskgroupReductionRef =
  806. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  807. }
  808. }
  809. DSAStackTy::DSAVarData
  810. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  811. BinaryOperatorKind &BOK,
  812. Expr *&TaskgroupDescriptor) {
  813. D = getCanonicalDecl(D);
  814. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  815. if (Stack.back().first.empty())
  816. return DSAVarData();
  817. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  818. E = Stack.back().first.rend();
  819. I != E; std::advance(I, 1)) {
  820. auto &Data = I->SharingMap[D];
  821. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  822. continue;
  823. auto &ReductionData = I->ReductionMap[D];
  824. if (!ReductionData.ReductionOp ||
  825. ReductionData.ReductionOp.is<const Expr *>())
  826. return DSAVarData();
  827. SR = ReductionData.ReductionRange;
  828. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  829. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  830. "expression for the descriptor is not "
  831. "set.");
  832. TaskgroupDescriptor = I->TaskgroupReductionRef;
  833. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  834. Data.PrivateCopy, I->DefaultAttrLoc);
  835. }
  836. return DSAVarData();
  837. }
  838. DSAStackTy::DSAVarData
  839. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  840. const Expr *&ReductionRef,
  841. Expr *&TaskgroupDescriptor) {
  842. D = getCanonicalDecl(D);
  843. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  844. if (Stack.back().first.empty())
  845. return DSAVarData();
  846. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  847. E = Stack.back().first.rend();
  848. I != E; std::advance(I, 1)) {
  849. auto &Data = I->SharingMap[D];
  850. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  851. continue;
  852. auto &ReductionData = I->ReductionMap[D];
  853. if (!ReductionData.ReductionOp ||
  854. !ReductionData.ReductionOp.is<const Expr *>())
  855. return DSAVarData();
  856. SR = ReductionData.ReductionRange;
  857. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  858. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  859. "expression for the descriptor is not "
  860. "set.");
  861. TaskgroupDescriptor = I->TaskgroupReductionRef;
  862. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  863. Data.PrivateCopy, I->DefaultAttrLoc);
  864. }
  865. return DSAVarData();
  866. }
  867. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  868. D = D->getCanonicalDecl();
  869. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  870. reverse_iterator I = Iter, E = Stack.back().first.rend();
  871. Scope *TopScope = nullptr;
  872. while (I != E && !isParallelOrTaskRegion(I->Directive))
  873. ++I;
  874. if (I == E)
  875. return false;
  876. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  877. Scope *CurScope = getCurScope();
  878. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  879. CurScope = CurScope->getParent();
  880. return CurScope != TopScope;
  881. }
  882. return false;
  883. }
  884. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
  885. D = getCanonicalDecl(D);
  886. DSAVarData DVar;
  887. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  888. // in a Construct, C/C++, predetermined, p.1]
  889. // Variables appearing in threadprivate directives are threadprivate.
  890. auto *VD = dyn_cast<VarDecl>(D);
  891. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  892. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  893. SemaRef.getLangOpts().OpenMPUseTLS &&
  894. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  895. (VD && VD->getStorageClass() == SC_Register &&
  896. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  897. addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  898. D->getLocation()),
  899. OMPC_threadprivate);
  900. }
  901. auto TI = Threadprivates.find(D);
  902. if (TI != Threadprivates.end()) {
  903. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  904. DVar.CKind = OMPC_threadprivate;
  905. return DVar;
  906. } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  907. DVar.RefExpr = buildDeclRefExpr(
  908. SemaRef, VD, D->getType().getNonReferenceType(),
  909. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  910. DVar.CKind = OMPC_threadprivate;
  911. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  912. }
  913. if (isStackEmpty())
  914. // Not in OpenMP execution region and top scope was already checked.
  915. return DVar;
  916. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  917. // in a Construct, C/C++, predetermined, p.4]
  918. // Static data members are shared.
  919. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  920. // in a Construct, C/C++, predetermined, p.7]
  921. // Variables with static storage duration that are declared in a scope
  922. // inside the construct are shared.
  923. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
  924. if (VD && VD->isStaticDataMember()) {
  925. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  926. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  927. return DVar;
  928. DVar.CKind = OMPC_shared;
  929. return DVar;
  930. }
  931. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  932. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  933. Type = SemaRef.getASTContext().getBaseElementType(Type);
  934. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  935. // in a Construct, C/C++, predetermined, p.6]
  936. // Variables with const qualified type having no mutable member are
  937. // shared.
  938. CXXRecordDecl *RD =
  939. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  940. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  941. if (auto *CTD = CTSD->getSpecializedTemplate())
  942. RD = CTD->getTemplatedDecl();
  943. if (IsConstant &&
  944. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  945. RD->hasMutableFields())) {
  946. // Variables with const-qualified type having no mutable member may be
  947. // listed in a firstprivate clause, even if they are static data members.
  948. DSAVarData DVarTemp = hasDSA(
  949. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
  950. MatchesAlways, FromParent);
  951. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  952. return DVar;
  953. DVar.CKind = OMPC_shared;
  954. return DVar;
  955. }
  956. // Explicitly specified attributes and local variables with predetermined
  957. // attributes.
  958. auto I = Stack.back().first.rbegin();
  959. auto EndI = Stack.back().first.rend();
  960. if (FromParent && I != EndI)
  961. std::advance(I, 1);
  962. if (I->SharingMap.count(D)) {
  963. DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
  964. DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
  965. DVar.CKind = I->SharingMap[D].Attributes;
  966. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  967. DVar.DKind = I->Directive;
  968. }
  969. return DVar;
  970. }
  971. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  972. bool FromParent) {
  973. if (isStackEmpty()) {
  974. StackTy::reverse_iterator I;
  975. return getDSA(I, D);
  976. }
  977. D = getCanonicalDecl(D);
  978. auto StartI = Stack.back().first.rbegin();
  979. auto EndI = Stack.back().first.rend();
  980. if (FromParent && StartI != EndI)
  981. std::advance(StartI, 1);
  982. return getDSA(StartI, D);
  983. }
  984. DSAStackTy::DSAVarData
  985. DSAStackTy::hasDSA(ValueDecl *D,
  986. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  987. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  988. bool FromParent) {
  989. if (isStackEmpty())
  990. return {};
  991. D = getCanonicalDecl(D);
  992. auto I = Stack.back().first.rbegin();
  993. auto EndI = Stack.back().first.rend();
  994. if (FromParent && I != EndI)
  995. std::advance(I, 1);
  996. for (; I != EndI; std::advance(I, 1)) {
  997. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  998. continue;
  999. auto NewI = I;
  1000. DSAVarData DVar = getDSA(NewI, D);
  1001. if (I == NewI && CPred(DVar.CKind))
  1002. return DVar;
  1003. }
  1004. return {};
  1005. }
  1006. DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1007. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1008. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1009. bool FromParent) {
  1010. if (isStackEmpty())
  1011. return {};
  1012. D = getCanonicalDecl(D);
  1013. auto StartI = Stack.back().first.rbegin();
  1014. auto EndI = Stack.back().first.rend();
  1015. if (FromParent && StartI != EndI)
  1016. std::advance(StartI, 1);
  1017. if (StartI == EndI || !DPred(StartI->Directive))
  1018. return {};
  1019. auto NewI = StartI;
  1020. DSAVarData DVar = getDSA(NewI, D);
  1021. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1022. }
  1023. bool DSAStackTy::hasExplicitDSA(
  1024. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1025. unsigned Level, bool NotLastprivate) {
  1026. if (isStackEmpty())
  1027. return false;
  1028. D = getCanonicalDecl(D);
  1029. auto StartI = Stack.back().first.begin();
  1030. auto EndI = Stack.back().first.end();
  1031. if (std::distance(StartI, EndI) <= (int)Level)
  1032. return false;
  1033. std::advance(StartI, Level);
  1034. return (StartI->SharingMap.count(D) > 0) &&
  1035. StartI->SharingMap[D].RefExpr.getPointer() &&
  1036. CPred(StartI->SharingMap[D].Attributes) &&
  1037. (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
  1038. }
  1039. bool DSAStackTy::hasExplicitDirective(
  1040. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1041. unsigned Level) {
  1042. if (isStackEmpty())
  1043. return false;
  1044. auto StartI = Stack.back().first.begin();
  1045. auto EndI = Stack.back().first.end();
  1046. if (std::distance(StartI, EndI) <= (int)Level)
  1047. return false;
  1048. std::advance(StartI, Level);
  1049. return DPred(StartI->Directive);
  1050. }
  1051. bool DSAStackTy::hasDirective(
  1052. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1053. const DeclarationNameInfo &, SourceLocation)>
  1054. &DPred,
  1055. bool FromParent) {
  1056. // We look only in the enclosing region.
  1057. if (isStackEmpty())
  1058. return false;
  1059. auto StartI = std::next(Stack.back().first.rbegin());
  1060. auto EndI = Stack.back().first.rend();
  1061. if (FromParent && StartI != EndI)
  1062. StartI = std::next(StartI);
  1063. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1064. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1065. return true;
  1066. }
  1067. return false;
  1068. }
  1069. void Sema::InitDataSharingAttributesStack() {
  1070. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1071. }
  1072. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1073. void Sema::pushOpenMPFunctionRegion() {
  1074. DSAStack->pushFunction();
  1075. }
  1076. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1077. DSAStack->popFunction(OldFSI);
  1078. }
  1079. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
  1080. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1081. auto &Ctx = getASTContext();
  1082. bool IsByRef = true;
  1083. // Find the directive that is associated with the provided scope.
  1084. D = cast<ValueDecl>(D->getCanonicalDecl());
  1085. auto Ty = D->getType();
  1086. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1087. // This table summarizes how a given variable should be passed to the device
  1088. // given its type and the clauses where it appears. This table is based on
  1089. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1090. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1091. //
  1092. // =========================================================================
  1093. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1094. // | |(tofrom:scalar)| | pvt | | | |
  1095. // =========================================================================
  1096. // | scl | | | | - | | bycopy|
  1097. // | scl | | - | x | - | - | bycopy|
  1098. // | scl | | x | - | - | - | null |
  1099. // | scl | x | | | - | | byref |
  1100. // | scl | x | - | x | - | - | bycopy|
  1101. // | scl | x | x | - | - | - | null |
  1102. // | scl | | - | - | - | x | byref |
  1103. // | scl | x | - | - | - | x | byref |
  1104. //
  1105. // | agg | n.a. | | | - | | byref |
  1106. // | agg | n.a. | - | x | - | - | byref |
  1107. // | agg | n.a. | x | - | - | - | null |
  1108. // | agg | n.a. | - | - | - | x | byref |
  1109. // | agg | n.a. | - | - | - | x[] | byref |
  1110. //
  1111. // | ptr | n.a. | | | - | | bycopy|
  1112. // | ptr | n.a. | - | x | - | - | bycopy|
  1113. // | ptr | n.a. | x | - | - | - | null |
  1114. // | ptr | n.a. | - | - | - | x | byref |
  1115. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1116. // | ptr | n.a. | - | - | x | | bycopy|
  1117. // | ptr | n.a. | - | - | x | x | bycopy|
  1118. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1119. // =========================================================================
  1120. // Legend:
  1121. // scl - scalar
  1122. // ptr - pointer
  1123. // agg - aggregate
  1124. // x - applies
  1125. // - - invalid in this combination
  1126. // [] - mapped with an array section
  1127. // byref - should be mapped by reference
  1128. // byval - should be mapped by value
  1129. // null - initialize a local variable to null on the device
  1130. //
  1131. // Observations:
  1132. // - All scalar declarations that show up in a map clause have to be passed
  1133. // by reference, because they may have been mapped in the enclosing data
  1134. // environment.
  1135. // - If the scalar value does not fit the size of uintptr, it has to be
  1136. // passed by reference, regardless the result in the table above.
  1137. // - For pointers mapped by value that have either an implicit map or an
  1138. // array section, the runtime library may pass the NULL value to the
  1139. // device instead of the value passed to it by the compiler.
  1140. if (Ty->isReferenceType())
  1141. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1142. // Locate map clauses and see if the variable being captured is referred to
  1143. // in any of those clauses. Here we only care about variables, not fields,
  1144. // because fields are part of aggregates.
  1145. bool IsVariableUsedInMapClause = false;
  1146. bool IsVariableAssociatedWithSection = false;
  1147. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1148. D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1149. MapExprComponents,
  1150. OpenMPClauseKind WhereFoundClauseKind) {
  1151. // Only the map clause information influences how a variable is
  1152. // captured. E.g. is_device_ptr does not require changing the default
  1153. // behavior.
  1154. if (WhereFoundClauseKind != OMPC_map)
  1155. return false;
  1156. auto EI = MapExprComponents.rbegin();
  1157. auto EE = MapExprComponents.rend();
  1158. assert(EI != EE && "Invalid map expression!");
  1159. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1160. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1161. ++EI;
  1162. if (EI == EE)
  1163. return false;
  1164. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1165. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1166. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1167. IsVariableAssociatedWithSection = true;
  1168. // There is nothing more we need to know about this variable.
  1169. return true;
  1170. }
  1171. // Keep looking for more map info.
  1172. return false;
  1173. });
  1174. if (IsVariableUsedInMapClause) {
  1175. // If variable is identified in a map clause it is always captured by
  1176. // reference except if it is a pointer that is dereferenced somehow.
  1177. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1178. } else {
  1179. // By default, all the data that has a scalar type is mapped by copy
  1180. // (except for reduction variables).
  1181. IsByRef =
  1182. !Ty->isScalarType() ||
  1183. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1184. DSAStack->hasExplicitDSA(
  1185. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1186. }
  1187. }
  1188. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1189. IsByRef = !DSAStack->hasExplicitDSA(
  1190. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1191. Level, /*NotLastprivate=*/true);
  1192. }
  1193. // When passing data by copy, we need to make sure it fits the uintptr size
  1194. // and alignment, because the runtime library only deals with uintptr types.
  1195. // If it does not fit the uintptr size, we need to pass the data by reference
  1196. // instead.
  1197. if (!IsByRef &&
  1198. (Ctx.getTypeSizeInChars(Ty) >
  1199. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1200. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1201. IsByRef = true;
  1202. }
  1203. return IsByRef;
  1204. }
  1205. unsigned Sema::getOpenMPNestingLevel() const {
  1206. assert(getLangOpts().OpenMP);
  1207. return DSAStack->getNestingLevel();
  1208. }
  1209. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1210. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1211. !DSAStack->isClauseParsingMode()) ||
  1212. DSAStack->hasDirective(
  1213. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1214. SourceLocation) -> bool {
  1215. return isOpenMPTargetExecutionDirective(K);
  1216. },
  1217. false);
  1218. }
  1219. VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  1220. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1221. D = getCanonicalDecl(D);
  1222. // If we are attempting to capture a global variable in a directive with
  1223. // 'target' we return true so that this global is also mapped to the device.
  1224. //
  1225. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  1226. // then it should not be captured. Therefore, an extra check has to be
  1227. // inserted here once support for 'declare target' is added.
  1228. //
  1229. auto *VD = dyn_cast<VarDecl>(D);
  1230. if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
  1231. return VD;
  1232. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1233. (!DSAStack->isClauseParsingMode() ||
  1234. DSAStack->getParentDirective() != OMPD_unknown)) {
  1235. auto &&Info = DSAStack->isLoopControlVariable(D);
  1236. if (Info.first ||
  1237. (VD && VD->hasLocalStorage() &&
  1238. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1239. (VD && DSAStack->isForceVarCapturing()))
  1240. return VD ? VD : Info.second;
  1241. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1242. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1243. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1244. DVarPrivate = DSAStack->hasDSA(
  1245. D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  1246. DSAStack->isClauseParsingMode());
  1247. if (DVarPrivate.CKind != OMPC_unknown)
  1248. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1249. }
  1250. return nullptr;
  1251. }
  1252. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1253. unsigned Level) const {
  1254. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1255. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1256. FunctionScopesIndex -= Regions.size();
  1257. }
  1258. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  1259. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1260. return DSAStack->hasExplicitDSA(
  1261. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
  1262. Level) ||
  1263. (DSAStack->isClauseParsingMode() &&
  1264. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1265. // Consider taskgroup reduction descriptor variable a private to avoid
  1266. // possible capture in the region.
  1267. (DSAStack->hasExplicitDirective(
  1268. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1269. Level) &&
  1270. DSAStack->isTaskgroupReductionRef(D, Level));
  1271. }
  1272. void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
  1273. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1274. D = getCanonicalDecl(D);
  1275. OpenMPClauseKind OMPC = OMPC_unknown;
  1276. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1277. const unsigned NewLevel = I - 1;
  1278. if (DSAStack->hasExplicitDSA(D,
  1279. [&OMPC](const OpenMPClauseKind K) {
  1280. if (isOpenMPPrivate(K)) {
  1281. OMPC = K;
  1282. return true;
  1283. }
  1284. return false;
  1285. },
  1286. NewLevel))
  1287. break;
  1288. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1289. D, NewLevel,
  1290. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1291. OpenMPClauseKind) { return true; })) {
  1292. OMPC = OMPC_map;
  1293. break;
  1294. }
  1295. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1296. NewLevel)) {
  1297. OMPC = OMPC_firstprivate;
  1298. break;
  1299. }
  1300. }
  1301. if (OMPC != OMPC_unknown)
  1302. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1303. }
  1304. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  1305. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1306. // Return true if the current level is no longer enclosed in a target region.
  1307. auto *VD = dyn_cast<VarDecl>(D);
  1308. return VD && !VD->hasLocalStorage() &&
  1309. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1310. Level);
  1311. }
  1312. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1313. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1314. const DeclarationNameInfo &DirName,
  1315. Scope *CurScope, SourceLocation Loc) {
  1316. DSAStack->push(DKind, DirName, CurScope, Loc);
  1317. PushExpressionEvaluationContext(
  1318. ExpressionEvaluationContext::PotentiallyEvaluated);
  1319. }
  1320. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1321. DSAStack->setClauseParsingMode(K);
  1322. }
  1323. void Sema::EndOpenMPClause() {
  1324. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1325. }
  1326. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1327. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1328. // A variable of class type (or array thereof) that appears in a lastprivate
  1329. // clause requires an accessible, unambiguous default constructor for the
  1330. // class type, unless the list item is also specified in a firstprivate
  1331. // clause.
  1332. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1333. for (auto *C : D->clauses()) {
  1334. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1335. SmallVector<Expr *, 8> PrivateCopies;
  1336. for (auto *DE : Clause->varlists()) {
  1337. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1338. PrivateCopies.push_back(nullptr);
  1339. continue;
  1340. }
  1341. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1342. VarDecl *VD = cast<VarDecl>(DRE->getDecl());
  1343. QualType Type = VD->getType().getNonReferenceType();
  1344. auto DVar = DSAStack->getTopDSA(VD, false);
  1345. if (DVar.CKind == OMPC_lastprivate) {
  1346. // Generate helper private variable and initialize it with the
  1347. // default value. The address of the original variable is replaced
  1348. // by the address of the new private variable in CodeGen. This new
  1349. // variable is not added to IdResolver, so the code in the OpenMP
  1350. // region uses original variable for proper diagnostics.
  1351. auto *VDPrivate = buildVarDecl(
  1352. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1353. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  1354. ActOnUninitializedDecl(VDPrivate);
  1355. if (VDPrivate->isInvalidDecl())
  1356. continue;
  1357. PrivateCopies.push_back(buildDeclRefExpr(
  1358. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1359. } else {
  1360. // The variable is also a firstprivate, so initialization sequence
  1361. // for private copy is generated already.
  1362. PrivateCopies.push_back(nullptr);
  1363. }
  1364. }
  1365. // Set initializers to private copies if no errors were found.
  1366. if (PrivateCopies.size() == Clause->varlist_size())
  1367. Clause->setPrivateCopies(PrivateCopies);
  1368. }
  1369. }
  1370. }
  1371. DSAStack->pop();
  1372. DiscardCleanupsInEvaluationContext();
  1373. PopExpressionEvaluationContext();
  1374. }
  1375. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1376. Expr *NumIterations, Sema &SemaRef,
  1377. Scope *S, DSAStackTy *Stack);
  1378. namespace {
  1379. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1380. private:
  1381. Sema &SemaRef;
  1382. public:
  1383. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1384. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1385. NamedDecl *ND = Candidate.getCorrectionDecl();
  1386. if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1387. return VD->hasGlobalStorage() &&
  1388. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1389. SemaRef.getCurScope());
  1390. }
  1391. return false;
  1392. }
  1393. };
  1394. class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
  1395. private:
  1396. Sema &SemaRef;
  1397. public:
  1398. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1399. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1400. NamedDecl *ND = Candidate.getCorrectionDecl();
  1401. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1402. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1403. SemaRef.getCurScope());
  1404. }
  1405. return false;
  1406. }
  1407. };
  1408. } // namespace
  1409. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1410. CXXScopeSpec &ScopeSpec,
  1411. const DeclarationNameInfo &Id) {
  1412. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1413. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1414. if (Lookup.isAmbiguous())
  1415. return ExprError();
  1416. VarDecl *VD;
  1417. if (!Lookup.isSingleResult()) {
  1418. if (TypoCorrection Corrected = CorrectTypo(
  1419. Id, LookupOrdinaryName, CurScope, nullptr,
  1420. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1421. diagnoseTypo(Corrected,
  1422. PDiag(Lookup.empty()
  1423. ? diag::err_undeclared_var_use_suggest
  1424. : diag::err_omp_expected_var_arg_suggest)
  1425. << Id.getName());
  1426. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1427. } else {
  1428. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1429. : diag::err_omp_expected_var_arg)
  1430. << Id.getName();
  1431. return ExprError();
  1432. }
  1433. } else {
  1434. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1435. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1436. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1437. return ExprError();
  1438. }
  1439. }
  1440. Lookup.suppressDiagnostics();
  1441. // OpenMP [2.9.2, Syntax, C/C++]
  1442. // Variables must be file-scope, namespace-scope, or static block-scope.
  1443. if (!VD->hasGlobalStorage()) {
  1444. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1445. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1446. bool IsDecl =
  1447. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1448. Diag(VD->getLocation(),
  1449. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1450. << VD;
  1451. return ExprError();
  1452. }
  1453. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1454. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1455. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1456. // A threadprivate directive for file-scope variables must appear outside
  1457. // any definition or declaration.
  1458. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1459. !getCurLexicalContext()->isTranslationUnit()) {
  1460. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1461. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1462. bool IsDecl =
  1463. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1464. Diag(VD->getLocation(),
  1465. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1466. << VD;
  1467. return ExprError();
  1468. }
  1469. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1470. // A threadprivate directive for static class member variables must appear
  1471. // in the class definition, in the same scope in which the member
  1472. // variables are declared.
  1473. if (CanonicalVD->isStaticDataMember() &&
  1474. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1475. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1476. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1477. bool IsDecl =
  1478. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1479. Diag(VD->getLocation(),
  1480. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1481. << VD;
  1482. return ExprError();
  1483. }
  1484. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1485. // A threadprivate directive for namespace-scope variables must appear
  1486. // outside any definition or declaration other than the namespace
  1487. // definition itself.
  1488. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1489. (!getCurLexicalContext()->isFileContext() ||
  1490. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1491. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1492. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1493. bool IsDecl =
  1494. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1495. Diag(VD->getLocation(),
  1496. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1497. << VD;
  1498. return ExprError();
  1499. }
  1500. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1501. // A threadprivate directive for static block-scope variables must appear
  1502. // in the scope of the variable and not in a nested scope.
  1503. if (CanonicalVD->isStaticLocal() && CurScope &&
  1504. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1505. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1506. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1507. bool IsDecl =
  1508. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1509. Diag(VD->getLocation(),
  1510. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1511. << VD;
  1512. return ExprError();
  1513. }
  1514. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1515. // A threadprivate directive must lexically precede all references to any
  1516. // of the variables in its list.
  1517. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1518. Diag(Id.getLoc(), diag::err_omp_var_used)
  1519. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1520. return ExprError();
  1521. }
  1522. QualType ExprType = VD->getType().getNonReferenceType();
  1523. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1524. SourceLocation(), VD,
  1525. /*RefersToEnclosingVariableOrCapture=*/false,
  1526. Id.getLoc(), ExprType, VK_LValue);
  1527. }
  1528. Sema::DeclGroupPtrTy
  1529. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1530. ArrayRef<Expr *> VarList) {
  1531. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1532. CurContext->addDecl(D);
  1533. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1534. }
  1535. return nullptr;
  1536. }
  1537. namespace {
  1538. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1539. Sema &SemaRef;
  1540. public:
  1541. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1542. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1543. if (VD->hasLocalStorage()) {
  1544. SemaRef.Diag(E->getLocStart(),
  1545. diag::err_omp_local_var_in_threadprivate_init)
  1546. << E->getSourceRange();
  1547. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1548. << VD << VD->getSourceRange();
  1549. return true;
  1550. }
  1551. }
  1552. return false;
  1553. }
  1554. bool VisitStmt(const Stmt *S) {
  1555. for (auto Child : S->children()) {
  1556. if (Child && Visit(Child))
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1562. };
  1563. } // namespace
  1564. OMPThreadPrivateDecl *
  1565. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1566. SmallVector<Expr *, 8> Vars;
  1567. for (auto &RefExpr : VarList) {
  1568. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1569. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1570. SourceLocation ILoc = DE->getExprLoc();
  1571. // Mark variable as used.
  1572. VD->setReferenced();
  1573. VD->markUsed(Context);
  1574. QualType QType = VD->getType();
  1575. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1576. // It will be analyzed later.
  1577. Vars.push_back(DE);
  1578. continue;
  1579. }
  1580. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1581. // A threadprivate variable must not have an incomplete type.
  1582. if (RequireCompleteType(ILoc, VD->getType(),
  1583. diag::err_omp_threadprivate_incomplete_type)) {
  1584. continue;
  1585. }
  1586. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1587. // A threadprivate variable must not have a reference type.
  1588. if (VD->getType()->isReferenceType()) {
  1589. Diag(ILoc, diag::err_omp_ref_type_arg)
  1590. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1591. bool IsDecl =
  1592. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1593. Diag(VD->getLocation(),
  1594. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1595. << VD;
  1596. continue;
  1597. }
  1598. // Check if this is a TLS variable. If TLS is not being supported, produce
  1599. // the corresponding diagnostic.
  1600. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1601. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1602. getLangOpts().OpenMPUseTLS &&
  1603. getASTContext().getTargetInfo().isTLSSupported())) ||
  1604. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1605. !VD->isLocalVarDecl())) {
  1606. Diag(ILoc, diag::err_omp_var_thread_local)
  1607. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1608. bool IsDecl =
  1609. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1610. Diag(VD->getLocation(),
  1611. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1612. << VD;
  1613. continue;
  1614. }
  1615. // Check if initial value of threadprivate variable reference variable with
  1616. // local storage (it is not supported by runtime).
  1617. if (auto Init = VD->getAnyInitializer()) {
  1618. LocalVarRefChecker Checker(*this);
  1619. if (Checker.Visit(Init))
  1620. continue;
  1621. }
  1622. Vars.push_back(RefExpr);
  1623. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1624. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1625. Context, SourceRange(Loc, Loc)));
  1626. if (auto *ML = Context.getASTMutationListener())
  1627. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1628. }
  1629. OMPThreadPrivateDecl *D = nullptr;
  1630. if (!Vars.empty()) {
  1631. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1632. Vars);
  1633. D->setAccess(AS_public);
  1634. }
  1635. return D;
  1636. }
  1637. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1638. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1639. bool IsLoopIterVar = false) {
  1640. if (DVar.RefExpr) {
  1641. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1642. << getOpenMPClauseName(DVar.CKind);
  1643. return;
  1644. }
  1645. enum {
  1646. PDSA_StaticMemberShared,
  1647. PDSA_StaticLocalVarShared,
  1648. PDSA_LoopIterVarPrivate,
  1649. PDSA_LoopIterVarLinear,
  1650. PDSA_LoopIterVarLastprivate,
  1651. PDSA_ConstVarShared,
  1652. PDSA_GlobalVarShared,
  1653. PDSA_TaskVarFirstprivate,
  1654. PDSA_LocalVarPrivate,
  1655. PDSA_Implicit
  1656. } Reason = PDSA_Implicit;
  1657. bool ReportHint = false;
  1658. auto ReportLoc = D->getLocation();
  1659. auto *VD = dyn_cast<VarDecl>(D);
  1660. if (IsLoopIterVar) {
  1661. if (DVar.CKind == OMPC_private)
  1662. Reason = PDSA_LoopIterVarPrivate;
  1663. else if (DVar.CKind == OMPC_lastprivate)
  1664. Reason = PDSA_LoopIterVarLastprivate;
  1665. else
  1666. Reason = PDSA_LoopIterVarLinear;
  1667. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1668. DVar.CKind == OMPC_firstprivate) {
  1669. Reason = PDSA_TaskVarFirstprivate;
  1670. ReportLoc = DVar.ImplicitDSALoc;
  1671. } else if (VD && VD->isStaticLocal())
  1672. Reason = PDSA_StaticLocalVarShared;
  1673. else if (VD && VD->isStaticDataMember())
  1674. Reason = PDSA_StaticMemberShared;
  1675. else if (VD && VD->isFileVarDecl())
  1676. Reason = PDSA_GlobalVarShared;
  1677. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1678. Reason = PDSA_ConstVarShared;
  1679. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1680. ReportHint = true;
  1681. Reason = PDSA_LocalVarPrivate;
  1682. }
  1683. if (Reason != PDSA_Implicit) {
  1684. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1685. << Reason << ReportHint
  1686. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1687. } else if (DVar.ImplicitDSALoc.isValid()) {
  1688. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1689. << getOpenMPClauseName(DVar.CKind);
  1690. }
  1691. }
  1692. namespace {
  1693. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1694. DSAStackTy *Stack;
  1695. Sema &SemaRef;
  1696. bool ErrorFound;
  1697. CapturedStmt *CS;
  1698. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1699. llvm::SmallVector<Expr *, 8> ImplicitMap;
  1700. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1701. llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
  1702. public:
  1703. void VisitDeclRefExpr(DeclRefExpr *E) {
  1704. if (E->isTypeDependent() || E->isValueDependent() ||
  1705. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1706. return;
  1707. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1708. VD = VD->getCanonicalDecl();
  1709. // Skip internally declared variables.
  1710. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1711. return;
  1712. auto DVar = Stack->getTopDSA(VD, false);
  1713. // Check if the variable has explicit DSA set and stop analysis if it so.
  1714. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1715. return;
  1716. // Skip internally declared static variables.
  1717. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
  1718. return;
  1719. auto ELoc = E->getExprLoc();
  1720. auto DKind = Stack->getCurrentDirective();
  1721. // The default(none) clause requires that each variable that is referenced
  1722. // in the construct, and does not have a predetermined data-sharing
  1723. // attribute, must have its data-sharing attribute explicitly determined
  1724. // by being listed in a data-sharing attribute clause.
  1725. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1726. isParallelOrTaskRegion(DKind) &&
  1727. VarsWithInheritedDSA.count(VD) == 0) {
  1728. VarsWithInheritedDSA[VD] = E;
  1729. return;
  1730. }
  1731. if (isOpenMPTargetExecutionDirective(DKind) &&
  1732. !Stack->isLoopControlVariable(VD).first) {
  1733. if (!Stack->checkMappableExprComponentListsForDecl(
  1734. VD, /*CurrentRegionOnly=*/true,
  1735. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1736. StackComponents,
  1737. OpenMPClauseKind) {
  1738. // Variable is used if it has been marked as an array, array
  1739. // section or the variable iself.
  1740. return StackComponents.size() == 1 ||
  1741. std::all_of(
  1742. std::next(StackComponents.rbegin()),
  1743. StackComponents.rend(),
  1744. [](const OMPClauseMappableExprCommon::
  1745. MappableComponent &MC) {
  1746. return MC.getAssociatedDeclaration() ==
  1747. nullptr &&
  1748. (isa<OMPArraySectionExpr>(
  1749. MC.getAssociatedExpression()) ||
  1750. isa<ArraySubscriptExpr>(
  1751. MC.getAssociatedExpression()));
  1752. });
  1753. })) {
  1754. bool IsFirstprivate = false;
  1755. // By default lambdas are captured as firstprivates.
  1756. if (const auto *RD =
  1757. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  1758. IsFirstprivate = RD->isLambda();
  1759. IsFirstprivate =
  1760. IsFirstprivate ||
  1761. (VD->getType().getNonReferenceType()->isScalarType() &&
  1762. Stack->getDefaultDMA() != DMA_tofrom_scalar);
  1763. if (IsFirstprivate)
  1764. ImplicitFirstprivate.emplace_back(E);
  1765. else
  1766. ImplicitMap.emplace_back(E);
  1767. return;
  1768. }
  1769. }
  1770. // OpenMP [2.9.3.6, Restrictions, p.2]
  1771. // A list item that appears in a reduction clause of the innermost
  1772. // enclosing worksharing or parallel construct may not be accessed in an
  1773. // explicit task.
  1774. DVar = Stack->hasInnermostDSA(
  1775. VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1776. [](OpenMPDirectiveKind K) -> bool {
  1777. return isOpenMPParallelDirective(K) ||
  1778. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1779. },
  1780. /*FromParent=*/true);
  1781. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1782. ErrorFound = true;
  1783. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1784. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1785. return;
  1786. }
  1787. // Define implicit data-sharing attributes for task.
  1788. DVar = Stack->getImplicitDSA(VD, false);
  1789. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1790. !Stack->isLoopControlVariable(VD).first)
  1791. ImplicitFirstprivate.push_back(E);
  1792. }
  1793. }
  1794. void VisitMemberExpr(MemberExpr *E) {
  1795. if (E->isTypeDependent() || E->isValueDependent() ||
  1796. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1797. return;
  1798. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  1799. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1800. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1801. if (!FD)
  1802. return;
  1803. auto DVar = Stack->getTopDSA(FD, false);
  1804. // Check if the variable has explicit DSA set and stop analysis if it
  1805. // so.
  1806. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  1807. return;
  1808. if (isOpenMPTargetExecutionDirective(DKind) &&
  1809. !Stack->isLoopControlVariable(FD).first &&
  1810. !Stack->checkMappableExprComponentListsForDecl(
  1811. FD, /*CurrentRegionOnly=*/true,
  1812. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1813. StackComponents,
  1814. OpenMPClauseKind) {
  1815. return isa<CXXThisExpr>(
  1816. cast<MemberExpr>(
  1817. StackComponents.back().getAssociatedExpression())
  1818. ->getBase()
  1819. ->IgnoreParens());
  1820. })) {
  1821. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  1822. // A bit-field cannot appear in a map clause.
  1823. //
  1824. if (FD->isBitField())
  1825. return;
  1826. ImplicitMap.emplace_back(E);
  1827. return;
  1828. }
  1829. auto ELoc = E->getExprLoc();
  1830. // OpenMP [2.9.3.6, Restrictions, p.2]
  1831. // A list item that appears in a reduction clause of the innermost
  1832. // enclosing worksharing or parallel construct may not be accessed in
  1833. // an explicit task.
  1834. DVar = Stack->hasInnermostDSA(
  1835. FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1836. [](OpenMPDirectiveKind K) -> bool {
  1837. return isOpenMPParallelDirective(K) ||
  1838. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1839. },
  1840. /*FromParent=*/true);
  1841. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1842. ErrorFound = true;
  1843. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1844. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1845. return;
  1846. }
  1847. // Define implicit data-sharing attributes for task.
  1848. DVar = Stack->getImplicitDSA(FD, false);
  1849. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1850. !Stack->isLoopControlVariable(FD).first)
  1851. ImplicitFirstprivate.push_back(E);
  1852. return;
  1853. }
  1854. if (isOpenMPTargetExecutionDirective(DKind)) {
  1855. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  1856. if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  1857. /*NoDiagnose=*/true))
  1858. return;
  1859. auto *VD = cast<ValueDecl>(
  1860. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  1861. if (!Stack->checkMappableExprComponentListsForDecl(
  1862. VD, /*CurrentRegionOnly=*/true,
  1863. [&CurComponents](
  1864. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1865. StackComponents,
  1866. OpenMPClauseKind) {
  1867. auto CCI = CurComponents.rbegin();
  1868. auto CCE = CurComponents.rend();
  1869. for (const auto &SC : llvm::reverse(StackComponents)) {
  1870. // Do both expressions have the same kind?
  1871. if (CCI->getAssociatedExpression()->getStmtClass() !=
  1872. SC.getAssociatedExpression()->getStmtClass())
  1873. if (!(isa<OMPArraySectionExpr>(
  1874. SC.getAssociatedExpression()) &&
  1875. isa<ArraySubscriptExpr>(
  1876. CCI->getAssociatedExpression())))
  1877. return false;
  1878. Decl *CCD = CCI->getAssociatedDeclaration();
  1879. Decl *SCD = SC.getAssociatedDeclaration();
  1880. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  1881. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  1882. if (SCD != CCD)
  1883. return false;
  1884. std::advance(CCI, 1);
  1885. if (CCI == CCE)
  1886. break;
  1887. }
  1888. return true;
  1889. })) {
  1890. Visit(E->getBase());
  1891. }
  1892. } else
  1893. Visit(E->getBase());
  1894. }
  1895. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1896. for (auto *C : S->clauses()) {
  1897. // Skip analysis of arguments of implicitly defined firstprivate clause
  1898. // for task|target directives.
  1899. // Skip analysis of arguments of implicitly defined map clause for target
  1900. // directives.
  1901. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  1902. C->isImplicit())) {
  1903. for (auto *CC : C->children()) {
  1904. if (CC)
  1905. Visit(CC);
  1906. }
  1907. }
  1908. }
  1909. }
  1910. void VisitStmt(Stmt *S) {
  1911. for (auto *C : S->children()) {
  1912. if (C && !isa<OMPExecutableDirective>(C))
  1913. Visit(C);
  1914. }
  1915. }
  1916. bool isErrorFound() { return ErrorFound; }
  1917. ArrayRef<Expr *> getImplicitFirstprivate() const {
  1918. return ImplicitFirstprivate;
  1919. }
  1920. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  1921. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1922. return VarsWithInheritedDSA;
  1923. }
  1924. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1925. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1926. };
  1927. } // namespace
  1928. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1929. switch (DKind) {
  1930. case OMPD_parallel:
  1931. case OMPD_parallel_for:
  1932. case OMPD_parallel_for_simd:
  1933. case OMPD_parallel_sections:
  1934. case OMPD_teams:
  1935. case OMPD_teams_distribute:
  1936. case OMPD_teams_distribute_simd: {
  1937. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1938. QualType KmpInt32PtrTy =
  1939. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1940. Sema::CapturedParamNameType Params[] = {
  1941. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1942. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1943. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1944. };
  1945. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1946. Params);
  1947. break;
  1948. }
  1949. case OMPD_target_teams:
  1950. case OMPD_target_parallel:
  1951. case OMPD_target_parallel_for:
  1952. case OMPD_target_parallel_for_simd:
  1953. case OMPD_target_teams_distribute:
  1954. case OMPD_target_teams_distribute_simd: {
  1955. Sema::CapturedParamNameType ParamsTarget[] = {
  1956. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1957. };
  1958. // Start a captured region for 'target' with no implicit parameters.
  1959. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1960. ParamsTarget);
  1961. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1962. QualType KmpInt32PtrTy =
  1963. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1964. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  1965. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1966. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1967. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1968. };
  1969. // Start a captured region for 'teams' or 'parallel'. Both regions have
  1970. // the same implicit parameters.
  1971. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1972. ParamsTeamsOrParallel);
  1973. break;
  1974. }
  1975. case OMPD_simd:
  1976. case OMPD_for:
  1977. case OMPD_for_simd:
  1978. case OMPD_sections:
  1979. case OMPD_section:
  1980. case OMPD_single:
  1981. case OMPD_master:
  1982. case OMPD_critical:
  1983. case OMPD_taskgroup:
  1984. case OMPD_distribute:
  1985. case OMPD_distribute_simd:
  1986. case OMPD_ordered:
  1987. case OMPD_atomic:
  1988. case OMPD_target_data:
  1989. case OMPD_target:
  1990. case OMPD_target_simd: {
  1991. Sema::CapturedParamNameType Params[] = {
  1992. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1993. };
  1994. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1995. Params);
  1996. break;
  1997. }
  1998. case OMPD_task: {
  1999. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2000. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2001. FunctionProtoType::ExtProtoInfo EPI;
  2002. EPI.Variadic = true;
  2003. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2004. Sema::CapturedParamNameType Params[] = {
  2005. std::make_pair(".global_tid.", KmpInt32Ty),
  2006. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2007. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  2008. std::make_pair(".copy_fn.",
  2009. Context.getPointerType(CopyFnType).withConst()),
  2010. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2011. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2012. };
  2013. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2014. Params);
  2015. // Mark this captured region as inlined, because we don't use outlined
  2016. // function directly.
  2017. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2018. AlwaysInlineAttr::CreateImplicit(
  2019. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2020. break;
  2021. }
  2022. case OMPD_taskloop:
  2023. case OMPD_taskloop_simd: {
  2024. QualType KmpInt32Ty =
  2025. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2026. QualType KmpUInt64Ty =
  2027. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  2028. QualType KmpInt64Ty =
  2029. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  2030. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2031. FunctionProtoType::ExtProtoInfo EPI;
  2032. EPI.Variadic = true;
  2033. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2034. Sema::CapturedParamNameType Params[] = {
  2035. std::make_pair(".global_tid.", KmpInt32Ty),
  2036. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2037. std::make_pair(".privates.",
  2038. Context.VoidPtrTy.withConst().withRestrict()),
  2039. std::make_pair(
  2040. ".copy_fn.",
  2041. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2042. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2043. std::make_pair(".lb.", KmpUInt64Ty),
  2044. std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
  2045. std::make_pair(".liter.", KmpInt32Ty),
  2046. std::make_pair(".reductions.",
  2047. Context.VoidPtrTy.withConst().withRestrict()),
  2048. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2049. };
  2050. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2051. Params);
  2052. // Mark this captured region as inlined, because we don't use outlined
  2053. // function directly.
  2054. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2055. AlwaysInlineAttr::CreateImplicit(
  2056. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2057. break;
  2058. }
  2059. case OMPD_distribute_parallel_for_simd:
  2060. case OMPD_distribute_parallel_for:
  2061. case OMPD_target_teams_distribute_parallel_for:
  2062. case OMPD_target_teams_distribute_parallel_for_simd: {
  2063. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2064. QualType KmpInt32PtrTy =
  2065. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2066. Sema::CapturedParamNameType Params[] = {
  2067. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2068. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2069. std::make_pair(".previous.lb.", Context.getSizeType()),
  2070. std::make_pair(".previous.ub.", Context.getSizeType()),
  2071. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2072. };
  2073. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2074. Params);
  2075. break;
  2076. }
  2077. case OMPD_teams_distribute_parallel_for:
  2078. case OMPD_teams_distribute_parallel_for_simd: {
  2079. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2080. QualType KmpInt32PtrTy =
  2081. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2082. Sema::CapturedParamNameType ParamsTeams[] = {
  2083. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2084. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2085. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2086. };
  2087. // Start a captured region for 'target' with no implicit parameters.
  2088. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2089. ParamsTeams);
  2090. Sema::CapturedParamNameType ParamsParallel[] = {
  2091. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2092. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2093. std::make_pair(".previous.lb.", Context.getSizeType()),
  2094. std::make_pair(".previous.ub.", Context.getSizeType()),
  2095. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2096. };
  2097. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2098. // the same implicit parameters.
  2099. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2100. ParamsParallel);
  2101. break;
  2102. }
  2103. case OMPD_target_update:
  2104. case OMPD_target_enter_data:
  2105. case OMPD_target_exit_data: {
  2106. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2107. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2108. FunctionProtoType::ExtProtoInfo EPI;
  2109. EPI.Variadic = true;
  2110. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2111. Sema::CapturedParamNameType Params[] = {
  2112. std::make_pair(".global_tid.", KmpInt32Ty),
  2113. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2114. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  2115. std::make_pair(".copy_fn.",
  2116. Context.getPointerType(CopyFnType).withConst()),
  2117. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2118. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2119. };
  2120. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2121. Params);
  2122. // Mark this captured region as inlined, because we don't use outlined
  2123. // function directly.
  2124. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2125. AlwaysInlineAttr::CreateImplicit(
  2126. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2127. break;
  2128. }
  2129. case OMPD_threadprivate:
  2130. case OMPD_taskyield:
  2131. case OMPD_barrier:
  2132. case OMPD_taskwait:
  2133. case OMPD_cancellation_point:
  2134. case OMPD_cancel:
  2135. case OMPD_flush:
  2136. case OMPD_declare_reduction:
  2137. case OMPD_declare_simd:
  2138. case OMPD_declare_target:
  2139. case OMPD_end_declare_target:
  2140. llvm_unreachable("OpenMP Directive is not allowed");
  2141. case OMPD_unknown:
  2142. llvm_unreachable("Unknown OpenMP directive");
  2143. }
  2144. }
  2145. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2146. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2147. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2148. return CaptureRegions.size();
  2149. }
  2150. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2151. Expr *CaptureExpr, bool WithInit,
  2152. bool AsExpression) {
  2153. assert(CaptureExpr);
  2154. ASTContext &C = S.getASTContext();
  2155. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2156. QualType Ty = Init->getType();
  2157. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2158. if (S.getLangOpts().CPlusPlus)
  2159. Ty = C.getLValueReferenceType(Ty);
  2160. else {
  2161. Ty = C.getPointerType(Ty);
  2162. ExprResult Res =
  2163. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2164. if (!Res.isUsable())
  2165. return nullptr;
  2166. Init = Res.get();
  2167. }
  2168. WithInit = true;
  2169. }
  2170. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2171. CaptureExpr->getLocStart());
  2172. if (!WithInit)
  2173. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
  2174. S.CurContext->addHiddenDecl(CED);
  2175. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2176. return CED;
  2177. }
  2178. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2179. bool WithInit) {
  2180. OMPCapturedExprDecl *CD;
  2181. if (auto *VD = S.IsOpenMPCapturedDecl(D))
  2182. CD = cast<OMPCapturedExprDecl>(VD);
  2183. else
  2184. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2185. /*AsExpression=*/false);
  2186. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2187. CaptureExpr->getExprLoc());
  2188. }
  2189. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2190. if (!Ref) {
  2191. auto *CD =
  2192. buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
  2193. CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
  2194. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2195. CaptureExpr->getExprLoc());
  2196. }
  2197. ExprResult Res = Ref;
  2198. if (!S.getLangOpts().CPlusPlus &&
  2199. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2200. Ref->getType()->isPointerType())
  2201. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2202. if (!Res.isUsable())
  2203. return ExprError();
  2204. return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
  2205. }
  2206. namespace {
  2207. // OpenMP directives parsed in this section are represented as a
  2208. // CapturedStatement with an associated statement. If a syntax error
  2209. // is detected during the parsing of the associated statement, the
  2210. // compiler must abort processing and close the CapturedStatement.
  2211. //
  2212. // Combined directives such as 'target parallel' have more than one
  2213. // nested CapturedStatements. This RAII ensures that we unwind out
  2214. // of all the nested CapturedStatements when an error is found.
  2215. class CaptureRegionUnwinderRAII {
  2216. private:
  2217. Sema &S;
  2218. bool &ErrorFound;
  2219. OpenMPDirectiveKind DKind;
  2220. public:
  2221. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2222. OpenMPDirectiveKind DKind)
  2223. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2224. ~CaptureRegionUnwinderRAII() {
  2225. if (ErrorFound) {
  2226. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2227. while (--ThisCaptureLevel >= 0)
  2228. S.ActOnCapturedRegionError();
  2229. }
  2230. }
  2231. };
  2232. } // namespace
  2233. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2234. ArrayRef<OMPClause *> Clauses) {
  2235. bool ErrorFound = false;
  2236. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2237. *this, ErrorFound, DSAStack->getCurrentDirective());
  2238. if (!S.isUsable()) {
  2239. ErrorFound = true;
  2240. return StmtError();
  2241. }
  2242. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2243. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2244. OMPOrderedClause *OC = nullptr;
  2245. OMPScheduleClause *SC = nullptr;
  2246. SmallVector<OMPLinearClause *, 4> LCs;
  2247. SmallVector<OMPClauseWithPreInit *, 8> PICs;
  2248. // This is required for proper codegen.
  2249. for (auto *Clause : Clauses) {
  2250. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2251. Clause->getClauseKind() == OMPC_in_reduction) {
  2252. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2253. // with the corresponding in_reduction items.
  2254. auto *IRC = cast<OMPInReductionClause>(Clause);
  2255. for (auto *E : IRC->taskgroup_descriptors())
  2256. if (E)
  2257. MarkDeclarationsReferencedInExpr(E);
  2258. }
  2259. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2260. Clause->getClauseKind() == OMPC_copyprivate ||
  2261. (getLangOpts().OpenMPUseTLS &&
  2262. getASTContext().getTargetInfo().isTLSSupported() &&
  2263. Clause->getClauseKind() == OMPC_copyin)) {
  2264. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2265. // Mark all variables in private list clauses as used in inner region.
  2266. for (auto *VarRef : Clause->children()) {
  2267. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2268. MarkDeclarationsReferencedInExpr(E);
  2269. }
  2270. }
  2271. DSAStack->setForceVarCapturing(/*V=*/false);
  2272. } else if (CaptureRegions.size() > 1 ||
  2273. CaptureRegions.back() != OMPD_unknown) {
  2274. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2275. PICs.push_back(C);
  2276. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2277. if (auto *E = C->getPostUpdateExpr())
  2278. MarkDeclarationsReferencedInExpr(E);
  2279. }
  2280. }
  2281. if (Clause->getClauseKind() == OMPC_schedule)
  2282. SC = cast<OMPScheduleClause>(Clause);
  2283. else if (Clause->getClauseKind() == OMPC_ordered)
  2284. OC = cast<OMPOrderedClause>(Clause);
  2285. else if (Clause->getClauseKind() == OMPC_linear)
  2286. LCs.push_back(cast<OMPLinearClause>(Clause));
  2287. }
  2288. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2289. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2290. // specified.
  2291. if (SC &&
  2292. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2293. SC->getSecondScheduleModifier() ==
  2294. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2295. OC) {
  2296. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2297. ? SC->getFirstScheduleModifierLoc()
  2298. : SC->getSecondScheduleModifierLoc(),
  2299. diag::err_omp_schedule_nonmonotonic_ordered)
  2300. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2301. ErrorFound = true;
  2302. }
  2303. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2304. for (auto *C : LCs) {
  2305. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  2306. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2307. }
  2308. ErrorFound = true;
  2309. }
  2310. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2311. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2312. OC->getNumForLoops()) {
  2313. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  2314. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2315. ErrorFound = true;
  2316. }
  2317. if (ErrorFound) {
  2318. return StmtError();
  2319. }
  2320. StmtResult SR = S;
  2321. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2322. // Mark all variables in private list clauses as used in inner region.
  2323. // Required for proper codegen of combined directives.
  2324. // TODO: add processing for other clauses.
  2325. if (ThisCaptureRegion != OMPD_unknown) {
  2326. for (auto *C : PICs) {
  2327. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2328. // Find the particular capture region for the clause if the
  2329. // directive is a combined one with multiple capture regions.
  2330. // If the directive is not a combined one, the capture region
  2331. // associated with the clause is OMPD_unknown and is generated
  2332. // only once.
  2333. if (CaptureRegion == ThisCaptureRegion ||
  2334. CaptureRegion == OMPD_unknown) {
  2335. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2336. for (auto *D : DS->decls())
  2337. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2338. }
  2339. }
  2340. }
  2341. }
  2342. SR = ActOnCapturedRegionEnd(SR.get());
  2343. }
  2344. return SR;
  2345. }
  2346. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2347. OpenMPDirectiveKind CancelRegion,
  2348. SourceLocation StartLoc) {
  2349. // CancelRegion is only needed for cancel and cancellation_point.
  2350. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2351. return false;
  2352. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2353. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2354. return false;
  2355. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2356. << getOpenMPDirectiveName(CancelRegion);
  2357. return true;
  2358. }
  2359. static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  2360. OpenMPDirectiveKind CurrentRegion,
  2361. const DeclarationNameInfo &CurrentName,
  2362. OpenMPDirectiveKind CancelRegion,
  2363. SourceLocation StartLoc) {
  2364. if (Stack->getCurScope()) {
  2365. auto ParentRegion = Stack->getParentDirective();
  2366. auto OffendingRegion = ParentRegion;
  2367. bool NestingProhibited = false;
  2368. bool CloseNesting = true;
  2369. bool OrphanSeen = false;
  2370. enum {
  2371. NoRecommend,
  2372. ShouldBeInParallelRegion,
  2373. ShouldBeInOrderedRegion,
  2374. ShouldBeInTargetRegion,
  2375. ShouldBeInTeamsRegion
  2376. } Recommend = NoRecommend;
  2377. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2378. // OpenMP [2.16, Nesting of Regions]
  2379. // OpenMP constructs may not be nested inside a simd region.
  2380. // OpenMP [2.8.1,simd Construct, Restrictions]
  2381. // An ordered construct with the simd clause is the only OpenMP
  2382. // construct that can appear in the simd region.
  2383. // Allowing a SIMD construct nested in another SIMD construct is an
  2384. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2385. // message.
  2386. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2387. ? diag::err_omp_prohibited_region_simd
  2388. : diag::warn_omp_nesting_simd);
  2389. return CurrentRegion != OMPD_simd;
  2390. }
  2391. if (ParentRegion == OMPD_atomic) {
  2392. // OpenMP [2.16, Nesting of Regions]
  2393. // OpenMP constructs may not be nested inside an atomic region.
  2394. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2395. return true;
  2396. }
  2397. if (CurrentRegion == OMPD_section) {
  2398. // OpenMP [2.7.2, sections Construct, Restrictions]
  2399. // Orphaned section directives are prohibited. That is, the section
  2400. // directives must appear within the sections construct and must not be
  2401. // encountered elsewhere in the sections region.
  2402. if (ParentRegion != OMPD_sections &&
  2403. ParentRegion != OMPD_parallel_sections) {
  2404. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2405. << (ParentRegion != OMPD_unknown)
  2406. << getOpenMPDirectiveName(ParentRegion);
  2407. return true;
  2408. }
  2409. return false;
  2410. }
  2411. // Allow some constructs (except teams) to be orphaned (they could be
  2412. // used in functions, called from OpenMP regions with the required
  2413. // preconditions).
  2414. if (ParentRegion == OMPD_unknown &&
  2415. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2416. return false;
  2417. if (CurrentRegion == OMPD_cancellation_point ||
  2418. CurrentRegion == OMPD_cancel) {
  2419. // OpenMP [2.16, Nesting of Regions]
  2420. // A cancellation point construct for which construct-type-clause is
  2421. // taskgroup must be nested inside a task construct. A cancellation
  2422. // point construct for which construct-type-clause is not taskgroup must
  2423. // be closely nested inside an OpenMP construct that matches the type
  2424. // specified in construct-type-clause.
  2425. // A cancel construct for which construct-type-clause is taskgroup must be
  2426. // nested inside a task construct. A cancel construct for which
  2427. // construct-type-clause is not taskgroup must be closely nested inside an
  2428. // OpenMP construct that matches the type specified in
  2429. // construct-type-clause.
  2430. NestingProhibited =
  2431. !((CancelRegion == OMPD_parallel &&
  2432. (ParentRegion == OMPD_parallel ||
  2433. ParentRegion == OMPD_target_parallel)) ||
  2434. (CancelRegion == OMPD_for &&
  2435. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2436. ParentRegion == OMPD_target_parallel_for ||
  2437. ParentRegion == OMPD_distribute_parallel_for ||
  2438. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2439. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2440. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2441. (CancelRegion == OMPD_sections &&
  2442. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2443. ParentRegion == OMPD_parallel_sections)));
  2444. } else if (CurrentRegion == OMPD_master) {
  2445. // OpenMP [2.16, Nesting of Regions]
  2446. // A master region may not be closely nested inside a worksharing,
  2447. // atomic, or explicit task region.
  2448. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2449. isOpenMPTaskingDirective(ParentRegion);
  2450. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2451. // OpenMP [2.16, Nesting of Regions]
  2452. // A critical region may not be nested (closely or otherwise) inside a
  2453. // critical region with the same name. Note that this restriction is not
  2454. // sufficient to prevent deadlock.
  2455. SourceLocation PreviousCriticalLoc;
  2456. bool DeadLock = Stack->hasDirective(
  2457. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2458. const DeclarationNameInfo &DNI,
  2459. SourceLocation Loc) -> bool {
  2460. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2461. PreviousCriticalLoc = Loc;
  2462. return true;
  2463. } else
  2464. return false;
  2465. },
  2466. false /* skip top directive */);
  2467. if (DeadLock) {
  2468. SemaRef.Diag(StartLoc,
  2469. diag::err_omp_prohibited_region_critical_same_name)
  2470. << CurrentName.getName();
  2471. if (PreviousCriticalLoc.isValid())
  2472. SemaRef.Diag(PreviousCriticalLoc,
  2473. diag::note_omp_previous_critical_region);
  2474. return true;
  2475. }
  2476. } else if (CurrentRegion == OMPD_barrier) {
  2477. // OpenMP [2.16, Nesting of Regions]
  2478. // A barrier region may not be closely nested inside a worksharing,
  2479. // explicit task, critical, ordered, atomic, or master region.
  2480. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2481. isOpenMPTaskingDirective(ParentRegion) ||
  2482. ParentRegion == OMPD_master ||
  2483. ParentRegion == OMPD_critical ||
  2484. ParentRegion == OMPD_ordered;
  2485. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2486. !isOpenMPParallelDirective(CurrentRegion) &&
  2487. !isOpenMPTeamsDirective(CurrentRegion)) {
  2488. // OpenMP [2.16, Nesting of Regions]
  2489. // A worksharing region may not be closely nested inside a worksharing,
  2490. // explicit task, critical, ordered, atomic, or master region.
  2491. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2492. isOpenMPTaskingDirective(ParentRegion) ||
  2493. ParentRegion == OMPD_master ||
  2494. ParentRegion == OMPD_critical ||
  2495. ParentRegion == OMPD_ordered;
  2496. Recommend = ShouldBeInParallelRegion;
  2497. } else if (CurrentRegion == OMPD_ordered) {
  2498. // OpenMP [2.16, Nesting of Regions]
  2499. // An ordered region may not be closely nested inside a critical,
  2500. // atomic, or explicit task region.
  2501. // An ordered region must be closely nested inside a loop region (or
  2502. // parallel loop region) with an ordered clause.
  2503. // OpenMP [2.8.1,simd Construct, Restrictions]
  2504. // An ordered construct with the simd clause is the only OpenMP construct
  2505. // that can appear in the simd region.
  2506. NestingProhibited = ParentRegion == OMPD_critical ||
  2507. isOpenMPTaskingDirective(ParentRegion) ||
  2508. !(isOpenMPSimdDirective(ParentRegion) ||
  2509. Stack->isParentOrderedRegion());
  2510. Recommend = ShouldBeInOrderedRegion;
  2511. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2512. // OpenMP [2.16, Nesting of Regions]
  2513. // If specified, a teams construct must be contained within a target
  2514. // construct.
  2515. NestingProhibited = ParentRegion != OMPD_target;
  2516. OrphanSeen = ParentRegion == OMPD_unknown;
  2517. Recommend = ShouldBeInTargetRegion;
  2518. }
  2519. if (!NestingProhibited &&
  2520. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2521. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2522. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2523. // OpenMP [2.16, Nesting of Regions]
  2524. // distribute, parallel, parallel sections, parallel workshare, and the
  2525. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2526. // constructs that can be closely nested in the teams region.
  2527. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2528. !isOpenMPDistributeDirective(CurrentRegion);
  2529. Recommend = ShouldBeInParallelRegion;
  2530. }
  2531. if (!NestingProhibited &&
  2532. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2533. // OpenMP 4.5 [2.17 Nesting of Regions]
  2534. // The region associated with the distribute construct must be strictly
  2535. // nested inside a teams region
  2536. NestingProhibited =
  2537. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2538. Recommend = ShouldBeInTeamsRegion;
  2539. }
  2540. if (!NestingProhibited &&
  2541. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2542. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2543. // OpenMP 4.5 [2.17 Nesting of Regions]
  2544. // If a target, target update, target data, target enter data, or
  2545. // target exit data construct is encountered during execution of a
  2546. // target region, the behavior is unspecified.
  2547. NestingProhibited = Stack->hasDirective(
  2548. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2549. SourceLocation) -> bool {
  2550. if (isOpenMPTargetExecutionDirective(K)) {
  2551. OffendingRegion = K;
  2552. return true;
  2553. } else
  2554. return false;
  2555. },
  2556. false /* don't skip top directive */);
  2557. CloseNesting = false;
  2558. }
  2559. if (NestingProhibited) {
  2560. if (OrphanSeen) {
  2561. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2562. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2563. } else {
  2564. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2565. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2566. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2567. }
  2568. return true;
  2569. }
  2570. }
  2571. return false;
  2572. }
  2573. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2574. ArrayRef<OMPClause *> Clauses,
  2575. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2576. bool ErrorFound = false;
  2577. unsigned NamedModifiersNumber = 0;
  2578. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2579. OMPD_unknown + 1);
  2580. SmallVector<SourceLocation, 4> NameModifierLoc;
  2581. for (const auto *C : Clauses) {
  2582. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2583. // At most one if clause without a directive-name-modifier can appear on
  2584. // the directive.
  2585. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2586. if (FoundNameModifiers[CurNM]) {
  2587. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2588. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2589. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2590. ErrorFound = true;
  2591. } else if (CurNM != OMPD_unknown) {
  2592. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2593. ++NamedModifiersNumber;
  2594. }
  2595. FoundNameModifiers[CurNM] = IC;
  2596. if (CurNM == OMPD_unknown)
  2597. continue;
  2598. // Check if the specified name modifier is allowed for the current
  2599. // directive.
  2600. // At most one if clause with the particular directive-name-modifier can
  2601. // appear on the directive.
  2602. bool MatchFound = false;
  2603. for (auto NM : AllowedNameModifiers) {
  2604. if (CurNM == NM) {
  2605. MatchFound = true;
  2606. break;
  2607. }
  2608. }
  2609. if (!MatchFound) {
  2610. S.Diag(IC->getNameModifierLoc(),
  2611. diag::err_omp_wrong_if_directive_name_modifier)
  2612. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2613. ErrorFound = true;
  2614. }
  2615. }
  2616. }
  2617. // If any if clause on the directive includes a directive-name-modifier then
  2618. // all if clauses on the directive must include a directive-name-modifier.
  2619. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2620. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2621. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2622. diag::err_omp_no_more_if_clause);
  2623. } else {
  2624. std::string Values;
  2625. std::string Sep(", ");
  2626. unsigned AllowedCnt = 0;
  2627. unsigned TotalAllowedNum =
  2628. AllowedNameModifiers.size() - NamedModifiersNumber;
  2629. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2630. ++Cnt) {
  2631. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2632. if (!FoundNameModifiers[NM]) {
  2633. Values += "'";
  2634. Values += getOpenMPDirectiveName(NM);
  2635. Values += "'";
  2636. if (AllowedCnt + 2 == TotalAllowedNum)
  2637. Values += " or ";
  2638. else if (AllowedCnt + 1 != TotalAllowedNum)
  2639. Values += Sep;
  2640. ++AllowedCnt;
  2641. }
  2642. }
  2643. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2644. diag::err_omp_unnamed_if_clause)
  2645. << (TotalAllowedNum > 1) << Values;
  2646. }
  2647. for (auto Loc : NameModifierLoc) {
  2648. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2649. }
  2650. ErrorFound = true;
  2651. }
  2652. return ErrorFound;
  2653. }
  2654. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2655. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2656. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2657. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2658. StmtResult Res = StmtError();
  2659. // First check CancelRegion which is then used in checkNestingOfRegions.
  2660. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  2661. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2662. StartLoc))
  2663. return StmtError();
  2664. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2665. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2666. bool ErrorFound = false;
  2667. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2668. if (AStmt && !CurContext->isDependentContext()) {
  2669. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2670. // Check default data sharing attributes for referenced variables.
  2671. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2672. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  2673. Stmt *S = AStmt;
  2674. while (--ThisCaptureLevel >= 0)
  2675. S = cast<CapturedStmt>(S)->getCapturedStmt();
  2676. DSAChecker.Visit(S);
  2677. if (DSAChecker.isErrorFound())
  2678. return StmtError();
  2679. // Generate list of implicitly defined firstprivate variables.
  2680. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2681. SmallVector<Expr *, 4> ImplicitFirstprivates(
  2682. DSAChecker.getImplicitFirstprivate().begin(),
  2683. DSAChecker.getImplicitFirstprivate().end());
  2684. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  2685. DSAChecker.getImplicitMap().end());
  2686. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  2687. for (auto *C : Clauses) {
  2688. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  2689. for (auto *E : IRC->taskgroup_descriptors())
  2690. if (E)
  2691. ImplicitFirstprivates.emplace_back(E);
  2692. }
  2693. }
  2694. if (!ImplicitFirstprivates.empty()) {
  2695. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2696. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  2697. SourceLocation())) {
  2698. ClausesWithImplicit.push_back(Implicit);
  2699. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2700. ImplicitFirstprivates.size();
  2701. } else
  2702. ErrorFound = true;
  2703. }
  2704. if (!ImplicitMaps.empty()) {
  2705. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  2706. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  2707. SourceLocation(), SourceLocation(), ImplicitMaps,
  2708. SourceLocation(), SourceLocation(), SourceLocation())) {
  2709. ClausesWithImplicit.emplace_back(Implicit);
  2710. ErrorFound |=
  2711. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  2712. } else
  2713. ErrorFound = true;
  2714. }
  2715. }
  2716. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2717. switch (Kind) {
  2718. case OMPD_parallel:
  2719. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2720. EndLoc);
  2721. AllowedNameModifiers.push_back(OMPD_parallel);
  2722. break;
  2723. case OMPD_simd:
  2724. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2725. VarsWithInheritedDSA);
  2726. break;
  2727. case OMPD_for:
  2728. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2729. VarsWithInheritedDSA);
  2730. break;
  2731. case OMPD_for_simd:
  2732. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2733. EndLoc, VarsWithInheritedDSA);
  2734. break;
  2735. case OMPD_sections:
  2736. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2737. EndLoc);
  2738. break;
  2739. case OMPD_section:
  2740. assert(ClausesWithImplicit.empty() &&
  2741. "No clauses are allowed for 'omp section' directive");
  2742. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2743. break;
  2744. case OMPD_single:
  2745. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2746. EndLoc);
  2747. break;
  2748. case OMPD_master:
  2749. assert(ClausesWithImplicit.empty() &&
  2750. "No clauses are allowed for 'omp master' directive");
  2751. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2752. break;
  2753. case OMPD_critical:
  2754. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2755. StartLoc, EndLoc);
  2756. break;
  2757. case OMPD_parallel_for:
  2758. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2759. EndLoc, VarsWithInheritedDSA);
  2760. AllowedNameModifiers.push_back(OMPD_parallel);
  2761. break;
  2762. case OMPD_parallel_for_simd:
  2763. Res = ActOnOpenMPParallelForSimdDirective(
  2764. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2765. AllowedNameModifiers.push_back(OMPD_parallel);
  2766. break;
  2767. case OMPD_parallel_sections:
  2768. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2769. StartLoc, EndLoc);
  2770. AllowedNameModifiers.push_back(OMPD_parallel);
  2771. break;
  2772. case OMPD_task:
  2773. Res =
  2774. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2775. AllowedNameModifiers.push_back(OMPD_task);
  2776. break;
  2777. case OMPD_taskyield:
  2778. assert(ClausesWithImplicit.empty() &&
  2779. "No clauses are allowed for 'omp taskyield' directive");
  2780. assert(AStmt == nullptr &&
  2781. "No associated statement allowed for 'omp taskyield' directive");
  2782. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2783. break;
  2784. case OMPD_barrier:
  2785. assert(ClausesWithImplicit.empty() &&
  2786. "No clauses are allowed for 'omp barrier' directive");
  2787. assert(AStmt == nullptr &&
  2788. "No associated statement allowed for 'omp barrier' directive");
  2789. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2790. break;
  2791. case OMPD_taskwait:
  2792. assert(ClausesWithImplicit.empty() &&
  2793. "No clauses are allowed for 'omp taskwait' directive");
  2794. assert(AStmt == nullptr &&
  2795. "No associated statement allowed for 'omp taskwait' directive");
  2796. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2797. break;
  2798. case OMPD_taskgroup:
  2799. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  2800. EndLoc);
  2801. break;
  2802. case OMPD_flush:
  2803. assert(AStmt == nullptr &&
  2804. "No associated statement allowed for 'omp flush' directive");
  2805. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2806. break;
  2807. case OMPD_ordered:
  2808. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2809. EndLoc);
  2810. break;
  2811. case OMPD_atomic:
  2812. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2813. EndLoc);
  2814. break;
  2815. case OMPD_teams:
  2816. Res =
  2817. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2818. break;
  2819. case OMPD_target:
  2820. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2821. EndLoc);
  2822. AllowedNameModifiers.push_back(OMPD_target);
  2823. break;
  2824. case OMPD_target_parallel:
  2825. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2826. StartLoc, EndLoc);
  2827. AllowedNameModifiers.push_back(OMPD_target);
  2828. AllowedNameModifiers.push_back(OMPD_parallel);
  2829. break;
  2830. case OMPD_target_parallel_for:
  2831. Res = ActOnOpenMPTargetParallelForDirective(
  2832. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2833. AllowedNameModifiers.push_back(OMPD_target);
  2834. AllowedNameModifiers.push_back(OMPD_parallel);
  2835. break;
  2836. case OMPD_cancellation_point:
  2837. assert(ClausesWithImplicit.empty() &&
  2838. "No clauses are allowed for 'omp cancellation point' directive");
  2839. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2840. "cancellation point' directive");
  2841. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2842. break;
  2843. case OMPD_cancel:
  2844. assert(AStmt == nullptr &&
  2845. "No associated statement allowed for 'omp cancel' directive");
  2846. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2847. CancelRegion);
  2848. AllowedNameModifiers.push_back(OMPD_cancel);
  2849. break;
  2850. case OMPD_target_data:
  2851. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2852. EndLoc);
  2853. AllowedNameModifiers.push_back(OMPD_target_data);
  2854. break;
  2855. case OMPD_target_enter_data:
  2856. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2857. EndLoc, AStmt);
  2858. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2859. break;
  2860. case OMPD_target_exit_data:
  2861. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2862. EndLoc, AStmt);
  2863. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2864. break;
  2865. case OMPD_taskloop:
  2866. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2867. EndLoc, VarsWithInheritedDSA);
  2868. AllowedNameModifiers.push_back(OMPD_taskloop);
  2869. break;
  2870. case OMPD_taskloop_simd:
  2871. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2872. EndLoc, VarsWithInheritedDSA);
  2873. AllowedNameModifiers.push_back(OMPD_taskloop);
  2874. break;
  2875. case OMPD_distribute:
  2876. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2877. EndLoc, VarsWithInheritedDSA);
  2878. break;
  2879. case OMPD_target_update:
  2880. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  2881. EndLoc, AStmt);
  2882. AllowedNameModifiers.push_back(OMPD_target_update);
  2883. break;
  2884. case OMPD_distribute_parallel_for:
  2885. Res = ActOnOpenMPDistributeParallelForDirective(
  2886. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2887. AllowedNameModifiers.push_back(OMPD_parallel);
  2888. break;
  2889. case OMPD_distribute_parallel_for_simd:
  2890. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  2891. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2892. AllowedNameModifiers.push_back(OMPD_parallel);
  2893. break;
  2894. case OMPD_distribute_simd:
  2895. Res = ActOnOpenMPDistributeSimdDirective(
  2896. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2897. break;
  2898. case OMPD_target_parallel_for_simd:
  2899. Res = ActOnOpenMPTargetParallelForSimdDirective(
  2900. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2901. AllowedNameModifiers.push_back(OMPD_target);
  2902. AllowedNameModifiers.push_back(OMPD_parallel);
  2903. break;
  2904. case OMPD_target_simd:
  2905. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2906. EndLoc, VarsWithInheritedDSA);
  2907. AllowedNameModifiers.push_back(OMPD_target);
  2908. break;
  2909. case OMPD_teams_distribute:
  2910. Res = ActOnOpenMPTeamsDistributeDirective(
  2911. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2912. break;
  2913. case OMPD_teams_distribute_simd:
  2914. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  2915. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2916. break;
  2917. case OMPD_teams_distribute_parallel_for_simd:
  2918. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  2919. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2920. AllowedNameModifiers.push_back(OMPD_parallel);
  2921. break;
  2922. case OMPD_teams_distribute_parallel_for:
  2923. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  2924. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2925. AllowedNameModifiers.push_back(OMPD_parallel);
  2926. break;
  2927. case OMPD_target_teams:
  2928. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2929. EndLoc);
  2930. AllowedNameModifiers.push_back(OMPD_target);
  2931. break;
  2932. case OMPD_target_teams_distribute:
  2933. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  2934. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2935. AllowedNameModifiers.push_back(OMPD_target);
  2936. break;
  2937. case OMPD_target_teams_distribute_parallel_for:
  2938. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  2939. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2940. AllowedNameModifiers.push_back(OMPD_target);
  2941. AllowedNameModifiers.push_back(OMPD_parallel);
  2942. break;
  2943. case OMPD_target_teams_distribute_parallel_for_simd:
  2944. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  2945. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2946. AllowedNameModifiers.push_back(OMPD_target);
  2947. AllowedNameModifiers.push_back(OMPD_parallel);
  2948. break;
  2949. case OMPD_target_teams_distribute_simd:
  2950. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  2951. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2952. AllowedNameModifiers.push_back(OMPD_target);
  2953. break;
  2954. case OMPD_declare_target:
  2955. case OMPD_end_declare_target:
  2956. case OMPD_threadprivate:
  2957. case OMPD_declare_reduction:
  2958. case OMPD_declare_simd:
  2959. llvm_unreachable("OpenMP Directive is not allowed");
  2960. case OMPD_unknown:
  2961. llvm_unreachable("Unknown OpenMP directive");
  2962. }
  2963. for (auto P : VarsWithInheritedDSA) {
  2964. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2965. << P.first << P.second->getSourceRange();
  2966. }
  2967. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2968. if (!AllowedNameModifiers.empty())
  2969. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2970. ErrorFound;
  2971. if (ErrorFound)
  2972. return StmtError();
  2973. return Res;
  2974. }
  2975. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  2976. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  2977. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  2978. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  2979. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  2980. assert(Aligneds.size() == Alignments.size());
  2981. assert(Linears.size() == LinModifiers.size());
  2982. assert(Linears.size() == Steps.size());
  2983. if (!DG || DG.get().isNull())
  2984. return DeclGroupPtrTy();
  2985. if (!DG.get().isSingleDecl()) {
  2986. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  2987. return DG;
  2988. }
  2989. auto *ADecl = DG.get().getSingleDecl();
  2990. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  2991. ADecl = FTD->getTemplatedDecl();
  2992. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  2993. if (!FD) {
  2994. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  2995. return DeclGroupPtrTy();
  2996. }
  2997. // OpenMP [2.8.2, declare simd construct, Description]
  2998. // The parameter of the simdlen clause must be a constant positive integer
  2999. // expression.
  3000. ExprResult SL;
  3001. if (Simdlen)
  3002. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3003. // OpenMP [2.8.2, declare simd construct, Description]
  3004. // The special this pointer can be used as if was one of the arguments to the
  3005. // function in any of the linear, aligned, or uniform clauses.
  3006. // The uniform clause declares one or more arguments to have an invariant
  3007. // value for all concurrent invocations of the function in the execution of a
  3008. // single SIMD loop.
  3009. llvm::DenseMap<Decl *, Expr *> UniformedArgs;
  3010. Expr *UniformedLinearThis = nullptr;
  3011. for (auto *E : Uniforms) {
  3012. E = E->IgnoreParenImpCasts();
  3013. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3014. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3015. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3016. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3017. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3018. UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
  3019. continue;
  3020. }
  3021. if (isa<CXXThisExpr>(E)) {
  3022. UniformedLinearThis = E;
  3023. continue;
  3024. }
  3025. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3026. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3027. }
  3028. // OpenMP [2.8.2, declare simd construct, Description]
  3029. // The aligned clause declares that the object to which each list item points
  3030. // is aligned to the number of bytes expressed in the optional parameter of
  3031. // the aligned clause.
  3032. // The special this pointer can be used as if was one of the arguments to the
  3033. // function in any of the linear, aligned, or uniform clauses.
  3034. // The type of list items appearing in the aligned clause must be array,
  3035. // pointer, reference to array, or reference to pointer.
  3036. llvm::DenseMap<Decl *, Expr *> AlignedArgs;
  3037. Expr *AlignedThis = nullptr;
  3038. for (auto *E : Aligneds) {
  3039. E = E->IgnoreParenImpCasts();
  3040. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3041. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3042. auto *CanonPVD = PVD->getCanonicalDecl();
  3043. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3044. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3045. ->getCanonicalDecl() == CanonPVD) {
  3046. // OpenMP [2.8.1, simd construct, Restrictions]
  3047. // A list-item cannot appear in more than one aligned clause.
  3048. if (AlignedArgs.count(CanonPVD) > 0) {
  3049. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3050. << 1 << E->getSourceRange();
  3051. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3052. diag::note_omp_explicit_dsa)
  3053. << getOpenMPClauseName(OMPC_aligned);
  3054. continue;
  3055. }
  3056. AlignedArgs[CanonPVD] = E;
  3057. QualType QTy = PVD->getType()
  3058. .getNonReferenceType()
  3059. .getUnqualifiedType()
  3060. .getCanonicalType();
  3061. const Type *Ty = QTy.getTypePtrOrNull();
  3062. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3063. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3064. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3065. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3066. }
  3067. continue;
  3068. }
  3069. }
  3070. if (isa<CXXThisExpr>(E)) {
  3071. if (AlignedThis) {
  3072. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3073. << 2 << E->getSourceRange();
  3074. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3075. << getOpenMPClauseName(OMPC_aligned);
  3076. }
  3077. AlignedThis = E;
  3078. continue;
  3079. }
  3080. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3081. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3082. }
  3083. // The optional parameter of the aligned clause, alignment, must be a constant
  3084. // positive integer expression. If no optional parameter is specified,
  3085. // implementation-defined default alignments for SIMD instructions on the
  3086. // target platforms are assumed.
  3087. SmallVector<Expr *, 4> NewAligns;
  3088. for (auto *E : Alignments) {
  3089. ExprResult Align;
  3090. if (E)
  3091. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3092. NewAligns.push_back(Align.get());
  3093. }
  3094. // OpenMP [2.8.2, declare simd construct, Description]
  3095. // The linear clause declares one or more list items to be private to a SIMD
  3096. // lane and to have a linear relationship with respect to the iteration space
  3097. // of a loop.
  3098. // The special this pointer can be used as if was one of the arguments to the
  3099. // function in any of the linear, aligned, or uniform clauses.
  3100. // When a linear-step expression is specified in a linear clause it must be
  3101. // either a constant integer expression or an integer-typed parameter that is
  3102. // specified in a uniform clause on the directive.
  3103. llvm::DenseMap<Decl *, Expr *> LinearArgs;
  3104. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3105. auto MI = LinModifiers.begin();
  3106. for (auto *E : Linears) {
  3107. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3108. ++MI;
  3109. E = E->IgnoreParenImpCasts();
  3110. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3111. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3112. auto *CanonPVD = PVD->getCanonicalDecl();
  3113. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3114. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3115. ->getCanonicalDecl() == CanonPVD) {
  3116. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3117. // A list-item cannot appear in more than one linear clause.
  3118. if (LinearArgs.count(CanonPVD) > 0) {
  3119. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3120. << getOpenMPClauseName(OMPC_linear)
  3121. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3122. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3123. diag::note_omp_explicit_dsa)
  3124. << getOpenMPClauseName(OMPC_linear);
  3125. continue;
  3126. }
  3127. // Each argument can appear in at most one uniform or linear clause.
  3128. if (UniformedArgs.count(CanonPVD) > 0) {
  3129. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3130. << getOpenMPClauseName(OMPC_linear)
  3131. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3132. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3133. diag::note_omp_explicit_dsa)
  3134. << getOpenMPClauseName(OMPC_uniform);
  3135. continue;
  3136. }
  3137. LinearArgs[CanonPVD] = E;
  3138. if (E->isValueDependent() || E->isTypeDependent() ||
  3139. E->isInstantiationDependent() ||
  3140. E->containsUnexpandedParameterPack())
  3141. continue;
  3142. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3143. PVD->getOriginalType());
  3144. continue;
  3145. }
  3146. }
  3147. if (isa<CXXThisExpr>(E)) {
  3148. if (UniformedLinearThis) {
  3149. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3150. << getOpenMPClauseName(OMPC_linear)
  3151. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3152. << E->getSourceRange();
  3153. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3154. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3155. : OMPC_linear);
  3156. continue;
  3157. }
  3158. UniformedLinearThis = E;
  3159. if (E->isValueDependent() || E->isTypeDependent() ||
  3160. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3161. continue;
  3162. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3163. E->getType());
  3164. continue;
  3165. }
  3166. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3167. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3168. }
  3169. Expr *Step = nullptr;
  3170. Expr *NewStep = nullptr;
  3171. SmallVector<Expr *, 4> NewSteps;
  3172. for (auto *E : Steps) {
  3173. // Skip the same step expression, it was checked already.
  3174. if (Step == E || !E) {
  3175. NewSteps.push_back(E ? NewStep : nullptr);
  3176. continue;
  3177. }
  3178. Step = E;
  3179. if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3180. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3181. auto *CanonPVD = PVD->getCanonicalDecl();
  3182. if (UniformedArgs.count(CanonPVD) == 0) {
  3183. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3184. << Step->getSourceRange();
  3185. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3186. E->isInstantiationDependent() ||
  3187. E->containsUnexpandedParameterPack() ||
  3188. CanonPVD->getType()->hasIntegerRepresentation())
  3189. NewSteps.push_back(Step);
  3190. else {
  3191. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3192. << Step->getSourceRange();
  3193. }
  3194. continue;
  3195. }
  3196. NewStep = Step;
  3197. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3198. !Step->isInstantiationDependent() &&
  3199. !Step->containsUnexpandedParameterPack()) {
  3200. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3201. .get();
  3202. if (NewStep)
  3203. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3204. }
  3205. NewSteps.push_back(NewStep);
  3206. }
  3207. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3208. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3209. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3210. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3211. const_cast<Expr **>(Linears.data()), Linears.size(),
  3212. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3213. NewSteps.data(), NewSteps.size(), SR);
  3214. ADecl->addAttr(NewAttr);
  3215. return ConvertDeclToDeclGroup(ADecl);
  3216. }
  3217. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3218. Stmt *AStmt,
  3219. SourceLocation StartLoc,
  3220. SourceLocation EndLoc) {
  3221. if (!AStmt)
  3222. return StmtError();
  3223. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3224. // 1.2.2 OpenMP Language Terminology
  3225. // Structured block - An executable statement with a single entry at the
  3226. // top and a single exit at the bottom.
  3227. // The point of exit cannot be a branch out of the structured block.
  3228. // longjmp() and throw() must not violate the entry/exit criteria.
  3229. CS->getCapturedDecl()->setNothrow();
  3230. getCurFunction()->setHasBranchProtectedScope();
  3231. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3232. DSAStack->isCancelRegion());
  3233. }
  3234. namespace {
  3235. /// \brief Helper class for checking canonical form of the OpenMP loops and
  3236. /// extracting iteration space of each loop in the loop nest, that will be used
  3237. /// for IR generation.
  3238. class OpenMPIterationSpaceChecker {
  3239. /// \brief Reference to Sema.
  3240. Sema &SemaRef;
  3241. /// \brief A location for diagnostics (when there is no some better location).
  3242. SourceLocation DefaultLoc;
  3243. /// \brief A location for diagnostics (when increment is not compatible).
  3244. SourceLocation ConditionLoc;
  3245. /// \brief A source location for referring to loop init later.
  3246. SourceRange InitSrcRange;
  3247. /// \brief A source location for referring to condition later.
  3248. SourceRange ConditionSrcRange;
  3249. /// \brief A source location for referring to increment later.
  3250. SourceRange IncrementSrcRange;
  3251. /// \brief Loop variable.
  3252. ValueDecl *LCDecl = nullptr;
  3253. /// \brief Reference to loop variable.
  3254. Expr *LCRef = nullptr;
  3255. /// \brief Lower bound (initializer for the var).
  3256. Expr *LB = nullptr;
  3257. /// \brief Upper bound.
  3258. Expr *UB = nullptr;
  3259. /// \brief Loop step (increment).
  3260. Expr *Step = nullptr;
  3261. /// \brief This flag is true when condition is one of:
  3262. /// Var < UB
  3263. /// Var <= UB
  3264. /// UB > Var
  3265. /// UB >= Var
  3266. bool TestIsLessOp = false;
  3267. /// \brief This flag is true when condition is strict ( < or > ).
  3268. bool TestIsStrictOp = false;
  3269. /// \brief This flag is true when step is subtracted on each iteration.
  3270. bool SubtractStep = false;
  3271. public:
  3272. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3273. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3274. /// \brief Check init-expr for canonical loop form and save loop counter
  3275. /// variable - #Var and its initialization value - #LB.
  3276. bool CheckInit(Stmt *S, bool EmitDiags = true);
  3277. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  3278. /// for less/greater and for strict/non-strict comparison.
  3279. bool CheckCond(Expr *S);
  3280. /// \brief Check incr-expr for canonical loop form and return true if it
  3281. /// does not conform, otherwise save loop step (#Step).
  3282. bool CheckInc(Expr *S);
  3283. /// \brief Return the loop counter variable.
  3284. ValueDecl *GetLoopDecl() const { return LCDecl; }
  3285. /// \brief Return the reference expression to loop counter variable.
  3286. Expr *GetLoopDeclRefExpr() const { return LCRef; }
  3287. /// \brief Source range of the loop init.
  3288. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  3289. /// \brief Source range of the loop condition.
  3290. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  3291. /// \brief Source range of the loop increment.
  3292. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  3293. /// \brief True if the step should be subtracted.
  3294. bool ShouldSubtractStep() const { return SubtractStep; }
  3295. /// \brief Build the expression to calculate the number of iterations.
  3296. Expr *
  3297. BuildNumIterations(Scope *S, const bool LimitedType,
  3298. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3299. /// \brief Build the precondition expression for the loops.
  3300. Expr *BuildPreCond(Scope *S, Expr *Cond,
  3301. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3302. /// \brief Build reference expression to the counter be used for codegen.
  3303. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
  3304. DSAStackTy &DSA) const;
  3305. /// \brief Build reference expression to the private counter be used for
  3306. /// codegen.
  3307. Expr *BuildPrivateCounterVar() const;
  3308. /// \brief Build initialization of the counter be used for codegen.
  3309. Expr *BuildCounterInit() const;
  3310. /// \brief Build step of the counter be used for codegen.
  3311. Expr *BuildCounterStep() const;
  3312. /// \brief Return true if any expression is dependent.
  3313. bool Dependent() const;
  3314. private:
  3315. /// \brief Check the right-hand side of an assignment in the increment
  3316. /// expression.
  3317. bool CheckIncRHS(Expr *RHS);
  3318. /// \brief Helper to set loop counter variable and its initializer.
  3319. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3320. /// \brief Helper to set upper bound.
  3321. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3322. SourceLocation SL);
  3323. /// \brief Helper to set loop increment.
  3324. bool SetStep(Expr *NewStep, bool Subtract);
  3325. };
  3326. bool OpenMPIterationSpaceChecker::Dependent() const {
  3327. if (!LCDecl) {
  3328. assert(!LB && !UB && !Step);
  3329. return false;
  3330. }
  3331. return LCDecl->getType()->isDependentType() ||
  3332. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3333. (Step && Step->isValueDependent());
  3334. }
  3335. bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
  3336. Expr *NewLCRefExpr,
  3337. Expr *NewLB) {
  3338. // State consistency checking to ensure correct usage.
  3339. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3340. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3341. if (!NewLCDecl || !NewLB)
  3342. return true;
  3343. LCDecl = getCanonicalDecl(NewLCDecl);
  3344. LCRef = NewLCRefExpr;
  3345. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3346. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3347. if ((Ctor->isCopyOrMoveConstructor() ||
  3348. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3349. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3350. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3351. LB = NewLB;
  3352. return false;
  3353. }
  3354. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3355. SourceRange SR, SourceLocation SL) {
  3356. // State consistency checking to ensure correct usage.
  3357. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3358. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3359. if (!NewUB)
  3360. return true;
  3361. UB = NewUB;
  3362. TestIsLessOp = LessOp;
  3363. TestIsStrictOp = StrictOp;
  3364. ConditionSrcRange = SR;
  3365. ConditionLoc = SL;
  3366. return false;
  3367. }
  3368. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  3369. // State consistency checking to ensure correct usage.
  3370. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3371. if (!NewStep)
  3372. return true;
  3373. if (!NewStep->isValueDependent()) {
  3374. // Check that the step is integer expression.
  3375. SourceLocation StepLoc = NewStep->getLocStart();
  3376. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3377. StepLoc, getExprAsWritten(NewStep));
  3378. if (Val.isInvalid())
  3379. return true;
  3380. NewStep = Val.get();
  3381. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3382. // If test-expr is of form var relational-op b and relational-op is < or
  3383. // <= then incr-expr must cause var to increase on each iteration of the
  3384. // loop. If test-expr is of form var relational-op b and relational-op is
  3385. // > or >= then incr-expr must cause var to decrease on each iteration of
  3386. // the loop.
  3387. // If test-expr is of form b relational-op var and relational-op is < or
  3388. // <= then incr-expr must cause var to decrease on each iteration of the
  3389. // loop. If test-expr is of form b relational-op var and relational-op is
  3390. // > or >= then incr-expr must cause var to increase on each iteration of
  3391. // the loop.
  3392. llvm::APSInt Result;
  3393. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3394. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3395. bool IsConstNeg =
  3396. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3397. bool IsConstPos =
  3398. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3399. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3400. if (UB && (IsConstZero ||
  3401. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3402. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3403. SemaRef.Diag(NewStep->getExprLoc(),
  3404. diag::err_omp_loop_incr_not_compatible)
  3405. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3406. SemaRef.Diag(ConditionLoc,
  3407. diag::note_omp_loop_cond_requres_compatible_incr)
  3408. << TestIsLessOp << ConditionSrcRange;
  3409. return true;
  3410. }
  3411. if (TestIsLessOp == Subtract) {
  3412. NewStep =
  3413. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3414. .get();
  3415. Subtract = !Subtract;
  3416. }
  3417. }
  3418. Step = NewStep;
  3419. SubtractStep = Subtract;
  3420. return false;
  3421. }
  3422. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  3423. // Check init-expr for canonical loop form and save loop counter
  3424. // variable - #Var and its initialization value - #LB.
  3425. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3426. // var = lb
  3427. // integer-type var = lb
  3428. // random-access-iterator-type var = lb
  3429. // pointer-type var = lb
  3430. //
  3431. if (!S) {
  3432. if (EmitDiags) {
  3433. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3434. }
  3435. return true;
  3436. }
  3437. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3438. if (!ExprTemp->cleanupsHaveSideEffects())
  3439. S = ExprTemp->getSubExpr();
  3440. InitSrcRange = S->getSourceRange();
  3441. if (Expr *E = dyn_cast<Expr>(S))
  3442. S = E->IgnoreParens();
  3443. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3444. if (BO->getOpcode() == BO_Assign) {
  3445. auto *LHS = BO->getLHS()->IgnoreParens();
  3446. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3447. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3448. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3449. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3450. return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3451. }
  3452. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3453. if (ME->isArrow() &&
  3454. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3455. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3456. }
  3457. }
  3458. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3459. if (DS->isSingleDecl()) {
  3460. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3461. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3462. // Accept non-canonical init form here but emit ext. warning.
  3463. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3464. SemaRef.Diag(S->getLocStart(),
  3465. diag::ext_omp_loop_not_canonical_init)
  3466. << S->getSourceRange();
  3467. return SetLCDeclAndLB(Var, nullptr, Var->getInit());
  3468. }
  3469. }
  3470. }
  3471. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3472. if (CE->getOperator() == OO_Equal) {
  3473. auto *LHS = CE->getArg(0);
  3474. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3475. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3476. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3477. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3478. return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3479. }
  3480. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3481. if (ME->isArrow() &&
  3482. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3483. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3484. }
  3485. }
  3486. }
  3487. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3488. return false;
  3489. if (EmitDiags) {
  3490. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3491. << S->getSourceRange();
  3492. }
  3493. return true;
  3494. }
  3495. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3496. /// variable (which may be the loop variable) if possible.
  3497. static const ValueDecl *GetInitLCDecl(Expr *E) {
  3498. if (!E)
  3499. return nullptr;
  3500. E = getExprAsWritten(E);
  3501. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3502. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3503. if ((Ctor->isCopyOrMoveConstructor() ||
  3504. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3505. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3506. E = CE->getArg(0)->IgnoreParenImpCasts();
  3507. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3508. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3509. return getCanonicalDecl(VD);
  3510. }
  3511. if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3512. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3513. return getCanonicalDecl(ME->getMemberDecl());
  3514. return nullptr;
  3515. }
  3516. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  3517. // Check test-expr for canonical form, save upper-bound UB, flags for
  3518. // less/greater and for strict/non-strict comparison.
  3519. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3520. // var relational-op b
  3521. // b relational-op var
  3522. //
  3523. if (!S) {
  3524. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3525. return true;
  3526. }
  3527. S = getExprAsWritten(S);
  3528. SourceLocation CondLoc = S->getLocStart();
  3529. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3530. if (BO->isRelationalOp()) {
  3531. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3532. return SetUB(BO->getRHS(),
  3533. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3534. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3535. BO->getSourceRange(), BO->getOperatorLoc());
  3536. if (GetInitLCDecl(BO->getRHS()) == LCDecl)
  3537. return SetUB(BO->getLHS(),
  3538. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3539. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3540. BO->getSourceRange(), BO->getOperatorLoc());
  3541. }
  3542. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3543. if (CE->getNumArgs() == 2) {
  3544. auto Op = CE->getOperator();
  3545. switch (Op) {
  3546. case OO_Greater:
  3547. case OO_GreaterEqual:
  3548. case OO_Less:
  3549. case OO_LessEqual:
  3550. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3551. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3552. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3553. CE->getOperatorLoc());
  3554. if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3555. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3556. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3557. CE->getOperatorLoc());
  3558. break;
  3559. default:
  3560. break;
  3561. }
  3562. }
  3563. }
  3564. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3565. return false;
  3566. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3567. << S->getSourceRange() << LCDecl;
  3568. return true;
  3569. }
  3570. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  3571. // RHS of canonical loop form increment can be:
  3572. // var + incr
  3573. // incr + var
  3574. // var - incr
  3575. //
  3576. RHS = RHS->IgnoreParenImpCasts();
  3577. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  3578. if (BO->isAdditiveOp()) {
  3579. bool IsAdd = BO->getOpcode() == BO_Add;
  3580. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3581. return SetStep(BO->getRHS(), !IsAdd);
  3582. if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
  3583. return SetStep(BO->getLHS(), false);
  3584. }
  3585. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3586. bool IsAdd = CE->getOperator() == OO_Plus;
  3587. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3588. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3589. return SetStep(CE->getArg(1), !IsAdd);
  3590. if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3591. return SetStep(CE->getArg(0), false);
  3592. }
  3593. }
  3594. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3595. return false;
  3596. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3597. << RHS->getSourceRange() << LCDecl;
  3598. return true;
  3599. }
  3600. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  3601. // Check incr-expr for canonical loop form and return true if it
  3602. // does not conform.
  3603. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3604. // ++var
  3605. // var++
  3606. // --var
  3607. // var--
  3608. // var += incr
  3609. // var -= incr
  3610. // var = var + incr
  3611. // var = incr + var
  3612. // var = var - incr
  3613. //
  3614. if (!S) {
  3615. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  3616. return true;
  3617. }
  3618. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3619. if (!ExprTemp->cleanupsHaveSideEffects())
  3620. S = ExprTemp->getSubExpr();
  3621. IncrementSrcRange = S->getSourceRange();
  3622. S = S->IgnoreParens();
  3623. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  3624. if (UO->isIncrementDecrementOp() &&
  3625. GetInitLCDecl(UO->getSubExpr()) == LCDecl)
  3626. return SetStep(SemaRef
  3627. .ActOnIntegerConstant(UO->getLocStart(),
  3628. (UO->isDecrementOp() ? -1 : 1))
  3629. .get(),
  3630. false);
  3631. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3632. switch (BO->getOpcode()) {
  3633. case BO_AddAssign:
  3634. case BO_SubAssign:
  3635. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3636. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3637. break;
  3638. case BO_Assign:
  3639. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3640. return CheckIncRHS(BO->getRHS());
  3641. break;
  3642. default:
  3643. break;
  3644. }
  3645. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3646. switch (CE->getOperator()) {
  3647. case OO_PlusPlus:
  3648. case OO_MinusMinus:
  3649. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3650. return SetStep(SemaRef
  3651. .ActOnIntegerConstant(
  3652. CE->getLocStart(),
  3653. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3654. .get(),
  3655. false);
  3656. break;
  3657. case OO_PlusEqual:
  3658. case OO_MinusEqual:
  3659. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3660. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3661. break;
  3662. case OO_Equal:
  3663. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3664. return CheckIncRHS(CE->getArg(1));
  3665. break;
  3666. default:
  3667. break;
  3668. }
  3669. }
  3670. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3671. return false;
  3672. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3673. << S->getSourceRange() << LCDecl;
  3674. return true;
  3675. }
  3676. static ExprResult
  3677. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3678. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3679. if (SemaRef.CurContext->isDependentContext())
  3680. return ExprResult(Capture);
  3681. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3682. return SemaRef.PerformImplicitConversion(
  3683. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3684. /*AllowExplicit=*/true);
  3685. auto I = Captures.find(Capture);
  3686. if (I != Captures.end())
  3687. return buildCapture(SemaRef, Capture, I->second);
  3688. DeclRefExpr *Ref = nullptr;
  3689. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3690. Captures[Capture] = Ref;
  3691. return Res;
  3692. }
  3693. /// \brief Build the expression to calculate the number of iterations.
  3694. Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
  3695. Scope *S, const bool LimitedType,
  3696. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3697. ExprResult Diff;
  3698. auto VarType = LCDecl->getType().getNonReferenceType();
  3699. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3700. SemaRef.getLangOpts().CPlusPlus) {
  3701. // Upper - Lower
  3702. auto *UBExpr = TestIsLessOp ? UB : LB;
  3703. auto *LBExpr = TestIsLessOp ? LB : UB;
  3704. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3705. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3706. if (!Upper || !Lower)
  3707. return nullptr;
  3708. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3709. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3710. // BuildBinOp already emitted error, this one is to point user to upper
  3711. // and lower bound, and to tell what is passed to 'operator-'.
  3712. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3713. << Upper->getSourceRange() << Lower->getSourceRange();
  3714. return nullptr;
  3715. }
  3716. }
  3717. if (!Diff.isUsable())
  3718. return nullptr;
  3719. // Upper - Lower [- 1]
  3720. if (TestIsStrictOp)
  3721. Diff = SemaRef.BuildBinOp(
  3722. S, DefaultLoc, BO_Sub, Diff.get(),
  3723. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3724. if (!Diff.isUsable())
  3725. return nullptr;
  3726. // Upper - Lower [- 1] + Step
  3727. auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3728. if (!NewStep.isUsable())
  3729. return nullptr;
  3730. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3731. if (!Diff.isUsable())
  3732. return nullptr;
  3733. // Parentheses (for dumping/debugging purposes only).
  3734. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3735. if (!Diff.isUsable())
  3736. return nullptr;
  3737. // (Upper - Lower [- 1] + Step) / Step
  3738. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3739. if (!Diff.isUsable())
  3740. return nullptr;
  3741. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3742. QualType Type = Diff.get()->getType();
  3743. auto &C = SemaRef.Context;
  3744. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3745. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3746. if (!Type->isIntegerType() || UseVarType) {
  3747. unsigned NewSize =
  3748. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3749. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3750. : Type->hasSignedIntegerRepresentation();
  3751. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3752. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3753. Diff = SemaRef.PerformImplicitConversion(
  3754. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3755. if (!Diff.isUsable())
  3756. return nullptr;
  3757. }
  3758. }
  3759. if (LimitedType) {
  3760. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3761. if (NewSize != C.getTypeSize(Type)) {
  3762. if (NewSize < C.getTypeSize(Type)) {
  3763. assert(NewSize == 64 && "incorrect loop var size");
  3764. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3765. << InitSrcRange << ConditionSrcRange;
  3766. }
  3767. QualType NewType = C.getIntTypeForBitwidth(
  3768. NewSize, Type->hasSignedIntegerRepresentation() ||
  3769. C.getTypeSize(Type) < NewSize);
  3770. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3771. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3772. Sema::AA_Converting, true);
  3773. if (!Diff.isUsable())
  3774. return nullptr;
  3775. }
  3776. }
  3777. }
  3778. return Diff.get();
  3779. }
  3780. Expr *OpenMPIterationSpaceChecker::BuildPreCond(
  3781. Scope *S, Expr *Cond,
  3782. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3783. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3784. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3785. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3786. auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
  3787. auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
  3788. if (!NewLB.isUsable() || !NewUB.isUsable())
  3789. return nullptr;
  3790. auto CondExpr = SemaRef.BuildBinOp(
  3791. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3792. : (TestIsStrictOp ? BO_GT : BO_GE),
  3793. NewLB.get(), NewUB.get());
  3794. if (CondExpr.isUsable()) {
  3795. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  3796. SemaRef.Context.BoolTy))
  3797. CondExpr = SemaRef.PerformImplicitConversion(
  3798. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3799. /*AllowExplicit=*/true);
  3800. }
  3801. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3802. // Otherwise use original loop conditon and evaluate it in runtime.
  3803. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3804. }
  3805. /// \brief Build reference expression to the counter be used for codegen.
  3806. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
  3807. llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  3808. auto *VD = dyn_cast<VarDecl>(LCDecl);
  3809. if (!VD) {
  3810. VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
  3811. auto *Ref = buildDeclRefExpr(
  3812. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  3813. DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  3814. // If the loop control decl is explicitly marked as private, do not mark it
  3815. // as captured again.
  3816. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  3817. Captures.insert(std::make_pair(LCRef, Ref));
  3818. return Ref;
  3819. }
  3820. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  3821. DefaultLoc);
  3822. }
  3823. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3824. if (LCDecl && !LCDecl->isInvalidDecl()) {
  3825. auto Type = LCDecl->getType().getNonReferenceType();
  3826. auto *PrivateVar =
  3827. buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
  3828. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
  3829. if (PrivateVar->isInvalidDecl())
  3830. return nullptr;
  3831. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3832. }
  3833. return nullptr;
  3834. }
  3835. /// \brief Build initialization of the counter to be used for codegen.
  3836. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3837. /// \brief Build step of the counter be used for codegen.
  3838. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3839. /// \brief Iteration space of a single for loop.
  3840. struct LoopIterationSpace final {
  3841. /// \brief Condition of the loop.
  3842. Expr *PreCond = nullptr;
  3843. /// \brief This expression calculates the number of iterations in the loop.
  3844. /// It is always possible to calculate it before starting the loop.
  3845. Expr *NumIterations = nullptr;
  3846. /// \brief The loop counter variable.
  3847. Expr *CounterVar = nullptr;
  3848. /// \brief Private loop counter variable.
  3849. Expr *PrivateCounterVar = nullptr;
  3850. /// \brief This is initializer for the initial value of #CounterVar.
  3851. Expr *CounterInit = nullptr;
  3852. /// \brief This is step for the #CounterVar used to generate its update:
  3853. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3854. Expr *CounterStep = nullptr;
  3855. /// \brief Should step be subtracted?
  3856. bool Subtract = false;
  3857. /// \brief Source range of the loop init.
  3858. SourceRange InitSrcRange;
  3859. /// \brief Source range of the loop condition.
  3860. SourceRange CondSrcRange;
  3861. /// \brief Source range of the loop increment.
  3862. SourceRange IncSrcRange;
  3863. };
  3864. } // namespace
  3865. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3866. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3867. assert(Init && "Expected loop in canonical form.");
  3868. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3869. if (AssociatedLoops > 0 &&
  3870. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3871. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3872. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3873. if (auto *D = ISC.GetLoopDecl()) {
  3874. auto *VD = dyn_cast<VarDecl>(D);
  3875. if (!VD) {
  3876. if (auto *Private = IsOpenMPCapturedDecl(D))
  3877. VD = Private;
  3878. else {
  3879. auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
  3880. /*WithInit=*/false);
  3881. VD = cast<VarDecl>(Ref->getDecl());
  3882. }
  3883. }
  3884. DSAStack->addLoopControlVariable(D, VD);
  3885. }
  3886. }
  3887. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3888. }
  3889. }
  3890. /// \brief Called on a for stmt to check and extract its iteration space
  3891. /// for further processing (such as collapsing).
  3892. static bool CheckOpenMPIterationSpace(
  3893. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3894. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3895. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3896. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3897. LoopIterationSpace &ResultIterSpace,
  3898. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3899. // OpenMP [2.6, Canonical Loop Form]
  3900. // for (init-expr; test-expr; incr-expr) structured-block
  3901. auto *For = dyn_cast_or_null<ForStmt>(S);
  3902. if (!For) {
  3903. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3904. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3905. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3906. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3907. if (NestedLoopCount > 1) {
  3908. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3909. SemaRef.Diag(DSA.getConstructLoc(),
  3910. diag::note_omp_collapse_ordered_expr)
  3911. << 2 << CollapseLoopCountExpr->getSourceRange()
  3912. << OrderedLoopCountExpr->getSourceRange();
  3913. else if (CollapseLoopCountExpr)
  3914. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3915. diag::note_omp_collapse_ordered_expr)
  3916. << 0 << CollapseLoopCountExpr->getSourceRange();
  3917. else
  3918. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3919. diag::note_omp_collapse_ordered_expr)
  3920. << 1 << OrderedLoopCountExpr->getSourceRange();
  3921. }
  3922. return true;
  3923. }
  3924. assert(For->getBody());
  3925. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3926. // Check init.
  3927. auto Init = For->getInit();
  3928. if (ISC.CheckInit(Init))
  3929. return true;
  3930. bool HasErrors = false;
  3931. // Check loop variable's type.
  3932. if (auto *LCDecl = ISC.GetLoopDecl()) {
  3933. auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
  3934. // OpenMP [2.6, Canonical Loop Form]
  3935. // Var is one of the following:
  3936. // A variable of signed or unsigned integer type.
  3937. // For C++, a variable of a random access iterator type.
  3938. // For C, a variable of a pointer type.
  3939. auto VarType = LCDecl->getType().getNonReferenceType();
  3940. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3941. !VarType->isPointerType() &&
  3942. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3943. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3944. << SemaRef.getLangOpts().CPlusPlus;
  3945. HasErrors = true;
  3946. }
  3947. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  3948. // a Construct
  3949. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3950. // parallel for construct is (are) private.
  3951. // The loop iteration variable in the associated for-loop of a simd
  3952. // construct with just one associated for-loop is linear with a
  3953. // constant-linear-step that is the increment of the associated for-loop.
  3954. // Exclude loop var from the list of variables with implicitly defined data
  3955. // sharing attributes.
  3956. VarsWithImplicitDSA.erase(LCDecl);
  3957. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  3958. // in a Construct, C/C++].
  3959. // The loop iteration variable in the associated for-loop of a simd
  3960. // construct with just one associated for-loop may be listed in a linear
  3961. // clause with a constant-linear-step that is the increment of the
  3962. // associated for-loop.
  3963. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3964. // parallel for construct may be listed in a private or lastprivate clause.
  3965. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  3966. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3967. // declared in the loop and it is predetermined as a private.
  3968. auto PredeterminedCKind =
  3969. isOpenMPSimdDirective(DKind)
  3970. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3971. : OMPC_private;
  3972. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3973. DVar.CKind != PredeterminedCKind) ||
  3974. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3975. isOpenMPDistributeDirective(DKind)) &&
  3976. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3977. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3978. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3979. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3980. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3981. << getOpenMPClauseName(PredeterminedCKind);
  3982. if (DVar.RefExpr == nullptr)
  3983. DVar.CKind = PredeterminedCKind;
  3984. ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  3985. HasErrors = true;
  3986. } else if (LoopDeclRefExpr != nullptr) {
  3987. // Make the loop iteration variable private (for worksharing constructs),
  3988. // linear (for simd directives with the only one associated loop) or
  3989. // lastprivate (for simd directives with several collapsed or ordered
  3990. // loops).
  3991. if (DVar.CKind == OMPC_unknown)
  3992. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  3993. [](OpenMPDirectiveKind) -> bool { return true; },
  3994. /*FromParent=*/false);
  3995. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  3996. }
  3997. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3998. // Check test-expr.
  3999. HasErrors |= ISC.CheckCond(For->getCond());
  4000. // Check incr-expr.
  4001. HasErrors |= ISC.CheckInc(For->getInc());
  4002. }
  4003. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4004. return HasErrors;
  4005. // Build the loop's iteration space representation.
  4006. ResultIterSpace.PreCond =
  4007. ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4008. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  4009. DSA.getCurScope(),
  4010. (isOpenMPWorksharingDirective(DKind) ||
  4011. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4012. Captures);
  4013. ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
  4014. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  4015. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  4016. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  4017. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  4018. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  4019. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  4020. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  4021. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4022. ResultIterSpace.NumIterations == nullptr ||
  4023. ResultIterSpace.CounterVar == nullptr ||
  4024. ResultIterSpace.PrivateCounterVar == nullptr ||
  4025. ResultIterSpace.CounterInit == nullptr ||
  4026. ResultIterSpace.CounterStep == nullptr);
  4027. return HasErrors;
  4028. }
  4029. /// \brief Build 'VarRef = Start.
  4030. static ExprResult
  4031. BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4032. ExprResult Start,
  4033. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4034. // Build 'VarRef = Start.
  4035. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4036. if (!NewStart.isUsable())
  4037. return ExprError();
  4038. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4039. VarRef.get()->getType())) {
  4040. NewStart = SemaRef.PerformImplicitConversion(
  4041. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4042. /*AllowExplicit=*/true);
  4043. if (!NewStart.isUsable())
  4044. return ExprError();
  4045. }
  4046. auto Init =
  4047. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4048. return Init;
  4049. }
  4050. /// \brief Build 'VarRef = Start + Iter * Step'.
  4051. static ExprResult
  4052. BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
  4053. ExprResult VarRef, ExprResult Start, ExprResult Iter,
  4054. ExprResult Step, bool Subtract,
  4055. llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
  4056. // Add parentheses (for debugging purposes only).
  4057. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4058. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4059. !Step.isUsable())
  4060. return ExprError();
  4061. ExprResult NewStep = Step;
  4062. if (Captures)
  4063. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4064. if (NewStep.isInvalid())
  4065. return ExprError();
  4066. ExprResult Update =
  4067. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4068. if (!Update.isUsable())
  4069. return ExprError();
  4070. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4071. // 'VarRef = Start (+|-) Iter * Step'.
  4072. ExprResult NewStart = Start;
  4073. if (Captures)
  4074. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4075. if (NewStart.isInvalid())
  4076. return ExprError();
  4077. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4078. ExprResult SavedUpdate = Update;
  4079. ExprResult UpdateVal;
  4080. if (VarRef.get()->getType()->isOverloadableType() ||
  4081. NewStart.get()->getType()->isOverloadableType() ||
  4082. Update.get()->getType()->isOverloadableType()) {
  4083. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4084. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4085. Update =
  4086. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4087. if (Update.isUsable()) {
  4088. UpdateVal =
  4089. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4090. VarRef.get(), SavedUpdate.get());
  4091. if (UpdateVal.isUsable()) {
  4092. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4093. UpdateVal.get());
  4094. }
  4095. }
  4096. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4097. }
  4098. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4099. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4100. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4101. NewStart.get(), SavedUpdate.get());
  4102. if (!Update.isUsable())
  4103. return ExprError();
  4104. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4105. VarRef.get()->getType())) {
  4106. Update = SemaRef.PerformImplicitConversion(
  4107. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4108. if (!Update.isUsable())
  4109. return ExprError();
  4110. }
  4111. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4112. }
  4113. return Update;
  4114. }
  4115. /// \brief Convert integer expression \a E to make it have at least \a Bits
  4116. /// bits.
  4117. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4118. if (E == nullptr)
  4119. return ExprError();
  4120. auto &C = SemaRef.Context;
  4121. QualType OldType = E->getType();
  4122. unsigned HasBits = C.getTypeSize(OldType);
  4123. if (HasBits >= Bits)
  4124. return ExprResult(E);
  4125. // OK to convert to signed, because new type has more bits than old.
  4126. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4127. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4128. true);
  4129. }
  4130. /// \brief Check if the given expression \a E is a constant integer that fits
  4131. /// into \a Bits bits.
  4132. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  4133. if (E == nullptr)
  4134. return false;
  4135. llvm::APSInt Result;
  4136. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4137. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4138. return false;
  4139. }
  4140. /// Build preinits statement for the given declarations.
  4141. static Stmt *buildPreInits(ASTContext &Context,
  4142. MutableArrayRef<Decl *> PreInits) {
  4143. if (!PreInits.empty()) {
  4144. return new (Context) DeclStmt(
  4145. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4146. SourceLocation(), SourceLocation());
  4147. }
  4148. return nullptr;
  4149. }
  4150. /// Build preinits statement for the given declarations.
  4151. static Stmt *
  4152. buildPreInits(ASTContext &Context,
  4153. const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4154. if (!Captures.empty()) {
  4155. SmallVector<Decl *, 16> PreInits;
  4156. for (auto &Pair : Captures)
  4157. PreInits.push_back(Pair.second->getDecl());
  4158. return buildPreInits(Context, PreInits);
  4159. }
  4160. return nullptr;
  4161. }
  4162. /// Build postupdate expression for the given list of postupdates expressions.
  4163. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4164. Expr *PostUpdate = nullptr;
  4165. if (!PostUpdates.empty()) {
  4166. for (auto *E : PostUpdates) {
  4167. Expr *ConvE = S.BuildCStyleCastExpr(
  4168. E->getExprLoc(),
  4169. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4170. E->getExprLoc(), E)
  4171. .get();
  4172. PostUpdate = PostUpdate
  4173. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4174. PostUpdate, ConvE)
  4175. .get()
  4176. : ConvE;
  4177. }
  4178. }
  4179. return PostUpdate;
  4180. }
  4181. /// \brief Called on a for stmt to check itself and nested loops (if any).
  4182. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4183. /// number of collapsed loops otherwise.
  4184. static unsigned
  4185. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4186. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4187. DSAStackTy &DSA,
  4188. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  4189. OMPLoopDirective::HelperExprs &Built) {
  4190. unsigned NestedLoopCount = 1;
  4191. if (CollapseLoopCountExpr) {
  4192. // Found 'collapse' clause - calculate collapse number.
  4193. llvm::APSInt Result;
  4194. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4195. NestedLoopCount = Result.getLimitedValue();
  4196. }
  4197. if (OrderedLoopCountExpr) {
  4198. // Found 'ordered' clause - calculate collapse number.
  4199. llvm::APSInt Result;
  4200. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4201. if (Result.getLimitedValue() < NestedLoopCount) {
  4202. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4203. diag::err_omp_wrong_ordered_loop_count)
  4204. << OrderedLoopCountExpr->getSourceRange();
  4205. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4206. diag::note_collapse_loop_count)
  4207. << CollapseLoopCountExpr->getSourceRange();
  4208. }
  4209. NestedLoopCount = Result.getLimitedValue();
  4210. }
  4211. }
  4212. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4213. // 'for simd', etc.).
  4214. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  4215. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4216. IterSpaces.resize(NestedLoopCount);
  4217. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4218. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4219. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  4220. NestedLoopCount, CollapseLoopCountExpr,
  4221. OrderedLoopCountExpr, VarsWithImplicitDSA,
  4222. IterSpaces[Cnt], Captures))
  4223. return 0;
  4224. // Move on to the next nested for loop, or to the loop body.
  4225. // OpenMP [2.8.1, simd construct, Restrictions]
  4226. // All loops associated with the construct must be perfectly nested; that
  4227. // is, there must be no intervening code nor any OpenMP directive between
  4228. // any two loops.
  4229. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4230. }
  4231. Built.clear(/* size */ NestedLoopCount);
  4232. if (SemaRef.CurContext->isDependentContext())
  4233. return NestedLoopCount;
  4234. // An example of what is generated for the following code:
  4235. //
  4236. // #pragma omp simd collapse(2) ordered(2)
  4237. // for (i = 0; i < NI; ++i)
  4238. // for (k = 0; k < NK; ++k)
  4239. // for (j = J0; j < NJ; j+=2) {
  4240. // <loop body>
  4241. // }
  4242. //
  4243. // We generate the code below.
  4244. // Note: the loop body may be outlined in CodeGen.
  4245. // Note: some counters may be C++ classes, operator- is used to find number of
  4246. // iterations and operator+= to calculate counter value.
  4247. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4248. // or i64 is currently supported).
  4249. //
  4250. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4251. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4252. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4253. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4254. // // similar updates for vars in clauses (e.g. 'linear')
  4255. // <loop body (using local i and j)>
  4256. // }
  4257. // i = NI; // assign final values of counters
  4258. // j = NJ;
  4259. //
  4260. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4261. // the iteration counts of the collapsed for loops.
  4262. // Precondition tests if there is at least one iteration (all conditions are
  4263. // true).
  4264. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4265. auto N0 = IterSpaces[0].NumIterations;
  4266. ExprResult LastIteration32 = WidenIterationCount(
  4267. 32 /* Bits */, SemaRef
  4268. .PerformImplicitConversion(
  4269. N0->IgnoreImpCasts(), N0->getType(),
  4270. Sema::AA_Converting, /*AllowExplicit=*/true)
  4271. .get(),
  4272. SemaRef);
  4273. ExprResult LastIteration64 = WidenIterationCount(
  4274. 64 /* Bits */, SemaRef
  4275. .PerformImplicitConversion(
  4276. N0->IgnoreImpCasts(), N0->getType(),
  4277. Sema::AA_Converting, /*AllowExplicit=*/true)
  4278. .get(),
  4279. SemaRef);
  4280. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4281. return NestedLoopCount;
  4282. auto &C = SemaRef.Context;
  4283. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4284. Scope *CurScope = DSA.getCurScope();
  4285. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4286. if (PreCond.isUsable()) {
  4287. PreCond =
  4288. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4289. PreCond.get(), IterSpaces[Cnt].PreCond);
  4290. }
  4291. auto N = IterSpaces[Cnt].NumIterations;
  4292. SourceLocation Loc = N->getExprLoc();
  4293. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4294. if (LastIteration32.isUsable())
  4295. LastIteration32 = SemaRef.BuildBinOp(
  4296. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4297. SemaRef
  4298. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4299. Sema::AA_Converting,
  4300. /*AllowExplicit=*/true)
  4301. .get());
  4302. if (LastIteration64.isUsable())
  4303. LastIteration64 = SemaRef.BuildBinOp(
  4304. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4305. SemaRef
  4306. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4307. Sema::AA_Converting,
  4308. /*AllowExplicit=*/true)
  4309. .get());
  4310. }
  4311. // Choose either the 32-bit or 64-bit version.
  4312. ExprResult LastIteration = LastIteration64;
  4313. if (LastIteration32.isUsable() &&
  4314. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4315. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4316. FitsInto(
  4317. 32 /* Bits */,
  4318. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4319. LastIteration64.get(), SemaRef)))
  4320. LastIteration = LastIteration32;
  4321. QualType VType = LastIteration.get()->getType();
  4322. QualType RealVType = VType;
  4323. QualType StrideVType = VType;
  4324. if (isOpenMPTaskLoopDirective(DKind)) {
  4325. VType =
  4326. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4327. StrideVType =
  4328. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4329. }
  4330. if (!LastIteration.isUsable())
  4331. return 0;
  4332. // Save the number of iterations.
  4333. ExprResult NumIterations = LastIteration;
  4334. {
  4335. LastIteration = SemaRef.BuildBinOp(
  4336. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4337. LastIteration.get(),
  4338. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4339. if (!LastIteration.isUsable())
  4340. return 0;
  4341. }
  4342. // Calculate the last iteration number beforehand instead of doing this on
  4343. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4344. llvm::APSInt Result;
  4345. bool IsConstant =
  4346. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4347. ExprResult CalcLastIteration;
  4348. if (!IsConstant) {
  4349. ExprResult SaveRef =
  4350. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4351. LastIteration = SaveRef;
  4352. // Prepare SaveRef + 1.
  4353. NumIterations = SemaRef.BuildBinOp(
  4354. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4355. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4356. if (!NumIterations.isUsable())
  4357. return 0;
  4358. }
  4359. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4360. // Build variables passed into runtime, necessary for worksharing directives.
  4361. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4362. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4363. isOpenMPDistributeDirective(DKind)) {
  4364. // Lower bound variable, initialized with zero.
  4365. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4366. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4367. SemaRef.AddInitializerToDecl(LBDecl,
  4368. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4369. /*DirectInit*/ false);
  4370. // Upper bound variable, initialized with last iteration number.
  4371. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4372. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4373. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4374. /*DirectInit*/ false);
  4375. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4376. // This will be used to implement clause 'lastprivate'.
  4377. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4378. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4379. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4380. SemaRef.AddInitializerToDecl(ILDecl,
  4381. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4382. /*DirectInit*/ false);
  4383. // Stride variable returned by runtime (we initialize it to 1 by default).
  4384. VarDecl *STDecl =
  4385. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4386. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4387. SemaRef.AddInitializerToDecl(STDecl,
  4388. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4389. /*DirectInit*/ false);
  4390. // Build expression: UB = min(UB, LastIteration)
  4391. // It is necessary for CodeGen of directives with static scheduling.
  4392. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4393. UB.get(), LastIteration.get());
  4394. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4395. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  4396. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4397. CondOp.get());
  4398. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4399. // If we have a combined directive that combines 'distribute', 'for' or
  4400. // 'simd' we need to be able to access the bounds of the schedule of the
  4401. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4402. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4403. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4404. // Lower bound variable, initialized with zero.
  4405. VarDecl *CombLBDecl =
  4406. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4407. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4408. SemaRef.AddInitializerToDecl(
  4409. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4410. /*DirectInit*/ false);
  4411. // Upper bound variable, initialized with last iteration number.
  4412. VarDecl *CombUBDecl =
  4413. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4414. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4415. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4416. /*DirectInit*/ false);
  4417. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4418. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4419. ExprResult CombCondOp =
  4420. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4421. LastIteration.get(), CombUB.get());
  4422. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4423. CombCondOp.get());
  4424. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4425. auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4426. // We expect to have at least 2 more parameters than the 'parallel'
  4427. // directive does - the lower and upper bounds of the previous schedule.
  4428. assert(CD->getNumParams() >= 4 &&
  4429. "Unexpected number of parameters in loop combined directive");
  4430. // Set the proper type for the bounds given what we learned from the
  4431. // enclosed loops.
  4432. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4433. auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4434. // Previous lower and upper bounds are obtained from the region
  4435. // parameters.
  4436. PrevLB =
  4437. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  4438. PrevUB =
  4439. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  4440. }
  4441. }
  4442. // Build the iteration variable and its initialization before loop.
  4443. ExprResult IV;
  4444. ExprResult Init, CombInit;
  4445. {
  4446. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  4447. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  4448. Expr *RHS =
  4449. (isOpenMPWorksharingDirective(DKind) ||
  4450. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4451. ? LB.get()
  4452. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4453. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  4454. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  4455. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4456. Expr *CombRHS =
  4457. (isOpenMPWorksharingDirective(DKind) ||
  4458. isOpenMPTaskLoopDirective(DKind) ||
  4459. isOpenMPDistributeDirective(DKind))
  4460. ? CombLB.get()
  4461. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4462. CombInit =
  4463. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  4464. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  4465. }
  4466. }
  4467. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  4468. SourceLocation CondLoc;
  4469. ExprResult Cond =
  4470. (isOpenMPWorksharingDirective(DKind) ||
  4471. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4472. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  4473. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  4474. NumIterations.get());
  4475. ExprResult CombCond;
  4476. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4477. CombCond =
  4478. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  4479. }
  4480. // Loop increment (IV = IV + 1)
  4481. SourceLocation IncLoc;
  4482. ExprResult Inc =
  4483. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  4484. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  4485. if (!Inc.isUsable())
  4486. return 0;
  4487. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  4488. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  4489. if (!Inc.isUsable())
  4490. return 0;
  4491. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  4492. // Used for directives with static scheduling.
  4493. // In combined construct, add combined version that use CombLB and CombUB
  4494. // base variables for the update
  4495. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  4496. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4497. isOpenMPDistributeDirective(DKind)) {
  4498. // LB + ST
  4499. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  4500. if (!NextLB.isUsable())
  4501. return 0;
  4502. // LB = LB + ST
  4503. NextLB =
  4504. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4505. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4506. if (!NextLB.isUsable())
  4507. return 0;
  4508. // UB + ST
  4509. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4510. if (!NextUB.isUsable())
  4511. return 0;
  4512. // UB = UB + ST
  4513. NextUB =
  4514. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4515. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4516. if (!NextUB.isUsable())
  4517. return 0;
  4518. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4519. CombNextLB =
  4520. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  4521. if (!NextLB.isUsable())
  4522. return 0;
  4523. // LB = LB + ST
  4524. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  4525. CombNextLB.get());
  4526. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  4527. if (!CombNextLB.isUsable())
  4528. return 0;
  4529. // UB + ST
  4530. CombNextUB =
  4531. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  4532. if (!CombNextUB.isUsable())
  4533. return 0;
  4534. // UB = UB + ST
  4535. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  4536. CombNextUB.get());
  4537. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  4538. if (!CombNextUB.isUsable())
  4539. return 0;
  4540. }
  4541. }
  4542. // Create increment expression for distribute loop when combined in a same
  4543. // directive with for as IV = IV + ST; ensure upper bound expression based
  4544. // on PrevUB instead of NumIterations - used to implement 'for' when found
  4545. // in combination with 'distribute', like in 'distribute parallel for'
  4546. SourceLocation DistIncLoc;
  4547. ExprResult DistCond, DistInc, PrevEUB;
  4548. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4549. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  4550. assert(DistCond.isUsable() && "distribute cond expr was not built");
  4551. DistInc =
  4552. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  4553. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4554. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  4555. DistInc.get());
  4556. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  4557. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4558. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  4559. // construct
  4560. SourceLocation DistEUBLoc;
  4561. ExprResult IsUBGreater =
  4562. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  4563. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4564. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  4565. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  4566. CondOp.get());
  4567. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  4568. }
  4569. // Build updates and final values of the loop counters.
  4570. bool HasErrors = false;
  4571. Built.Counters.resize(NestedLoopCount);
  4572. Built.Inits.resize(NestedLoopCount);
  4573. Built.Updates.resize(NestedLoopCount);
  4574. Built.Finals.resize(NestedLoopCount);
  4575. SmallVector<Expr *, 4> LoopMultipliers;
  4576. {
  4577. ExprResult Div;
  4578. // Go from inner nested loop to outer.
  4579. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4580. LoopIterationSpace &IS = IterSpaces[Cnt];
  4581. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4582. // Build: Iter = (IV / Div) % IS.NumIters
  4583. // where Div is product of previous iterations' IS.NumIters.
  4584. ExprResult Iter;
  4585. if (Div.isUsable()) {
  4586. Iter =
  4587. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4588. } else {
  4589. Iter = IV;
  4590. assert((Cnt == (int)NestedLoopCount - 1) &&
  4591. "unusable div expected on first iteration only");
  4592. }
  4593. if (Cnt != 0 && Iter.isUsable())
  4594. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4595. IS.NumIterations);
  4596. if (!Iter.isUsable()) {
  4597. HasErrors = true;
  4598. break;
  4599. }
  4600. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4601. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  4602. auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
  4603. IS.CounterVar->getExprLoc(),
  4604. /*RefersToCapture=*/true);
  4605. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4606. IS.CounterInit, Captures);
  4607. if (!Init.isUsable()) {
  4608. HasErrors = true;
  4609. break;
  4610. }
  4611. ExprResult Update = BuildCounterUpdate(
  4612. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  4613. IS.CounterStep, IS.Subtract, &Captures);
  4614. if (!Update.isUsable()) {
  4615. HasErrors = true;
  4616. break;
  4617. }
  4618. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4619. ExprResult Final = BuildCounterUpdate(
  4620. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4621. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  4622. if (!Final.isUsable()) {
  4623. HasErrors = true;
  4624. break;
  4625. }
  4626. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4627. if (Cnt != 0) {
  4628. if (Div.isUnset())
  4629. Div = IS.NumIterations;
  4630. else
  4631. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4632. IS.NumIterations);
  4633. // Add parentheses (for debugging purposes only).
  4634. if (Div.isUsable())
  4635. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  4636. if (!Div.isUsable()) {
  4637. HasErrors = true;
  4638. break;
  4639. }
  4640. LoopMultipliers.push_back(Div.get());
  4641. }
  4642. if (!Update.isUsable() || !Final.isUsable()) {
  4643. HasErrors = true;
  4644. break;
  4645. }
  4646. // Save results
  4647. Built.Counters[Cnt] = IS.CounterVar;
  4648. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4649. Built.Inits[Cnt] = Init.get();
  4650. Built.Updates[Cnt] = Update.get();
  4651. Built.Finals[Cnt] = Final.get();
  4652. }
  4653. }
  4654. if (HasErrors)
  4655. return 0;
  4656. // Save results
  4657. Built.IterationVarRef = IV.get();
  4658. Built.LastIteration = LastIteration.get();
  4659. Built.NumIterations = NumIterations.get();
  4660. Built.CalcLastIteration =
  4661. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4662. Built.PreCond = PreCond.get();
  4663. Built.PreInits = buildPreInits(C, Captures);
  4664. Built.Cond = Cond.get();
  4665. Built.Init = Init.get();
  4666. Built.Inc = Inc.get();
  4667. Built.LB = LB.get();
  4668. Built.UB = UB.get();
  4669. Built.IL = IL.get();
  4670. Built.ST = ST.get();
  4671. Built.EUB = EUB.get();
  4672. Built.NLB = NextLB.get();
  4673. Built.NUB = NextUB.get();
  4674. Built.PrevLB = PrevLB.get();
  4675. Built.PrevUB = PrevUB.get();
  4676. Built.DistInc = DistInc.get();
  4677. Built.PrevEUB = PrevEUB.get();
  4678. Built.DistCombinedFields.LB = CombLB.get();
  4679. Built.DistCombinedFields.UB = CombUB.get();
  4680. Built.DistCombinedFields.EUB = CombEUB.get();
  4681. Built.DistCombinedFields.Init = CombInit.get();
  4682. Built.DistCombinedFields.Cond = CombCond.get();
  4683. Built.DistCombinedFields.NLB = CombNextLB.get();
  4684. Built.DistCombinedFields.NUB = CombNextUB.get();
  4685. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  4686. // Fill data for doacross depend clauses.
  4687. for (auto Pair : DSA.getDoacrossDependClauses()) {
  4688. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4689. Pair.first->setCounterValue(CounterVal);
  4690. else {
  4691. if (NestedLoopCount != Pair.second.size() ||
  4692. NestedLoopCount != LoopMultipliers.size() + 1) {
  4693. // Erroneous case - clause has some problems.
  4694. Pair.first->setCounterValue(CounterVal);
  4695. continue;
  4696. }
  4697. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  4698. auto I = Pair.second.rbegin();
  4699. auto IS = IterSpaces.rbegin();
  4700. auto ILM = LoopMultipliers.rbegin();
  4701. Expr *UpCounterVal = CounterVal;
  4702. Expr *Multiplier = nullptr;
  4703. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4704. if (I->first) {
  4705. assert(IS->CounterStep);
  4706. Expr *NormalizedOffset =
  4707. SemaRef
  4708. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  4709. I->first, IS->CounterStep)
  4710. .get();
  4711. if (Multiplier) {
  4712. NormalizedOffset =
  4713. SemaRef
  4714. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  4715. NormalizedOffset, Multiplier)
  4716. .get();
  4717. }
  4718. assert(I->second == OO_Plus || I->second == OO_Minus);
  4719. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  4720. UpCounterVal = SemaRef
  4721. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  4722. UpCounterVal, NormalizedOffset)
  4723. .get();
  4724. }
  4725. Multiplier = *ILM;
  4726. ++I;
  4727. ++IS;
  4728. ++ILM;
  4729. }
  4730. Pair.first->setCounterValue(UpCounterVal);
  4731. }
  4732. }
  4733. return NestedLoopCount;
  4734. }
  4735. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4736. auto CollapseClauses =
  4737. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4738. if (CollapseClauses.begin() != CollapseClauses.end())
  4739. return (*CollapseClauses.begin())->getNumForLoops();
  4740. return nullptr;
  4741. }
  4742. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4743. auto OrderedClauses =
  4744. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4745. if (OrderedClauses.begin() != OrderedClauses.end())
  4746. return (*OrderedClauses.begin())->getNumForLoops();
  4747. return nullptr;
  4748. }
  4749. static bool checkSimdlenSafelenSpecified(Sema &S,
  4750. const ArrayRef<OMPClause *> Clauses) {
  4751. OMPSafelenClause *Safelen = nullptr;
  4752. OMPSimdlenClause *Simdlen = nullptr;
  4753. for (auto *Clause : Clauses) {
  4754. if (Clause->getClauseKind() == OMPC_safelen)
  4755. Safelen = cast<OMPSafelenClause>(Clause);
  4756. else if (Clause->getClauseKind() == OMPC_simdlen)
  4757. Simdlen = cast<OMPSimdlenClause>(Clause);
  4758. if (Safelen && Simdlen)
  4759. break;
  4760. }
  4761. if (Simdlen && Safelen) {
  4762. llvm::APSInt SimdlenRes, SafelenRes;
  4763. auto SimdlenLength = Simdlen->getSimdlen();
  4764. auto SafelenLength = Safelen->getSafelen();
  4765. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4766. SimdlenLength->isInstantiationDependent() ||
  4767. SimdlenLength->containsUnexpandedParameterPack())
  4768. return false;
  4769. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4770. SafelenLength->isInstantiationDependent() ||
  4771. SafelenLength->containsUnexpandedParameterPack())
  4772. return false;
  4773. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  4774. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  4775. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  4776. // If both simdlen and safelen clauses are specified, the value of the
  4777. // simdlen parameter must be less than or equal to the value of the safelen
  4778. // parameter.
  4779. if (SimdlenRes > SafelenRes) {
  4780. S.Diag(SimdlenLength->getExprLoc(),
  4781. diag::err_omp_wrong_simdlen_safelen_values)
  4782. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  4783. return true;
  4784. }
  4785. }
  4786. return false;
  4787. }
  4788. StmtResult Sema::ActOnOpenMPSimdDirective(
  4789. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4790. SourceLocation EndLoc,
  4791. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4792. if (!AStmt)
  4793. return StmtError();
  4794. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4795. OMPLoopDirective::HelperExprs B;
  4796. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4797. // define the nested loops number.
  4798. unsigned NestedLoopCount = CheckOpenMPLoop(
  4799. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4800. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4801. if (NestedLoopCount == 0)
  4802. return StmtError();
  4803. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4804. "omp simd loop exprs were not built");
  4805. if (!CurContext->isDependentContext()) {
  4806. // Finalize the clauses that need pre-built expressions for CodeGen.
  4807. for (auto C : Clauses) {
  4808. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4809. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4810. B.NumIterations, *this, CurScope,
  4811. DSAStack))
  4812. return StmtError();
  4813. }
  4814. }
  4815. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4816. return StmtError();
  4817. getCurFunction()->setHasBranchProtectedScope();
  4818. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4819. Clauses, AStmt, B);
  4820. }
  4821. StmtResult Sema::ActOnOpenMPForDirective(
  4822. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4823. SourceLocation EndLoc,
  4824. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4825. if (!AStmt)
  4826. return StmtError();
  4827. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4828. OMPLoopDirective::HelperExprs B;
  4829. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4830. // define the nested loops number.
  4831. unsigned NestedLoopCount = CheckOpenMPLoop(
  4832. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4833. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4834. if (NestedLoopCount == 0)
  4835. return StmtError();
  4836. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4837. "omp for loop exprs were not built");
  4838. if (!CurContext->isDependentContext()) {
  4839. // Finalize the clauses that need pre-built expressions for CodeGen.
  4840. for (auto C : Clauses) {
  4841. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4842. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4843. B.NumIterations, *this, CurScope,
  4844. DSAStack))
  4845. return StmtError();
  4846. }
  4847. }
  4848. getCurFunction()->setHasBranchProtectedScope();
  4849. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4850. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4851. }
  4852. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4853. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4854. SourceLocation EndLoc,
  4855. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4856. if (!AStmt)
  4857. return StmtError();
  4858. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4859. OMPLoopDirective::HelperExprs B;
  4860. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4861. // define the nested loops number.
  4862. unsigned NestedLoopCount =
  4863. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4864. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4865. VarsWithImplicitDSA, B);
  4866. if (NestedLoopCount == 0)
  4867. return StmtError();
  4868. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4869. "omp for simd loop exprs were not built");
  4870. if (!CurContext->isDependentContext()) {
  4871. // Finalize the clauses that need pre-built expressions for CodeGen.
  4872. for (auto C : Clauses) {
  4873. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4874. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4875. B.NumIterations, *this, CurScope,
  4876. DSAStack))
  4877. return StmtError();
  4878. }
  4879. }
  4880. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4881. return StmtError();
  4882. getCurFunction()->setHasBranchProtectedScope();
  4883. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4884. Clauses, AStmt, B);
  4885. }
  4886. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4887. Stmt *AStmt,
  4888. SourceLocation StartLoc,
  4889. SourceLocation EndLoc) {
  4890. if (!AStmt)
  4891. return StmtError();
  4892. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4893. auto BaseStmt = AStmt;
  4894. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4895. BaseStmt = CS->getCapturedStmt();
  4896. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4897. auto S = C->children();
  4898. if (S.begin() == S.end())
  4899. return StmtError();
  4900. // All associated statements must be '#pragma omp section' except for
  4901. // the first one.
  4902. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4903. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4904. if (SectionStmt)
  4905. Diag(SectionStmt->getLocStart(),
  4906. diag::err_omp_sections_substmt_not_section);
  4907. return StmtError();
  4908. }
  4909. cast<OMPSectionDirective>(SectionStmt)
  4910. ->setHasCancel(DSAStack->isCancelRegion());
  4911. }
  4912. } else {
  4913. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4914. return StmtError();
  4915. }
  4916. getCurFunction()->setHasBranchProtectedScope();
  4917. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4918. DSAStack->isCancelRegion());
  4919. }
  4920. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4921. SourceLocation StartLoc,
  4922. SourceLocation EndLoc) {
  4923. if (!AStmt)
  4924. return StmtError();
  4925. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4926. getCurFunction()->setHasBranchProtectedScope();
  4927. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4928. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4929. DSAStack->isCancelRegion());
  4930. }
  4931. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4932. Stmt *AStmt,
  4933. SourceLocation StartLoc,
  4934. SourceLocation EndLoc) {
  4935. if (!AStmt)
  4936. return StmtError();
  4937. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4938. getCurFunction()->setHasBranchProtectedScope();
  4939. // OpenMP [2.7.3, single Construct, Restrictions]
  4940. // The copyprivate clause must not be used with the nowait clause.
  4941. OMPClause *Nowait = nullptr;
  4942. OMPClause *Copyprivate = nullptr;
  4943. for (auto *Clause : Clauses) {
  4944. if (Clause->getClauseKind() == OMPC_nowait)
  4945. Nowait = Clause;
  4946. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4947. Copyprivate = Clause;
  4948. if (Copyprivate && Nowait) {
  4949. Diag(Copyprivate->getLocStart(),
  4950. diag::err_omp_single_copyprivate_with_nowait);
  4951. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4952. return StmtError();
  4953. }
  4954. }
  4955. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4956. }
  4957. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4958. SourceLocation StartLoc,
  4959. SourceLocation EndLoc) {
  4960. if (!AStmt)
  4961. return StmtError();
  4962. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4963. getCurFunction()->setHasBranchProtectedScope();
  4964. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4965. }
  4966. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4967. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4968. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4969. if (!AStmt)
  4970. return StmtError();
  4971. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4972. bool ErrorFound = false;
  4973. llvm::APSInt Hint;
  4974. SourceLocation HintLoc;
  4975. bool DependentHint = false;
  4976. for (auto *C : Clauses) {
  4977. if (C->getClauseKind() == OMPC_hint) {
  4978. if (!DirName.getName()) {
  4979. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4980. ErrorFound = true;
  4981. }
  4982. Expr *E = cast<OMPHintClause>(C)->getHint();
  4983. if (E->isTypeDependent() || E->isValueDependent() ||
  4984. E->isInstantiationDependent())
  4985. DependentHint = true;
  4986. else {
  4987. Hint = E->EvaluateKnownConstInt(Context);
  4988. HintLoc = C->getLocStart();
  4989. }
  4990. }
  4991. }
  4992. if (ErrorFound)
  4993. return StmtError();
  4994. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4995. if (Pair.first && DirName.getName() && !DependentHint) {
  4996. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4997. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4998. if (HintLoc.isValid()) {
  4999. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5000. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5001. } else
  5002. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5003. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5004. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  5005. << 1
  5006. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5007. /*Radix=*/10, /*Signed=*/false);
  5008. } else
  5009. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  5010. }
  5011. }
  5012. getCurFunction()->setHasBranchProtectedScope();
  5013. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5014. Clauses, AStmt);
  5015. if (!Pair.first && DirName.getName() && !DependentHint)
  5016. DSAStack->addCriticalWithHint(Dir, Hint);
  5017. return Dir;
  5018. }
  5019. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5020. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5021. SourceLocation EndLoc,
  5022. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5023. if (!AStmt)
  5024. return StmtError();
  5025. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5026. // 1.2.2 OpenMP Language Terminology
  5027. // Structured block - An executable statement with a single entry at the
  5028. // top and a single exit at the bottom.
  5029. // The point of exit cannot be a branch out of the structured block.
  5030. // longjmp() and throw() must not violate the entry/exit criteria.
  5031. CS->getCapturedDecl()->setNothrow();
  5032. OMPLoopDirective::HelperExprs B;
  5033. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5034. // define the nested loops number.
  5035. unsigned NestedLoopCount =
  5036. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5037. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5038. VarsWithImplicitDSA, B);
  5039. if (NestedLoopCount == 0)
  5040. return StmtError();
  5041. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5042. "omp parallel for loop exprs were not built");
  5043. if (!CurContext->isDependentContext()) {
  5044. // Finalize the clauses that need pre-built expressions for CodeGen.
  5045. for (auto C : Clauses) {
  5046. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5047. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5048. B.NumIterations, *this, CurScope,
  5049. DSAStack))
  5050. return StmtError();
  5051. }
  5052. }
  5053. getCurFunction()->setHasBranchProtectedScope();
  5054. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5055. NestedLoopCount, Clauses, AStmt, B,
  5056. DSAStack->isCancelRegion());
  5057. }
  5058. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5059. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5060. SourceLocation EndLoc,
  5061. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5062. if (!AStmt)
  5063. return StmtError();
  5064. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5065. // 1.2.2 OpenMP Language Terminology
  5066. // Structured block - An executable statement with a single entry at the
  5067. // top and a single exit at the bottom.
  5068. // The point of exit cannot be a branch out of the structured block.
  5069. // longjmp() and throw() must not violate the entry/exit criteria.
  5070. CS->getCapturedDecl()->setNothrow();
  5071. OMPLoopDirective::HelperExprs B;
  5072. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5073. // define the nested loops number.
  5074. unsigned NestedLoopCount =
  5075. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5076. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5077. VarsWithImplicitDSA, B);
  5078. if (NestedLoopCount == 0)
  5079. return StmtError();
  5080. if (!CurContext->isDependentContext()) {
  5081. // Finalize the clauses that need pre-built expressions for CodeGen.
  5082. for (auto C : Clauses) {
  5083. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5084. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5085. B.NumIterations, *this, CurScope,
  5086. DSAStack))
  5087. return StmtError();
  5088. }
  5089. }
  5090. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5091. return StmtError();
  5092. getCurFunction()->setHasBranchProtectedScope();
  5093. return OMPParallelForSimdDirective::Create(
  5094. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5095. }
  5096. StmtResult
  5097. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5098. Stmt *AStmt, SourceLocation StartLoc,
  5099. SourceLocation EndLoc) {
  5100. if (!AStmt)
  5101. return StmtError();
  5102. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5103. auto BaseStmt = AStmt;
  5104. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5105. BaseStmt = CS->getCapturedStmt();
  5106. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5107. auto S = C->children();
  5108. if (S.begin() == S.end())
  5109. return StmtError();
  5110. // All associated statements must be '#pragma omp section' except for
  5111. // the first one.
  5112. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5113. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5114. if (SectionStmt)
  5115. Diag(SectionStmt->getLocStart(),
  5116. diag::err_omp_parallel_sections_substmt_not_section);
  5117. return StmtError();
  5118. }
  5119. cast<OMPSectionDirective>(SectionStmt)
  5120. ->setHasCancel(DSAStack->isCancelRegion());
  5121. }
  5122. } else {
  5123. Diag(AStmt->getLocStart(),
  5124. diag::err_omp_parallel_sections_not_compound_stmt);
  5125. return StmtError();
  5126. }
  5127. getCurFunction()->setHasBranchProtectedScope();
  5128. return OMPParallelSectionsDirective::Create(
  5129. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5130. }
  5131. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5132. Stmt *AStmt, SourceLocation StartLoc,
  5133. SourceLocation EndLoc) {
  5134. if (!AStmt)
  5135. return StmtError();
  5136. auto *CS = cast<CapturedStmt>(AStmt);
  5137. // 1.2.2 OpenMP Language Terminology
  5138. // Structured block - An executable statement with a single entry at the
  5139. // top and a single exit at the bottom.
  5140. // The point of exit cannot be a branch out of the structured block.
  5141. // longjmp() and throw() must not violate the entry/exit criteria.
  5142. CS->getCapturedDecl()->setNothrow();
  5143. getCurFunction()->setHasBranchProtectedScope();
  5144. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5145. DSAStack->isCancelRegion());
  5146. }
  5147. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5148. SourceLocation EndLoc) {
  5149. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5150. }
  5151. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5152. SourceLocation EndLoc) {
  5153. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5154. }
  5155. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5156. SourceLocation EndLoc) {
  5157. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5158. }
  5159. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5160. Stmt *AStmt,
  5161. SourceLocation StartLoc,
  5162. SourceLocation EndLoc) {
  5163. if (!AStmt)
  5164. return StmtError();
  5165. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5166. getCurFunction()->setHasBranchProtectedScope();
  5167. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5168. AStmt,
  5169. DSAStack->getTaskgroupReductionRef());
  5170. }
  5171. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5172. SourceLocation StartLoc,
  5173. SourceLocation EndLoc) {
  5174. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5175. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5176. }
  5177. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5178. Stmt *AStmt,
  5179. SourceLocation StartLoc,
  5180. SourceLocation EndLoc) {
  5181. OMPClause *DependFound = nullptr;
  5182. OMPClause *DependSourceClause = nullptr;
  5183. OMPClause *DependSinkClause = nullptr;
  5184. bool ErrorFound = false;
  5185. OMPThreadsClause *TC = nullptr;
  5186. OMPSIMDClause *SC = nullptr;
  5187. for (auto *C : Clauses) {
  5188. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5189. DependFound = C;
  5190. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5191. if (DependSourceClause) {
  5192. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  5193. << getOpenMPDirectiveName(OMPD_ordered)
  5194. << getOpenMPClauseName(OMPC_depend) << 2;
  5195. ErrorFound = true;
  5196. } else
  5197. DependSourceClause = C;
  5198. if (DependSinkClause) {
  5199. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5200. << 0;
  5201. ErrorFound = true;
  5202. }
  5203. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5204. if (DependSourceClause) {
  5205. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5206. << 1;
  5207. ErrorFound = true;
  5208. }
  5209. DependSinkClause = C;
  5210. }
  5211. } else if (C->getClauseKind() == OMPC_threads)
  5212. TC = cast<OMPThreadsClause>(C);
  5213. else if (C->getClauseKind() == OMPC_simd)
  5214. SC = cast<OMPSIMDClause>(C);
  5215. }
  5216. if (!ErrorFound && !SC &&
  5217. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5218. // OpenMP [2.8.1,simd Construct, Restrictions]
  5219. // An ordered construct with the simd clause is the only OpenMP construct
  5220. // that can appear in the simd region.
  5221. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5222. ErrorFound = true;
  5223. } else if (DependFound && (TC || SC)) {
  5224. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  5225. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5226. ErrorFound = true;
  5227. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  5228. Diag(DependFound->getLocStart(),
  5229. diag::err_omp_ordered_directive_without_param);
  5230. ErrorFound = true;
  5231. } else if (TC || Clauses.empty()) {
  5232. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  5233. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  5234. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5235. << (TC != nullptr);
  5236. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  5237. ErrorFound = true;
  5238. }
  5239. }
  5240. if ((!AStmt && !DependFound) || ErrorFound)
  5241. return StmtError();
  5242. if (AStmt) {
  5243. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5244. getCurFunction()->setHasBranchProtectedScope();
  5245. }
  5246. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5247. }
  5248. namespace {
  5249. /// \brief Helper class for checking expression in 'omp atomic [update]'
  5250. /// construct.
  5251. class OpenMPAtomicUpdateChecker {
  5252. /// \brief Error results for atomic update expressions.
  5253. enum ExprAnalysisErrorCode {
  5254. /// \brief A statement is not an expression statement.
  5255. NotAnExpression,
  5256. /// \brief Expression is not builtin binary or unary operation.
  5257. NotABinaryOrUnaryExpression,
  5258. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  5259. NotAnUnaryIncDecExpression,
  5260. /// \brief An expression is not of scalar type.
  5261. NotAScalarType,
  5262. /// \brief A binary operation is not an assignment operation.
  5263. NotAnAssignmentOp,
  5264. /// \brief RHS part of the binary operation is not a binary expression.
  5265. NotABinaryExpression,
  5266. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  5267. /// expression.
  5268. NotABinaryOperator,
  5269. /// \brief RHS binary operation does not have reference to the updated LHS
  5270. /// part.
  5271. NotAnUpdateExpression,
  5272. /// \brief No errors is found.
  5273. NoError
  5274. };
  5275. /// \brief Reference to Sema.
  5276. Sema &SemaRef;
  5277. /// \brief A location for note diagnostics (when error is found).
  5278. SourceLocation NoteLoc;
  5279. /// \brief 'x' lvalue part of the source atomic expression.
  5280. Expr *X;
  5281. /// \brief 'expr' rvalue part of the source atomic expression.
  5282. Expr *E;
  5283. /// \brief Helper expression of the form
  5284. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5285. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5286. Expr *UpdateExpr;
  5287. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  5288. /// important for non-associative operations.
  5289. bool IsXLHSInRHSPart;
  5290. BinaryOperatorKind Op;
  5291. SourceLocation OpLoc;
  5292. /// \brief true if the source expression is a postfix unary operation, false
  5293. /// if it is a prefix unary operation.
  5294. bool IsPostfixUpdate;
  5295. public:
  5296. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5297. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5298. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5299. /// \brief Check specified statement that it is suitable for 'atomic update'
  5300. /// constructs and extract 'x', 'expr' and Operation from the original
  5301. /// expression. If DiagId and NoteId == 0, then only check is performed
  5302. /// without error notification.
  5303. /// \param DiagId Diagnostic which should be emitted if error is found.
  5304. /// \param NoteId Diagnostic note for the main error message.
  5305. /// \return true if statement is not an update expression, false otherwise.
  5306. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5307. /// \brief Return the 'x' lvalue part of the source atomic expression.
  5308. Expr *getX() const { return X; }
  5309. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  5310. Expr *getExpr() const { return E; }
  5311. /// \brief Return the update expression used in calculation of the updated
  5312. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5313. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5314. Expr *getUpdateExpr() const { return UpdateExpr; }
  5315. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  5316. /// false otherwise.
  5317. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5318. /// \brief true if the source expression is a postfix unary operation, false
  5319. /// if it is a prefix unary operation.
  5320. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5321. private:
  5322. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5323. unsigned NoteId = 0);
  5324. };
  5325. } // namespace
  5326. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5327. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5328. ExprAnalysisErrorCode ErrorFound = NoError;
  5329. SourceLocation ErrorLoc, NoteLoc;
  5330. SourceRange ErrorRange, NoteRange;
  5331. // Allowed constructs are:
  5332. // x = x binop expr;
  5333. // x = expr binop x;
  5334. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5335. X = AtomicBinOp->getLHS();
  5336. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5337. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5338. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5339. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5340. AtomicInnerBinOp->isBitwiseOp()) {
  5341. Op = AtomicInnerBinOp->getOpcode();
  5342. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5343. auto *LHS = AtomicInnerBinOp->getLHS();
  5344. auto *RHS = AtomicInnerBinOp->getRHS();
  5345. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5346. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5347. /*Canonical=*/true);
  5348. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5349. /*Canonical=*/true);
  5350. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5351. /*Canonical=*/true);
  5352. if (XId == LHSId) {
  5353. E = RHS;
  5354. IsXLHSInRHSPart = true;
  5355. } else if (XId == RHSId) {
  5356. E = LHS;
  5357. IsXLHSInRHSPart = false;
  5358. } else {
  5359. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5360. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5361. NoteLoc = X->getExprLoc();
  5362. NoteRange = X->getSourceRange();
  5363. ErrorFound = NotAnUpdateExpression;
  5364. }
  5365. } else {
  5366. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5367. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5368. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5369. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5370. ErrorFound = NotABinaryOperator;
  5371. }
  5372. } else {
  5373. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5374. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5375. ErrorFound = NotABinaryExpression;
  5376. }
  5377. } else {
  5378. ErrorLoc = AtomicBinOp->getExprLoc();
  5379. ErrorRange = AtomicBinOp->getSourceRange();
  5380. NoteLoc = AtomicBinOp->getOperatorLoc();
  5381. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5382. ErrorFound = NotAnAssignmentOp;
  5383. }
  5384. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5385. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5386. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5387. return true;
  5388. } else if (SemaRef.CurContext->isDependentContext())
  5389. E = X = UpdateExpr = nullptr;
  5390. return ErrorFound != NoError;
  5391. }
  5392. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5393. unsigned NoteId) {
  5394. ExprAnalysisErrorCode ErrorFound = NoError;
  5395. SourceLocation ErrorLoc, NoteLoc;
  5396. SourceRange ErrorRange, NoteRange;
  5397. // Allowed constructs are:
  5398. // x++;
  5399. // x--;
  5400. // ++x;
  5401. // --x;
  5402. // x binop= expr;
  5403. // x = x binop expr;
  5404. // x = expr binop x;
  5405. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5406. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5407. if (AtomicBody->getType()->isScalarType() ||
  5408. AtomicBody->isInstantiationDependent()) {
  5409. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5410. AtomicBody->IgnoreParenImpCasts())) {
  5411. // Check for Compound Assignment Operation
  5412. Op = BinaryOperator::getOpForCompoundAssignment(
  5413. AtomicCompAssignOp->getOpcode());
  5414. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5415. E = AtomicCompAssignOp->getRHS();
  5416. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5417. IsXLHSInRHSPart = true;
  5418. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5419. AtomicBody->IgnoreParenImpCasts())) {
  5420. // Check for Binary Operation
  5421. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5422. return true;
  5423. } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5424. AtomicBody->IgnoreParenImpCasts())) {
  5425. // Check for Unary Operation
  5426. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5427. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5428. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5429. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5430. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5431. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5432. IsXLHSInRHSPart = true;
  5433. } else {
  5434. ErrorFound = NotAnUnaryIncDecExpression;
  5435. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5436. ErrorRange = AtomicUnaryOp->getSourceRange();
  5437. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5438. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5439. }
  5440. } else if (!AtomicBody->isInstantiationDependent()) {
  5441. ErrorFound = NotABinaryOrUnaryExpression;
  5442. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5443. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5444. }
  5445. } else {
  5446. ErrorFound = NotAScalarType;
  5447. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  5448. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5449. }
  5450. } else {
  5451. ErrorFound = NotAnExpression;
  5452. NoteLoc = ErrorLoc = S->getLocStart();
  5453. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5454. }
  5455. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5456. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5457. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5458. return true;
  5459. } else if (SemaRef.CurContext->isDependentContext())
  5460. E = X = UpdateExpr = nullptr;
  5461. if (ErrorFound == NoError && E && X) {
  5462. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5463. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5464. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5465. auto *OVEX = new (SemaRef.getASTContext())
  5466. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5467. auto *OVEExpr = new (SemaRef.getASTContext())
  5468. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5469. auto Update =
  5470. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  5471. IsXLHSInRHSPart ? OVEExpr : OVEX);
  5472. if (Update.isInvalid())
  5473. return true;
  5474. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  5475. Sema::AA_Casting);
  5476. if (Update.isInvalid())
  5477. return true;
  5478. UpdateExpr = Update.get();
  5479. }
  5480. return ErrorFound != NoError;
  5481. }
  5482. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  5483. Stmt *AStmt,
  5484. SourceLocation StartLoc,
  5485. SourceLocation EndLoc) {
  5486. if (!AStmt)
  5487. return StmtError();
  5488. auto *CS = cast<CapturedStmt>(AStmt);
  5489. // 1.2.2 OpenMP Language Terminology
  5490. // Structured block - An executable statement with a single entry at the
  5491. // top and a single exit at the bottom.
  5492. // The point of exit cannot be a branch out of the structured block.
  5493. // longjmp() and throw() must not violate the entry/exit criteria.
  5494. OpenMPClauseKind AtomicKind = OMPC_unknown;
  5495. SourceLocation AtomicKindLoc;
  5496. for (auto *C : Clauses) {
  5497. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  5498. C->getClauseKind() == OMPC_update ||
  5499. C->getClauseKind() == OMPC_capture) {
  5500. if (AtomicKind != OMPC_unknown) {
  5501. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  5502. << SourceRange(C->getLocStart(), C->getLocEnd());
  5503. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  5504. << getOpenMPClauseName(AtomicKind);
  5505. } else {
  5506. AtomicKind = C->getClauseKind();
  5507. AtomicKindLoc = C->getLocStart();
  5508. }
  5509. }
  5510. }
  5511. auto Body = CS->getCapturedStmt();
  5512. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  5513. Body = EWC->getSubExpr();
  5514. Expr *X = nullptr;
  5515. Expr *V = nullptr;
  5516. Expr *E = nullptr;
  5517. Expr *UE = nullptr;
  5518. bool IsXLHSInRHSPart = false;
  5519. bool IsPostfixUpdate = false;
  5520. // OpenMP [2.12.6, atomic Construct]
  5521. // In the next expressions:
  5522. // * x and v (as applicable) are both l-value expressions with scalar type.
  5523. // * During the execution of an atomic region, multiple syntactic
  5524. // occurrences of x must designate the same storage location.
  5525. // * Neither of v and expr (as applicable) may access the storage location
  5526. // designated by x.
  5527. // * Neither of x and expr (as applicable) may access the storage location
  5528. // designated by v.
  5529. // * expr is an expression with scalar type.
  5530. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  5531. // * binop, binop=, ++, and -- are not overloaded operators.
  5532. // * The expression x binop expr must be numerically equivalent to x binop
  5533. // (expr). This requirement is satisfied if the operators in expr have
  5534. // precedence greater than binop, or by using parentheses around expr or
  5535. // subexpressions of expr.
  5536. // * The expression expr binop x must be numerically equivalent to (expr)
  5537. // binop x. This requirement is satisfied if the operators in expr have
  5538. // precedence equal to or greater than binop, or by using parentheses around
  5539. // expr or subexpressions of expr.
  5540. // * For forms that allow multiple occurrences of x, the number of times
  5541. // that x is evaluated is unspecified.
  5542. if (AtomicKind == OMPC_read) {
  5543. enum {
  5544. NotAnExpression,
  5545. NotAnAssignmentOp,
  5546. NotAScalarType,
  5547. NotAnLValue,
  5548. NoError
  5549. } ErrorFound = NoError;
  5550. SourceLocation ErrorLoc, NoteLoc;
  5551. SourceRange ErrorRange, NoteRange;
  5552. // If clause is read:
  5553. // v = x;
  5554. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5555. auto *AtomicBinOp =
  5556. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5557. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5558. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5559. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  5560. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5561. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  5562. if (!X->isLValue() || !V->isLValue()) {
  5563. auto NotLValueExpr = X->isLValue() ? V : X;
  5564. ErrorFound = NotAnLValue;
  5565. ErrorLoc = AtomicBinOp->getExprLoc();
  5566. ErrorRange = AtomicBinOp->getSourceRange();
  5567. NoteLoc = NotLValueExpr->getExprLoc();
  5568. NoteRange = NotLValueExpr->getSourceRange();
  5569. }
  5570. } else if (!X->isInstantiationDependent() ||
  5571. !V->isInstantiationDependent()) {
  5572. auto NotScalarExpr =
  5573. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5574. ? V
  5575. : X;
  5576. ErrorFound = NotAScalarType;
  5577. ErrorLoc = AtomicBinOp->getExprLoc();
  5578. ErrorRange = AtomicBinOp->getSourceRange();
  5579. NoteLoc = NotScalarExpr->getExprLoc();
  5580. NoteRange = NotScalarExpr->getSourceRange();
  5581. }
  5582. } else if (!AtomicBody->isInstantiationDependent()) {
  5583. ErrorFound = NotAnAssignmentOp;
  5584. ErrorLoc = AtomicBody->getExprLoc();
  5585. ErrorRange = AtomicBody->getSourceRange();
  5586. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5587. : AtomicBody->getExprLoc();
  5588. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5589. : AtomicBody->getSourceRange();
  5590. }
  5591. } else {
  5592. ErrorFound = NotAnExpression;
  5593. NoteLoc = ErrorLoc = Body->getLocStart();
  5594. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5595. }
  5596. if (ErrorFound != NoError) {
  5597. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5598. << ErrorRange;
  5599. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5600. << NoteRange;
  5601. return StmtError();
  5602. } else if (CurContext->isDependentContext())
  5603. V = X = nullptr;
  5604. } else if (AtomicKind == OMPC_write) {
  5605. enum {
  5606. NotAnExpression,
  5607. NotAnAssignmentOp,
  5608. NotAScalarType,
  5609. NotAnLValue,
  5610. NoError
  5611. } ErrorFound = NoError;
  5612. SourceLocation ErrorLoc, NoteLoc;
  5613. SourceRange ErrorRange, NoteRange;
  5614. // If clause is write:
  5615. // x = expr;
  5616. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5617. auto *AtomicBinOp =
  5618. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5619. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5620. X = AtomicBinOp->getLHS();
  5621. E = AtomicBinOp->getRHS();
  5622. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5623. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5624. if (!X->isLValue()) {
  5625. ErrorFound = NotAnLValue;
  5626. ErrorLoc = AtomicBinOp->getExprLoc();
  5627. ErrorRange = AtomicBinOp->getSourceRange();
  5628. NoteLoc = X->getExprLoc();
  5629. NoteRange = X->getSourceRange();
  5630. }
  5631. } else if (!X->isInstantiationDependent() ||
  5632. !E->isInstantiationDependent()) {
  5633. auto NotScalarExpr =
  5634. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5635. ? E
  5636. : X;
  5637. ErrorFound = NotAScalarType;
  5638. ErrorLoc = AtomicBinOp->getExprLoc();
  5639. ErrorRange = AtomicBinOp->getSourceRange();
  5640. NoteLoc = NotScalarExpr->getExprLoc();
  5641. NoteRange = NotScalarExpr->getSourceRange();
  5642. }
  5643. } else if (!AtomicBody->isInstantiationDependent()) {
  5644. ErrorFound = NotAnAssignmentOp;
  5645. ErrorLoc = AtomicBody->getExprLoc();
  5646. ErrorRange = AtomicBody->getSourceRange();
  5647. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5648. : AtomicBody->getExprLoc();
  5649. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5650. : AtomicBody->getSourceRange();
  5651. }
  5652. } else {
  5653. ErrorFound = NotAnExpression;
  5654. NoteLoc = ErrorLoc = Body->getLocStart();
  5655. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5656. }
  5657. if (ErrorFound != NoError) {
  5658. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5659. << ErrorRange;
  5660. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5661. << NoteRange;
  5662. return StmtError();
  5663. } else if (CurContext->isDependentContext())
  5664. E = X = nullptr;
  5665. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5666. // If clause is update:
  5667. // x++;
  5668. // x--;
  5669. // ++x;
  5670. // --x;
  5671. // x binop= expr;
  5672. // x = x binop expr;
  5673. // x = expr binop x;
  5674. OpenMPAtomicUpdateChecker Checker(*this);
  5675. if (Checker.checkStatement(
  5676. Body, (AtomicKind == OMPC_update)
  5677. ? diag::err_omp_atomic_update_not_expression_statement
  5678. : diag::err_omp_atomic_not_expression_statement,
  5679. diag::note_omp_atomic_update))
  5680. return StmtError();
  5681. if (!CurContext->isDependentContext()) {
  5682. E = Checker.getExpr();
  5683. X = Checker.getX();
  5684. UE = Checker.getUpdateExpr();
  5685. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5686. }
  5687. } else if (AtomicKind == OMPC_capture) {
  5688. enum {
  5689. NotAnAssignmentOp,
  5690. NotACompoundStatement,
  5691. NotTwoSubstatements,
  5692. NotASpecificExpression,
  5693. NoError
  5694. } ErrorFound = NoError;
  5695. SourceLocation ErrorLoc, NoteLoc;
  5696. SourceRange ErrorRange, NoteRange;
  5697. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5698. // If clause is a capture:
  5699. // v = x++;
  5700. // v = x--;
  5701. // v = ++x;
  5702. // v = --x;
  5703. // v = x binop= expr;
  5704. // v = x = x binop expr;
  5705. // v = x = expr binop x;
  5706. auto *AtomicBinOp =
  5707. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5708. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5709. V = AtomicBinOp->getLHS();
  5710. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5711. OpenMPAtomicUpdateChecker Checker(*this);
  5712. if (Checker.checkStatement(
  5713. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5714. diag::note_omp_atomic_update))
  5715. return StmtError();
  5716. E = Checker.getExpr();
  5717. X = Checker.getX();
  5718. UE = Checker.getUpdateExpr();
  5719. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5720. IsPostfixUpdate = Checker.isPostfixUpdate();
  5721. } else if (!AtomicBody->isInstantiationDependent()) {
  5722. ErrorLoc = AtomicBody->getExprLoc();
  5723. ErrorRange = AtomicBody->getSourceRange();
  5724. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5725. : AtomicBody->getExprLoc();
  5726. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5727. : AtomicBody->getSourceRange();
  5728. ErrorFound = NotAnAssignmentOp;
  5729. }
  5730. if (ErrorFound != NoError) {
  5731. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5732. << ErrorRange;
  5733. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5734. return StmtError();
  5735. } else if (CurContext->isDependentContext()) {
  5736. UE = V = E = X = nullptr;
  5737. }
  5738. } else {
  5739. // If clause is a capture:
  5740. // { v = x; x = expr; }
  5741. // { v = x; x++; }
  5742. // { v = x; x--; }
  5743. // { v = x; ++x; }
  5744. // { v = x; --x; }
  5745. // { v = x; x binop= expr; }
  5746. // { v = x; x = x binop expr; }
  5747. // { v = x; x = expr binop x; }
  5748. // { x++; v = x; }
  5749. // { x--; v = x; }
  5750. // { ++x; v = x; }
  5751. // { --x; v = x; }
  5752. // { x binop= expr; v = x; }
  5753. // { x = x binop expr; v = x; }
  5754. // { x = expr binop x; v = x; }
  5755. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5756. // Check that this is { expr1; expr2; }
  5757. if (CS->size() == 2) {
  5758. auto *First = CS->body_front();
  5759. auto *Second = CS->body_back();
  5760. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5761. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5762. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5763. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5764. // Need to find what subexpression is 'v' and what is 'x'.
  5765. OpenMPAtomicUpdateChecker Checker(*this);
  5766. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5767. BinaryOperator *BinOp = nullptr;
  5768. if (IsUpdateExprFound) {
  5769. BinOp = dyn_cast<BinaryOperator>(First);
  5770. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5771. }
  5772. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5773. // { v = x; x++; }
  5774. // { v = x; x--; }
  5775. // { v = x; ++x; }
  5776. // { v = x; --x; }
  5777. // { v = x; x binop= expr; }
  5778. // { v = x; x = x binop expr; }
  5779. // { v = x; x = expr binop x; }
  5780. // Check that the first expression has form v = x.
  5781. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5782. llvm::FoldingSetNodeID XId, PossibleXId;
  5783. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5784. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5785. IsUpdateExprFound = XId == PossibleXId;
  5786. if (IsUpdateExprFound) {
  5787. V = BinOp->getLHS();
  5788. X = Checker.getX();
  5789. E = Checker.getExpr();
  5790. UE = Checker.getUpdateExpr();
  5791. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5792. IsPostfixUpdate = true;
  5793. }
  5794. }
  5795. if (!IsUpdateExprFound) {
  5796. IsUpdateExprFound = !Checker.checkStatement(First);
  5797. BinOp = nullptr;
  5798. if (IsUpdateExprFound) {
  5799. BinOp = dyn_cast<BinaryOperator>(Second);
  5800. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5801. }
  5802. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5803. // { x++; v = x; }
  5804. // { x--; v = x; }
  5805. // { ++x; v = x; }
  5806. // { --x; v = x; }
  5807. // { x binop= expr; v = x; }
  5808. // { x = x binop expr; v = x; }
  5809. // { x = expr binop x; v = x; }
  5810. // Check that the second expression has form v = x.
  5811. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5812. llvm::FoldingSetNodeID XId, PossibleXId;
  5813. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5814. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5815. IsUpdateExprFound = XId == PossibleXId;
  5816. if (IsUpdateExprFound) {
  5817. V = BinOp->getLHS();
  5818. X = Checker.getX();
  5819. E = Checker.getExpr();
  5820. UE = Checker.getUpdateExpr();
  5821. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5822. IsPostfixUpdate = false;
  5823. }
  5824. }
  5825. }
  5826. if (!IsUpdateExprFound) {
  5827. // { v = x; x = expr; }
  5828. auto *FirstExpr = dyn_cast<Expr>(First);
  5829. auto *SecondExpr = dyn_cast<Expr>(Second);
  5830. if (!FirstExpr || !SecondExpr ||
  5831. !(FirstExpr->isInstantiationDependent() ||
  5832. SecondExpr->isInstantiationDependent())) {
  5833. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5834. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5835. ErrorFound = NotAnAssignmentOp;
  5836. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5837. : First->getLocStart();
  5838. NoteRange = ErrorRange = FirstBinOp
  5839. ? FirstBinOp->getSourceRange()
  5840. : SourceRange(ErrorLoc, ErrorLoc);
  5841. } else {
  5842. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5843. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5844. ErrorFound = NotAnAssignmentOp;
  5845. NoteLoc = ErrorLoc = SecondBinOp
  5846. ? SecondBinOp->getOperatorLoc()
  5847. : Second->getLocStart();
  5848. NoteRange = ErrorRange =
  5849. SecondBinOp ? SecondBinOp->getSourceRange()
  5850. : SourceRange(ErrorLoc, ErrorLoc);
  5851. } else {
  5852. auto *PossibleXRHSInFirst =
  5853. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5854. auto *PossibleXLHSInSecond =
  5855. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5856. llvm::FoldingSetNodeID X1Id, X2Id;
  5857. PossibleXRHSInFirst->Profile(X1Id, Context,
  5858. /*Canonical=*/true);
  5859. PossibleXLHSInSecond->Profile(X2Id, Context,
  5860. /*Canonical=*/true);
  5861. IsUpdateExprFound = X1Id == X2Id;
  5862. if (IsUpdateExprFound) {
  5863. V = FirstBinOp->getLHS();
  5864. X = SecondBinOp->getLHS();
  5865. E = SecondBinOp->getRHS();
  5866. UE = nullptr;
  5867. IsXLHSInRHSPart = false;
  5868. IsPostfixUpdate = true;
  5869. } else {
  5870. ErrorFound = NotASpecificExpression;
  5871. ErrorLoc = FirstBinOp->getExprLoc();
  5872. ErrorRange = FirstBinOp->getSourceRange();
  5873. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5874. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5875. }
  5876. }
  5877. }
  5878. }
  5879. }
  5880. } else {
  5881. NoteLoc = ErrorLoc = Body->getLocStart();
  5882. NoteRange = ErrorRange =
  5883. SourceRange(Body->getLocStart(), Body->getLocStart());
  5884. ErrorFound = NotTwoSubstatements;
  5885. }
  5886. } else {
  5887. NoteLoc = ErrorLoc = Body->getLocStart();
  5888. NoteRange = ErrorRange =
  5889. SourceRange(Body->getLocStart(), Body->getLocStart());
  5890. ErrorFound = NotACompoundStatement;
  5891. }
  5892. if (ErrorFound != NoError) {
  5893. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5894. << ErrorRange;
  5895. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5896. return StmtError();
  5897. } else if (CurContext->isDependentContext()) {
  5898. UE = V = E = X = nullptr;
  5899. }
  5900. }
  5901. }
  5902. getCurFunction()->setHasBranchProtectedScope();
  5903. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5904. X, V, E, UE, IsXLHSInRHSPart,
  5905. IsPostfixUpdate);
  5906. }
  5907. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5908. Stmt *AStmt,
  5909. SourceLocation StartLoc,
  5910. SourceLocation EndLoc) {
  5911. if (!AStmt)
  5912. return StmtError();
  5913. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5914. // 1.2.2 OpenMP Language Terminology
  5915. // Structured block - An executable statement with a single entry at the
  5916. // top and a single exit at the bottom.
  5917. // The point of exit cannot be a branch out of the structured block.
  5918. // longjmp() and throw() must not violate the entry/exit criteria.
  5919. CS->getCapturedDecl()->setNothrow();
  5920. // OpenMP [2.16, Nesting of Regions]
  5921. // If specified, a teams construct must be contained within a target
  5922. // construct. That target construct must contain no statements or directives
  5923. // outside of the teams construct.
  5924. if (DSAStack->hasInnerTeamsRegion()) {
  5925. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5926. bool OMPTeamsFound = true;
  5927. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5928. auto I = CS->body_begin();
  5929. while (I != CS->body_end()) {
  5930. auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  5931. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5932. OMPTeamsFound = false;
  5933. break;
  5934. }
  5935. ++I;
  5936. }
  5937. assert(I != CS->body_end() && "Not found statement");
  5938. S = *I;
  5939. } else {
  5940. auto *OED = dyn_cast<OMPExecutableDirective>(S);
  5941. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  5942. }
  5943. if (!OMPTeamsFound) {
  5944. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5945. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5946. diag::note_omp_nested_teams_construct_here);
  5947. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5948. << isa<OMPExecutableDirective>(S);
  5949. return StmtError();
  5950. }
  5951. }
  5952. getCurFunction()->setHasBranchProtectedScope();
  5953. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5954. }
  5955. StmtResult
  5956. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5957. Stmt *AStmt, SourceLocation StartLoc,
  5958. SourceLocation EndLoc) {
  5959. if (!AStmt)
  5960. return StmtError();
  5961. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5962. // 1.2.2 OpenMP Language Terminology
  5963. // Structured block - An executable statement with a single entry at the
  5964. // top and a single exit at the bottom.
  5965. // The point of exit cannot be a branch out of the structured block.
  5966. // longjmp() and throw() must not violate the entry/exit criteria.
  5967. CS->getCapturedDecl()->setNothrow();
  5968. getCurFunction()->setHasBranchProtectedScope();
  5969. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5970. AStmt);
  5971. }
  5972. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  5973. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5974. SourceLocation EndLoc,
  5975. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5976. if (!AStmt)
  5977. return StmtError();
  5978. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5979. // 1.2.2 OpenMP Language Terminology
  5980. // Structured block - An executable statement with a single entry at the
  5981. // top and a single exit at the bottom.
  5982. // The point of exit cannot be a branch out of the structured block.
  5983. // longjmp() and throw() must not violate the entry/exit criteria.
  5984. CS->getCapturedDecl()->setNothrow();
  5985. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  5986. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  5987. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  5988. // 1.2.2 OpenMP Language Terminology
  5989. // Structured block - An executable statement with a single entry at the
  5990. // top and a single exit at the bottom.
  5991. // The point of exit cannot be a branch out of the structured block.
  5992. // longjmp() and throw() must not violate the entry/exit criteria.
  5993. CS->getCapturedDecl()->setNothrow();
  5994. }
  5995. OMPLoopDirective::HelperExprs B;
  5996. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5997. // define the nested loops number.
  5998. unsigned NestedLoopCount =
  5999. CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6000. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6001. VarsWithImplicitDSA, B);
  6002. if (NestedLoopCount == 0)
  6003. return StmtError();
  6004. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6005. "omp target parallel for loop exprs were not built");
  6006. if (!CurContext->isDependentContext()) {
  6007. // Finalize the clauses that need pre-built expressions for CodeGen.
  6008. for (auto C : Clauses) {
  6009. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6010. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6011. B.NumIterations, *this, CurScope,
  6012. DSAStack))
  6013. return StmtError();
  6014. }
  6015. }
  6016. getCurFunction()->setHasBranchProtectedScope();
  6017. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6018. NestedLoopCount, Clauses, AStmt,
  6019. B, DSAStack->isCancelRegion());
  6020. }
  6021. /// Check for existence of a map clause in the list of clauses.
  6022. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6023. const OpenMPClauseKind K) {
  6024. return llvm::any_of(
  6025. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6026. }
  6027. template <typename... Params>
  6028. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6029. const Params... ClauseTypes) {
  6030. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6031. }
  6032. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6033. Stmt *AStmt,
  6034. SourceLocation StartLoc,
  6035. SourceLocation EndLoc) {
  6036. if (!AStmt)
  6037. return StmtError();
  6038. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6039. // OpenMP [2.10.1, Restrictions, p. 97]
  6040. // At least one map clause must appear on the directive.
  6041. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6042. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6043. << "'map' or 'use_device_ptr'"
  6044. << getOpenMPDirectiveName(OMPD_target_data);
  6045. return StmtError();
  6046. }
  6047. getCurFunction()->setHasBranchProtectedScope();
  6048. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6049. AStmt);
  6050. }
  6051. StmtResult
  6052. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6053. SourceLocation StartLoc,
  6054. SourceLocation EndLoc, Stmt *AStmt) {
  6055. if (!AStmt)
  6056. return StmtError();
  6057. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6058. // 1.2.2 OpenMP Language Terminology
  6059. // Structured block - An executable statement with a single entry at the
  6060. // top and a single exit at the bottom.
  6061. // The point of exit cannot be a branch out of the structured block.
  6062. // longjmp() and throw() must not violate the entry/exit criteria.
  6063. CS->getCapturedDecl()->setNothrow();
  6064. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6065. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6066. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6067. // 1.2.2 OpenMP Language Terminology
  6068. // Structured block - An executable statement with a single entry at the
  6069. // top and a single exit at the bottom.
  6070. // The point of exit cannot be a branch out of the structured block.
  6071. // longjmp() and throw() must not violate the entry/exit criteria.
  6072. CS->getCapturedDecl()->setNothrow();
  6073. }
  6074. // OpenMP [2.10.2, Restrictions, p. 99]
  6075. // At least one map clause must appear on the directive.
  6076. if (!hasClauses(Clauses, OMPC_map)) {
  6077. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6078. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6079. return StmtError();
  6080. }
  6081. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6082. AStmt);
  6083. }
  6084. StmtResult
  6085. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6086. SourceLocation StartLoc,
  6087. SourceLocation EndLoc, Stmt *AStmt) {
  6088. if (!AStmt)
  6089. return StmtError();
  6090. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6091. // 1.2.2 OpenMP Language Terminology
  6092. // Structured block - An executable statement with a single entry at the
  6093. // top and a single exit at the bottom.
  6094. // The point of exit cannot be a branch out of the structured block.
  6095. // longjmp() and throw() must not violate the entry/exit criteria.
  6096. CS->getCapturedDecl()->setNothrow();
  6097. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6098. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6099. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6100. // 1.2.2 OpenMP Language Terminology
  6101. // Structured block - An executable statement with a single entry at the
  6102. // top and a single exit at the bottom.
  6103. // The point of exit cannot be a branch out of the structured block.
  6104. // longjmp() and throw() must not violate the entry/exit criteria.
  6105. CS->getCapturedDecl()->setNothrow();
  6106. }
  6107. // OpenMP [2.10.3, Restrictions, p. 102]
  6108. // At least one map clause must appear on the directive.
  6109. if (!hasClauses(Clauses, OMPC_map)) {
  6110. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6111. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6112. return StmtError();
  6113. }
  6114. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6115. AStmt);
  6116. }
  6117. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6118. SourceLocation StartLoc,
  6119. SourceLocation EndLoc,
  6120. Stmt *AStmt) {
  6121. if (!AStmt)
  6122. return StmtError();
  6123. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6124. // 1.2.2 OpenMP Language Terminology
  6125. // Structured block - An executable statement with a single entry at the
  6126. // top and a single exit at the bottom.
  6127. // The point of exit cannot be a branch out of the structured block.
  6128. // longjmp() and throw() must not violate the entry/exit criteria.
  6129. CS->getCapturedDecl()->setNothrow();
  6130. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6131. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6132. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6133. // 1.2.2 OpenMP Language Terminology
  6134. // Structured block - An executable statement with a single entry at the
  6135. // top and a single exit at the bottom.
  6136. // The point of exit cannot be a branch out of the structured block.
  6137. // longjmp() and throw() must not violate the entry/exit criteria.
  6138. CS->getCapturedDecl()->setNothrow();
  6139. }
  6140. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6141. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6142. return StmtError();
  6143. }
  6144. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6145. AStmt);
  6146. }
  6147. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6148. Stmt *AStmt, SourceLocation StartLoc,
  6149. SourceLocation EndLoc) {
  6150. if (!AStmt)
  6151. return StmtError();
  6152. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6153. // 1.2.2 OpenMP Language Terminology
  6154. // Structured block - An executable statement with a single entry at the
  6155. // top and a single exit at the bottom.
  6156. // The point of exit cannot be a branch out of the structured block.
  6157. // longjmp() and throw() must not violate the entry/exit criteria.
  6158. CS->getCapturedDecl()->setNothrow();
  6159. getCurFunction()->setHasBranchProtectedScope();
  6160. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6161. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6162. }
  6163. StmtResult
  6164. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6165. SourceLocation EndLoc,
  6166. OpenMPDirectiveKind CancelRegion) {
  6167. if (DSAStack->isParentNowaitRegion()) {
  6168. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6169. return StmtError();
  6170. }
  6171. if (DSAStack->isParentOrderedRegion()) {
  6172. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6173. return StmtError();
  6174. }
  6175. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6176. CancelRegion);
  6177. }
  6178. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6179. SourceLocation StartLoc,
  6180. SourceLocation EndLoc,
  6181. OpenMPDirectiveKind CancelRegion) {
  6182. if (DSAStack->isParentNowaitRegion()) {
  6183. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6184. return StmtError();
  6185. }
  6186. if (DSAStack->isParentOrderedRegion()) {
  6187. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6188. return StmtError();
  6189. }
  6190. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6191. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6192. CancelRegion);
  6193. }
  6194. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6195. ArrayRef<OMPClause *> Clauses) {
  6196. OMPClause *PrevClause = nullptr;
  6197. bool ErrorFound = false;
  6198. for (auto *C : Clauses) {
  6199. if (C->getClauseKind() == OMPC_grainsize ||
  6200. C->getClauseKind() == OMPC_num_tasks) {
  6201. if (!PrevClause)
  6202. PrevClause = C;
  6203. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6204. S.Diag(C->getLocStart(),
  6205. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6206. << getOpenMPClauseName(C->getClauseKind())
  6207. << getOpenMPClauseName(PrevClause->getClauseKind());
  6208. S.Diag(PrevClause->getLocStart(),
  6209. diag::note_omp_previous_grainsize_num_tasks)
  6210. << getOpenMPClauseName(PrevClause->getClauseKind());
  6211. ErrorFound = true;
  6212. }
  6213. }
  6214. }
  6215. return ErrorFound;
  6216. }
  6217. static bool checkReductionClauseWithNogroup(Sema &S,
  6218. ArrayRef<OMPClause *> Clauses) {
  6219. OMPClause *ReductionClause = nullptr;
  6220. OMPClause *NogroupClause = nullptr;
  6221. for (auto *C : Clauses) {
  6222. if (C->getClauseKind() == OMPC_reduction) {
  6223. ReductionClause = C;
  6224. if (NogroupClause)
  6225. break;
  6226. continue;
  6227. }
  6228. if (C->getClauseKind() == OMPC_nogroup) {
  6229. NogroupClause = C;
  6230. if (ReductionClause)
  6231. break;
  6232. continue;
  6233. }
  6234. }
  6235. if (ReductionClause && NogroupClause) {
  6236. S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
  6237. << SourceRange(NogroupClause->getLocStart(),
  6238. NogroupClause->getLocEnd());
  6239. return true;
  6240. }
  6241. return false;
  6242. }
  6243. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6244. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6245. SourceLocation EndLoc,
  6246. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6247. if (!AStmt)
  6248. return StmtError();
  6249. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6250. OMPLoopDirective::HelperExprs B;
  6251. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6252. // define the nested loops number.
  6253. unsigned NestedLoopCount =
  6254. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6255. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6256. VarsWithImplicitDSA, B);
  6257. if (NestedLoopCount == 0)
  6258. return StmtError();
  6259. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6260. "omp for loop exprs were not built");
  6261. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6262. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6263. // not appear on the same taskloop directive.
  6264. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6265. return StmtError();
  6266. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6267. // If a reduction clause is present on the taskloop directive, the nogroup
  6268. // clause must not be specified.
  6269. if (checkReductionClauseWithNogroup(*this, Clauses))
  6270. return StmtError();
  6271. getCurFunction()->setHasBranchProtectedScope();
  6272. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6273. NestedLoopCount, Clauses, AStmt, B);
  6274. }
  6275. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6276. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6277. SourceLocation EndLoc,
  6278. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6279. if (!AStmt)
  6280. return StmtError();
  6281. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6282. OMPLoopDirective::HelperExprs B;
  6283. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6284. // define the nested loops number.
  6285. unsigned NestedLoopCount =
  6286. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6287. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6288. VarsWithImplicitDSA, B);
  6289. if (NestedLoopCount == 0)
  6290. return StmtError();
  6291. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6292. "omp for loop exprs were not built");
  6293. if (!CurContext->isDependentContext()) {
  6294. // Finalize the clauses that need pre-built expressions for CodeGen.
  6295. for (auto C : Clauses) {
  6296. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6297. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6298. B.NumIterations, *this, CurScope,
  6299. DSAStack))
  6300. return StmtError();
  6301. }
  6302. }
  6303. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6304. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6305. // not appear on the same taskloop directive.
  6306. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6307. return StmtError();
  6308. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6309. // If a reduction clause is present on the taskloop directive, the nogroup
  6310. // clause must not be specified.
  6311. if (checkReductionClauseWithNogroup(*this, Clauses))
  6312. return StmtError();
  6313. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6314. return StmtError();
  6315. getCurFunction()->setHasBranchProtectedScope();
  6316. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6317. NestedLoopCount, Clauses, AStmt, B);
  6318. }
  6319. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6320. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6321. SourceLocation EndLoc,
  6322. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6323. if (!AStmt)
  6324. return StmtError();
  6325. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6326. OMPLoopDirective::HelperExprs B;
  6327. // In presence of clause 'collapse' with number of loops, it will
  6328. // define the nested loops number.
  6329. unsigned NestedLoopCount =
  6330. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6331. nullptr /*ordered not a clause on distribute*/, AStmt,
  6332. *this, *DSAStack, VarsWithImplicitDSA, B);
  6333. if (NestedLoopCount == 0)
  6334. return StmtError();
  6335. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6336. "omp for loop exprs were not built");
  6337. getCurFunction()->setHasBranchProtectedScope();
  6338. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6339. NestedLoopCount, Clauses, AStmt, B);
  6340. }
  6341. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6342. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6343. SourceLocation EndLoc,
  6344. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6345. if (!AStmt)
  6346. return StmtError();
  6347. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6348. // 1.2.2 OpenMP Language Terminology
  6349. // Structured block - An executable statement with a single entry at the
  6350. // top and a single exit at the bottom.
  6351. // The point of exit cannot be a branch out of the structured block.
  6352. // longjmp() and throw() must not violate the entry/exit criteria.
  6353. CS->getCapturedDecl()->setNothrow();
  6354. for (int ThisCaptureLevel =
  6355. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6356. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6357. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6358. // 1.2.2 OpenMP Language Terminology
  6359. // Structured block - An executable statement with a single entry at the
  6360. // top and a single exit at the bottom.
  6361. // The point of exit cannot be a branch out of the structured block.
  6362. // longjmp() and throw() must not violate the entry/exit criteria.
  6363. CS->getCapturedDecl()->setNothrow();
  6364. }
  6365. OMPLoopDirective::HelperExprs B;
  6366. // In presence of clause 'collapse' with number of loops, it will
  6367. // define the nested loops number.
  6368. unsigned NestedLoopCount = CheckOpenMPLoop(
  6369. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6370. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6371. VarsWithImplicitDSA, B);
  6372. if (NestedLoopCount == 0)
  6373. return StmtError();
  6374. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6375. "omp for loop exprs were not built");
  6376. getCurFunction()->setHasBranchProtectedScope();
  6377. return OMPDistributeParallelForDirective::Create(
  6378. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6379. DSAStack->isCancelRegion());
  6380. }
  6381. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6382. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6383. SourceLocation EndLoc,
  6384. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6385. if (!AStmt)
  6386. return StmtError();
  6387. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6388. // 1.2.2 OpenMP Language Terminology
  6389. // Structured block - An executable statement with a single entry at the
  6390. // top and a single exit at the bottom.
  6391. // The point of exit cannot be a branch out of the structured block.
  6392. // longjmp() and throw() must not violate the entry/exit criteria.
  6393. CS->getCapturedDecl()->setNothrow();
  6394. for (int ThisCaptureLevel =
  6395. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6396. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6397. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6398. // 1.2.2 OpenMP Language Terminology
  6399. // Structured block - An executable statement with a single entry at the
  6400. // top and a single exit at the bottom.
  6401. // The point of exit cannot be a branch out of the structured block.
  6402. // longjmp() and throw() must not violate the entry/exit criteria.
  6403. CS->getCapturedDecl()->setNothrow();
  6404. }
  6405. OMPLoopDirective::HelperExprs B;
  6406. // In presence of clause 'collapse' with number of loops, it will
  6407. // define the nested loops number.
  6408. unsigned NestedLoopCount = CheckOpenMPLoop(
  6409. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6410. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6411. VarsWithImplicitDSA, B);
  6412. if (NestedLoopCount == 0)
  6413. return StmtError();
  6414. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6415. "omp for loop exprs were not built");
  6416. if (!CurContext->isDependentContext()) {
  6417. // Finalize the clauses that need pre-built expressions for CodeGen.
  6418. for (auto C : Clauses) {
  6419. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6420. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6421. B.NumIterations, *this, CurScope,
  6422. DSAStack))
  6423. return StmtError();
  6424. }
  6425. }
  6426. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6427. return StmtError();
  6428. getCurFunction()->setHasBranchProtectedScope();
  6429. return OMPDistributeParallelForSimdDirective::Create(
  6430. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6431. }
  6432. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6433. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6434. SourceLocation EndLoc,
  6435. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6436. if (!AStmt)
  6437. return StmtError();
  6438. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6439. // 1.2.2 OpenMP Language Terminology
  6440. // Structured block - An executable statement with a single entry at the
  6441. // top and a single exit at the bottom.
  6442. // The point of exit cannot be a branch out of the structured block.
  6443. // longjmp() and throw() must not violate the entry/exit criteria.
  6444. CS->getCapturedDecl()->setNothrow();
  6445. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  6446. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6447. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6448. // 1.2.2 OpenMP Language Terminology
  6449. // Structured block - An executable statement with a single entry at the
  6450. // top and a single exit at the bottom.
  6451. // The point of exit cannot be a branch out of the structured block.
  6452. // longjmp() and throw() must not violate the entry/exit criteria.
  6453. CS->getCapturedDecl()->setNothrow();
  6454. }
  6455. OMPLoopDirective::HelperExprs B;
  6456. // In presence of clause 'collapse' with number of loops, it will
  6457. // define the nested loops number.
  6458. unsigned NestedLoopCount =
  6459. CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  6460. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6461. *DSAStack, VarsWithImplicitDSA, B);
  6462. if (NestedLoopCount == 0)
  6463. return StmtError();
  6464. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6465. "omp for loop exprs were not built");
  6466. if (!CurContext->isDependentContext()) {
  6467. // Finalize the clauses that need pre-built expressions for CodeGen.
  6468. for (auto C : Clauses) {
  6469. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6470. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6471. B.NumIterations, *this, CurScope,
  6472. DSAStack))
  6473. return StmtError();
  6474. }
  6475. }
  6476. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6477. return StmtError();
  6478. getCurFunction()->setHasBranchProtectedScope();
  6479. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  6480. NestedLoopCount, Clauses, AStmt, B);
  6481. }
  6482. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  6483. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6484. SourceLocation EndLoc,
  6485. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6486. if (!AStmt)
  6487. return StmtError();
  6488. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6489. // 1.2.2 OpenMP Language Terminology
  6490. // Structured block - An executable statement with a single entry at the
  6491. // top and a single exit at the bottom.
  6492. // The point of exit cannot be a branch out of the structured block.
  6493. // longjmp() and throw() must not violate the entry/exit criteria.
  6494. CS->getCapturedDecl()->setNothrow();
  6495. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6496. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6497. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6498. // 1.2.2 OpenMP Language Terminology
  6499. // Structured block - An executable statement with a single entry at the
  6500. // top and a single exit at the bottom.
  6501. // The point of exit cannot be a branch out of the structured block.
  6502. // longjmp() and throw() must not violate the entry/exit criteria.
  6503. CS->getCapturedDecl()->setNothrow();
  6504. }
  6505. OMPLoopDirective::HelperExprs B;
  6506. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6507. // define the nested loops number.
  6508. unsigned NestedLoopCount = CheckOpenMPLoop(
  6509. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6510. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6511. VarsWithImplicitDSA, B);
  6512. if (NestedLoopCount == 0)
  6513. return StmtError();
  6514. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6515. "omp target parallel for simd loop exprs were not built");
  6516. if (!CurContext->isDependentContext()) {
  6517. // Finalize the clauses that need pre-built expressions for CodeGen.
  6518. for (auto C : Clauses) {
  6519. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6520. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6521. B.NumIterations, *this, CurScope,
  6522. DSAStack))
  6523. return StmtError();
  6524. }
  6525. }
  6526. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6527. return StmtError();
  6528. getCurFunction()->setHasBranchProtectedScope();
  6529. return OMPTargetParallelForSimdDirective::Create(
  6530. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6531. }
  6532. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  6533. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6534. SourceLocation EndLoc,
  6535. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6536. if (!AStmt)
  6537. return StmtError();
  6538. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6539. // 1.2.2 OpenMP Language Terminology
  6540. // Structured block - An executable statement with a single entry at the
  6541. // top and a single exit at the bottom.
  6542. // The point of exit cannot be a branch out of the structured block.
  6543. // longjmp() and throw() must not violate the entry/exit criteria.
  6544. CS->getCapturedDecl()->setNothrow();
  6545. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  6546. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6547. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6548. // 1.2.2 OpenMP Language Terminology
  6549. // Structured block - An executable statement with a single entry at the
  6550. // top and a single exit at the bottom.
  6551. // The point of exit cannot be a branch out of the structured block.
  6552. // longjmp() and throw() must not violate the entry/exit criteria.
  6553. CS->getCapturedDecl()->setNothrow();
  6554. }
  6555. OMPLoopDirective::HelperExprs B;
  6556. // In presence of clause 'collapse' with number of loops, it will define the
  6557. // nested loops number.
  6558. unsigned NestedLoopCount =
  6559. CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  6560. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6561. VarsWithImplicitDSA, B);
  6562. if (NestedLoopCount == 0)
  6563. return StmtError();
  6564. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6565. "omp target simd loop exprs were not built");
  6566. if (!CurContext->isDependentContext()) {
  6567. // Finalize the clauses that need pre-built expressions for CodeGen.
  6568. for (auto C : Clauses) {
  6569. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6570. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6571. B.NumIterations, *this, CurScope,
  6572. DSAStack))
  6573. return StmtError();
  6574. }
  6575. }
  6576. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6577. return StmtError();
  6578. getCurFunction()->setHasBranchProtectedScope();
  6579. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  6580. NestedLoopCount, Clauses, AStmt, B);
  6581. }
  6582. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  6583. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6584. SourceLocation EndLoc,
  6585. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6586. if (!AStmt)
  6587. return StmtError();
  6588. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6589. // 1.2.2 OpenMP Language Terminology
  6590. // Structured block - An executable statement with a single entry at the
  6591. // top and a single exit at the bottom.
  6592. // The point of exit cannot be a branch out of the structured block.
  6593. // longjmp() and throw() must not violate the entry/exit criteria.
  6594. CS->getCapturedDecl()->setNothrow();
  6595. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  6596. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6597. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6598. // 1.2.2 OpenMP Language Terminology
  6599. // Structured block - An executable statement with a single entry at the
  6600. // top and a single exit at the bottom.
  6601. // The point of exit cannot be a branch out of the structured block.
  6602. // longjmp() and throw() must not violate the entry/exit criteria.
  6603. CS->getCapturedDecl()->setNothrow();
  6604. }
  6605. OMPLoopDirective::HelperExprs B;
  6606. // In presence of clause 'collapse' with number of loops, it will
  6607. // define the nested loops number.
  6608. unsigned NestedLoopCount =
  6609. CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  6610. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6611. *DSAStack, VarsWithImplicitDSA, B);
  6612. if (NestedLoopCount == 0)
  6613. return StmtError();
  6614. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6615. "omp teams distribute loop exprs were not built");
  6616. getCurFunction()->setHasBranchProtectedScope();
  6617. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6618. return OMPTeamsDistributeDirective::Create(
  6619. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6620. }
  6621. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  6622. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6623. SourceLocation EndLoc,
  6624. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6625. if (!AStmt)
  6626. return StmtError();
  6627. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6628. // 1.2.2 OpenMP Language Terminology
  6629. // Structured block - An executable statement with a single entry at the
  6630. // top and a single exit at the bottom.
  6631. // The point of exit cannot be a branch out of the structured block.
  6632. // longjmp() and throw() must not violate the entry/exit criteria.
  6633. CS->getCapturedDecl()->setNothrow();
  6634. for (int ThisCaptureLevel =
  6635. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  6636. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6637. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6638. // 1.2.2 OpenMP Language Terminology
  6639. // Structured block - An executable statement with a single entry at the
  6640. // top and a single exit at the bottom.
  6641. // The point of exit cannot be a branch out of the structured block.
  6642. // longjmp() and throw() must not violate the entry/exit criteria.
  6643. CS->getCapturedDecl()->setNothrow();
  6644. }
  6645. OMPLoopDirective::HelperExprs B;
  6646. // In presence of clause 'collapse' with number of loops, it will
  6647. // define the nested loops number.
  6648. unsigned NestedLoopCount = CheckOpenMPLoop(
  6649. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6650. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6651. VarsWithImplicitDSA, B);
  6652. if (NestedLoopCount == 0)
  6653. return StmtError();
  6654. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6655. "omp teams distribute simd loop exprs were not built");
  6656. if (!CurContext->isDependentContext()) {
  6657. // Finalize the clauses that need pre-built expressions for CodeGen.
  6658. for (auto C : Clauses) {
  6659. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6660. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6661. B.NumIterations, *this, CurScope,
  6662. DSAStack))
  6663. return StmtError();
  6664. }
  6665. }
  6666. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6667. return StmtError();
  6668. getCurFunction()->setHasBranchProtectedScope();
  6669. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6670. return OMPTeamsDistributeSimdDirective::Create(
  6671. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6672. }
  6673. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6674. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6675. SourceLocation EndLoc,
  6676. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6677. if (!AStmt)
  6678. return StmtError();
  6679. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6680. // 1.2.2 OpenMP Language Terminology
  6681. // Structured block - An executable statement with a single entry at the
  6682. // top and a single exit at the bottom.
  6683. // The point of exit cannot be a branch out of the structured block.
  6684. // longjmp() and throw() must not violate the entry/exit criteria.
  6685. CS->getCapturedDecl()->setNothrow();
  6686. for (int ThisCaptureLevel =
  6687. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  6688. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6689. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6690. // 1.2.2 OpenMP Language Terminology
  6691. // Structured block - An executable statement with a single entry at the
  6692. // top and a single exit at the bottom.
  6693. // The point of exit cannot be a branch out of the structured block.
  6694. // longjmp() and throw() must not violate the entry/exit criteria.
  6695. CS->getCapturedDecl()->setNothrow();
  6696. }
  6697. OMPLoopDirective::HelperExprs B;
  6698. // In presence of clause 'collapse' with number of loops, it will
  6699. // define the nested loops number.
  6700. auto NestedLoopCount = CheckOpenMPLoop(
  6701. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6702. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6703. VarsWithImplicitDSA, B);
  6704. if (NestedLoopCount == 0)
  6705. return StmtError();
  6706. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6707. "omp for loop exprs were not built");
  6708. if (!CurContext->isDependentContext()) {
  6709. // Finalize the clauses that need pre-built expressions for CodeGen.
  6710. for (auto C : Clauses) {
  6711. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6712. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6713. B.NumIterations, *this, CurScope,
  6714. DSAStack))
  6715. return StmtError();
  6716. }
  6717. }
  6718. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6719. return StmtError();
  6720. getCurFunction()->setHasBranchProtectedScope();
  6721. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6722. return OMPTeamsDistributeParallelForSimdDirective::Create(
  6723. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6724. }
  6725. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  6726. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6727. SourceLocation EndLoc,
  6728. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6729. if (!AStmt)
  6730. return StmtError();
  6731. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6732. // 1.2.2 OpenMP Language Terminology
  6733. // Structured block - An executable statement with a single entry at the
  6734. // top and a single exit at the bottom.
  6735. // The point of exit cannot be a branch out of the structured block.
  6736. // longjmp() and throw() must not violate the entry/exit criteria.
  6737. CS->getCapturedDecl()->setNothrow();
  6738. for (int ThisCaptureLevel =
  6739. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  6740. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6741. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6742. // 1.2.2 OpenMP Language Terminology
  6743. // Structured block - An executable statement with a single entry at the
  6744. // top and a single exit at the bottom.
  6745. // The point of exit cannot be a branch out of the structured block.
  6746. // longjmp() and throw() must not violate the entry/exit criteria.
  6747. CS->getCapturedDecl()->setNothrow();
  6748. }
  6749. OMPLoopDirective::HelperExprs B;
  6750. // In presence of clause 'collapse' with number of loops, it will
  6751. // define the nested loops number.
  6752. unsigned NestedLoopCount = CheckOpenMPLoop(
  6753. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6754. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6755. VarsWithImplicitDSA, B);
  6756. if (NestedLoopCount == 0)
  6757. return StmtError();
  6758. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6759. "omp for loop exprs were not built");
  6760. getCurFunction()->setHasBranchProtectedScope();
  6761. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6762. return OMPTeamsDistributeParallelForDirective::Create(
  6763. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6764. DSAStack->isCancelRegion());
  6765. }
  6766. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6767. Stmt *AStmt,
  6768. SourceLocation StartLoc,
  6769. SourceLocation EndLoc) {
  6770. if (!AStmt)
  6771. return StmtError();
  6772. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6773. // 1.2.2 OpenMP Language Terminology
  6774. // Structured block - An executable statement with a single entry at the
  6775. // top and a single exit at the bottom.
  6776. // The point of exit cannot be a branch out of the structured block.
  6777. // longjmp() and throw() must not violate the entry/exit criteria.
  6778. CS->getCapturedDecl()->setNothrow();
  6779. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  6780. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6781. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6782. // 1.2.2 OpenMP Language Terminology
  6783. // Structured block - An executable statement with a single entry at the
  6784. // top and a single exit at the bottom.
  6785. // The point of exit cannot be a branch out of the structured block.
  6786. // longjmp() and throw() must not violate the entry/exit criteria.
  6787. CS->getCapturedDecl()->setNothrow();
  6788. }
  6789. getCurFunction()->setHasBranchProtectedScope();
  6790. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6791. AStmt);
  6792. }
  6793. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  6794. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6795. SourceLocation EndLoc,
  6796. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6797. if (!AStmt)
  6798. return StmtError();
  6799. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6800. // 1.2.2 OpenMP Language Terminology
  6801. // Structured block - An executable statement with a single entry at the
  6802. // top and a single exit at the bottom.
  6803. // The point of exit cannot be a branch out of the structured block.
  6804. // longjmp() and throw() must not violate the entry/exit criteria.
  6805. CS->getCapturedDecl()->setNothrow();
  6806. for (int ThisCaptureLevel =
  6807. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  6808. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6809. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6810. // 1.2.2 OpenMP Language Terminology
  6811. // Structured block - An executable statement with a single entry at the
  6812. // top and a single exit at the bottom.
  6813. // The point of exit cannot be a branch out of the structured block.
  6814. // longjmp() and throw() must not violate the entry/exit criteria.
  6815. CS->getCapturedDecl()->setNothrow();
  6816. }
  6817. OMPLoopDirective::HelperExprs B;
  6818. // In presence of clause 'collapse' with number of loops, it will
  6819. // define the nested loops number.
  6820. auto NestedLoopCount = CheckOpenMPLoop(
  6821. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  6822. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6823. VarsWithImplicitDSA, B);
  6824. if (NestedLoopCount == 0)
  6825. return StmtError();
  6826. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6827. "omp target teams distribute loop exprs were not built");
  6828. getCurFunction()->setHasBranchProtectedScope();
  6829. return OMPTargetTeamsDistributeDirective::Create(
  6830. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6831. }
  6832. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  6833. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6834. SourceLocation EndLoc,
  6835. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6836. if (!AStmt)
  6837. return StmtError();
  6838. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6839. // 1.2.2 OpenMP Language Terminology
  6840. // Structured block - An executable statement with a single entry at the
  6841. // top and a single exit at the bottom.
  6842. // The point of exit cannot be a branch out of the structured block.
  6843. // longjmp() and throw() must not violate the entry/exit criteria.
  6844. CS->getCapturedDecl()->setNothrow();
  6845. OMPLoopDirective::HelperExprs B;
  6846. // In presence of clause 'collapse' with number of loops, it will
  6847. // define the nested loops number.
  6848. auto NestedLoopCount = CheckOpenMPLoop(
  6849. OMPD_target_teams_distribute_parallel_for,
  6850. getCollapseNumberExpr(Clauses),
  6851. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6852. VarsWithImplicitDSA, B);
  6853. if (NestedLoopCount == 0)
  6854. return StmtError();
  6855. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6856. "omp target teams distribute parallel for loop exprs were not built");
  6857. getCurFunction()->setHasBranchProtectedScope();
  6858. return OMPTargetTeamsDistributeParallelForDirective::Create(
  6859. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6860. DSAStack->isCancelRegion());
  6861. }
  6862. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  6863. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6864. SourceLocation EndLoc,
  6865. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6866. if (!AStmt)
  6867. return StmtError();
  6868. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6869. // 1.2.2 OpenMP Language Terminology
  6870. // Structured block - An executable statement with a single entry at the
  6871. // top and a single exit at the bottom.
  6872. // The point of exit cannot be a branch out of the structured block.
  6873. // longjmp() and throw() must not violate the entry/exit criteria.
  6874. CS->getCapturedDecl()->setNothrow();
  6875. OMPLoopDirective::HelperExprs B;
  6876. // In presence of clause 'collapse' with number of loops, it will
  6877. // define the nested loops number.
  6878. auto NestedLoopCount = CheckOpenMPLoop(
  6879. OMPD_target_teams_distribute_parallel_for_simd,
  6880. getCollapseNumberExpr(Clauses),
  6881. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6882. VarsWithImplicitDSA, B);
  6883. if (NestedLoopCount == 0)
  6884. return StmtError();
  6885. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6886. "omp target teams distribute parallel for simd loop exprs were not "
  6887. "built");
  6888. if (!CurContext->isDependentContext()) {
  6889. // Finalize the clauses that need pre-built expressions for CodeGen.
  6890. for (auto C : Clauses) {
  6891. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6892. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6893. B.NumIterations, *this, CurScope,
  6894. DSAStack))
  6895. return StmtError();
  6896. }
  6897. }
  6898. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6899. return StmtError();
  6900. getCurFunction()->setHasBranchProtectedScope();
  6901. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  6902. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6903. }
  6904. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  6905. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6906. SourceLocation EndLoc,
  6907. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6908. if (!AStmt)
  6909. return StmtError();
  6910. auto *CS = cast<CapturedStmt>(AStmt);
  6911. // 1.2.2 OpenMP Language Terminology
  6912. // Structured block - An executable statement with a single entry at the
  6913. // top and a single exit at the bottom.
  6914. // The point of exit cannot be a branch out of the structured block.
  6915. // longjmp() and throw() must not violate the entry/exit criteria.
  6916. CS->getCapturedDecl()->setNothrow();
  6917. for (int ThisCaptureLevel =
  6918. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  6919. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6920. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6921. // 1.2.2 OpenMP Language Terminology
  6922. // Structured block - An executable statement with a single entry at the
  6923. // top and a single exit at the bottom.
  6924. // The point of exit cannot be a branch out of the structured block.
  6925. // longjmp() and throw() must not violate the entry/exit criteria.
  6926. CS->getCapturedDecl()->setNothrow();
  6927. }
  6928. OMPLoopDirective::HelperExprs B;
  6929. // In presence of clause 'collapse' with number of loops, it will
  6930. // define the nested loops number.
  6931. auto NestedLoopCount = CheckOpenMPLoop(
  6932. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6933. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6934. VarsWithImplicitDSA, B);
  6935. if (NestedLoopCount == 0)
  6936. return StmtError();
  6937. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6938. "omp target teams distribute simd loop exprs were not built");
  6939. if (!CurContext->isDependentContext()) {
  6940. // Finalize the clauses that need pre-built expressions for CodeGen.
  6941. for (auto C : Clauses) {
  6942. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6943. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6944. B.NumIterations, *this, CurScope,
  6945. DSAStack))
  6946. return StmtError();
  6947. }
  6948. }
  6949. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6950. return StmtError();
  6951. getCurFunction()->setHasBranchProtectedScope();
  6952. return OMPTargetTeamsDistributeSimdDirective::Create(
  6953. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6954. }
  6955. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  6956. SourceLocation StartLoc,
  6957. SourceLocation LParenLoc,
  6958. SourceLocation EndLoc) {
  6959. OMPClause *Res = nullptr;
  6960. switch (Kind) {
  6961. case OMPC_final:
  6962. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  6963. break;
  6964. case OMPC_num_threads:
  6965. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6966. break;
  6967. case OMPC_safelen:
  6968. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6969. break;
  6970. case OMPC_simdlen:
  6971. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6972. break;
  6973. case OMPC_collapse:
  6974. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  6975. break;
  6976. case OMPC_ordered:
  6977. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  6978. break;
  6979. case OMPC_device:
  6980. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  6981. break;
  6982. case OMPC_num_teams:
  6983. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6984. break;
  6985. case OMPC_thread_limit:
  6986. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  6987. break;
  6988. case OMPC_priority:
  6989. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  6990. break;
  6991. case OMPC_grainsize:
  6992. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  6993. break;
  6994. case OMPC_num_tasks:
  6995. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  6996. break;
  6997. case OMPC_hint:
  6998. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  6999. break;
  7000. case OMPC_if:
  7001. case OMPC_default:
  7002. case OMPC_proc_bind:
  7003. case OMPC_schedule:
  7004. case OMPC_private:
  7005. case OMPC_firstprivate:
  7006. case OMPC_lastprivate:
  7007. case OMPC_shared:
  7008. case OMPC_reduction:
  7009. case OMPC_task_reduction:
  7010. case OMPC_in_reduction:
  7011. case OMPC_linear:
  7012. case OMPC_aligned:
  7013. case OMPC_copyin:
  7014. case OMPC_copyprivate:
  7015. case OMPC_nowait:
  7016. case OMPC_untied:
  7017. case OMPC_mergeable:
  7018. case OMPC_threadprivate:
  7019. case OMPC_flush:
  7020. case OMPC_read:
  7021. case OMPC_write:
  7022. case OMPC_update:
  7023. case OMPC_capture:
  7024. case OMPC_seq_cst:
  7025. case OMPC_depend:
  7026. case OMPC_threads:
  7027. case OMPC_simd:
  7028. case OMPC_map:
  7029. case OMPC_nogroup:
  7030. case OMPC_dist_schedule:
  7031. case OMPC_defaultmap:
  7032. case OMPC_unknown:
  7033. case OMPC_uniform:
  7034. case OMPC_to:
  7035. case OMPC_from:
  7036. case OMPC_use_device_ptr:
  7037. case OMPC_is_device_ptr:
  7038. llvm_unreachable("Clause is not allowed.");
  7039. }
  7040. return Res;
  7041. }
  7042. // An OpenMP directive such as 'target parallel' has two captured regions:
  7043. // for the 'target' and 'parallel' respectively. This function returns
  7044. // the region in which to capture expressions associated with a clause.
  7045. // A return value of OMPD_unknown signifies that the expression should not
  7046. // be captured.
  7047. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7048. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7049. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7050. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7051. switch (CKind) {
  7052. case OMPC_if:
  7053. switch (DKind) {
  7054. case OMPD_target_parallel:
  7055. case OMPD_target_parallel_for:
  7056. case OMPD_target_parallel_for_simd:
  7057. case OMPD_target_teams_distribute_parallel_for:
  7058. case OMPD_target_teams_distribute_parallel_for_simd:
  7059. // If this clause applies to the nested 'parallel' region, capture within
  7060. // the 'target' region, otherwise do not capture.
  7061. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7062. CaptureRegion = OMPD_target;
  7063. break;
  7064. case OMPD_teams_distribute_parallel_for:
  7065. case OMPD_teams_distribute_parallel_for_simd:
  7066. CaptureRegion = OMPD_teams;
  7067. break;
  7068. case OMPD_cancel:
  7069. case OMPD_parallel:
  7070. case OMPD_parallel_sections:
  7071. case OMPD_parallel_for:
  7072. case OMPD_parallel_for_simd:
  7073. case OMPD_target:
  7074. case OMPD_target_simd:
  7075. case OMPD_target_teams:
  7076. case OMPD_target_teams_distribute:
  7077. case OMPD_target_teams_distribute_simd:
  7078. case OMPD_distribute_parallel_for:
  7079. case OMPD_distribute_parallel_for_simd:
  7080. case OMPD_task:
  7081. case OMPD_taskloop:
  7082. case OMPD_taskloop_simd:
  7083. case OMPD_target_data:
  7084. case OMPD_target_enter_data:
  7085. case OMPD_target_exit_data:
  7086. case OMPD_target_update:
  7087. // Do not capture if-clause expressions.
  7088. break;
  7089. case OMPD_threadprivate:
  7090. case OMPD_taskyield:
  7091. case OMPD_barrier:
  7092. case OMPD_taskwait:
  7093. case OMPD_cancellation_point:
  7094. case OMPD_flush:
  7095. case OMPD_declare_reduction:
  7096. case OMPD_declare_simd:
  7097. case OMPD_declare_target:
  7098. case OMPD_end_declare_target:
  7099. case OMPD_teams:
  7100. case OMPD_simd:
  7101. case OMPD_for:
  7102. case OMPD_for_simd:
  7103. case OMPD_sections:
  7104. case OMPD_section:
  7105. case OMPD_single:
  7106. case OMPD_master:
  7107. case OMPD_critical:
  7108. case OMPD_taskgroup:
  7109. case OMPD_distribute:
  7110. case OMPD_ordered:
  7111. case OMPD_atomic:
  7112. case OMPD_distribute_simd:
  7113. case OMPD_teams_distribute:
  7114. case OMPD_teams_distribute_simd:
  7115. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7116. case OMPD_unknown:
  7117. llvm_unreachable("Unknown OpenMP directive");
  7118. }
  7119. break;
  7120. case OMPC_num_threads:
  7121. switch (DKind) {
  7122. case OMPD_target_parallel:
  7123. case OMPD_target_parallel_for:
  7124. case OMPD_target_parallel_for_simd:
  7125. case OMPD_target_teams_distribute_parallel_for:
  7126. case OMPD_target_teams_distribute_parallel_for_simd:
  7127. CaptureRegion = OMPD_target;
  7128. break;
  7129. case OMPD_teams_distribute_parallel_for:
  7130. case OMPD_teams_distribute_parallel_for_simd:
  7131. CaptureRegion = OMPD_teams;
  7132. break;
  7133. case OMPD_parallel:
  7134. case OMPD_parallel_sections:
  7135. case OMPD_parallel_for:
  7136. case OMPD_parallel_for_simd:
  7137. case OMPD_distribute_parallel_for:
  7138. case OMPD_distribute_parallel_for_simd:
  7139. // Do not capture num_threads-clause expressions.
  7140. break;
  7141. case OMPD_target_data:
  7142. case OMPD_target_enter_data:
  7143. case OMPD_target_exit_data:
  7144. case OMPD_target_update:
  7145. case OMPD_target:
  7146. case OMPD_target_simd:
  7147. case OMPD_target_teams:
  7148. case OMPD_target_teams_distribute:
  7149. case OMPD_target_teams_distribute_simd:
  7150. case OMPD_cancel:
  7151. case OMPD_task:
  7152. case OMPD_taskloop:
  7153. case OMPD_taskloop_simd:
  7154. case OMPD_threadprivate:
  7155. case OMPD_taskyield:
  7156. case OMPD_barrier:
  7157. case OMPD_taskwait:
  7158. case OMPD_cancellation_point:
  7159. case OMPD_flush:
  7160. case OMPD_declare_reduction:
  7161. case OMPD_declare_simd:
  7162. case OMPD_declare_target:
  7163. case OMPD_end_declare_target:
  7164. case OMPD_teams:
  7165. case OMPD_simd:
  7166. case OMPD_for:
  7167. case OMPD_for_simd:
  7168. case OMPD_sections:
  7169. case OMPD_section:
  7170. case OMPD_single:
  7171. case OMPD_master:
  7172. case OMPD_critical:
  7173. case OMPD_taskgroup:
  7174. case OMPD_distribute:
  7175. case OMPD_ordered:
  7176. case OMPD_atomic:
  7177. case OMPD_distribute_simd:
  7178. case OMPD_teams_distribute:
  7179. case OMPD_teams_distribute_simd:
  7180. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7181. case OMPD_unknown:
  7182. llvm_unreachable("Unknown OpenMP directive");
  7183. }
  7184. break;
  7185. case OMPC_num_teams:
  7186. switch (DKind) {
  7187. case OMPD_target_teams:
  7188. case OMPD_target_teams_distribute:
  7189. case OMPD_target_teams_distribute_simd:
  7190. case OMPD_target_teams_distribute_parallel_for:
  7191. case OMPD_target_teams_distribute_parallel_for_simd:
  7192. CaptureRegion = OMPD_target;
  7193. break;
  7194. case OMPD_teams_distribute_parallel_for:
  7195. case OMPD_teams_distribute_parallel_for_simd:
  7196. case OMPD_teams:
  7197. case OMPD_teams_distribute:
  7198. case OMPD_teams_distribute_simd:
  7199. // Do not capture num_teams-clause expressions.
  7200. break;
  7201. case OMPD_distribute_parallel_for:
  7202. case OMPD_distribute_parallel_for_simd:
  7203. case OMPD_task:
  7204. case OMPD_taskloop:
  7205. case OMPD_taskloop_simd:
  7206. case OMPD_target_data:
  7207. case OMPD_target_enter_data:
  7208. case OMPD_target_exit_data:
  7209. case OMPD_target_update:
  7210. case OMPD_cancel:
  7211. case OMPD_parallel:
  7212. case OMPD_parallel_sections:
  7213. case OMPD_parallel_for:
  7214. case OMPD_parallel_for_simd:
  7215. case OMPD_target:
  7216. case OMPD_target_simd:
  7217. case OMPD_target_parallel:
  7218. case OMPD_target_parallel_for:
  7219. case OMPD_target_parallel_for_simd:
  7220. case OMPD_threadprivate:
  7221. case OMPD_taskyield:
  7222. case OMPD_barrier:
  7223. case OMPD_taskwait:
  7224. case OMPD_cancellation_point:
  7225. case OMPD_flush:
  7226. case OMPD_declare_reduction:
  7227. case OMPD_declare_simd:
  7228. case OMPD_declare_target:
  7229. case OMPD_end_declare_target:
  7230. case OMPD_simd:
  7231. case OMPD_for:
  7232. case OMPD_for_simd:
  7233. case OMPD_sections:
  7234. case OMPD_section:
  7235. case OMPD_single:
  7236. case OMPD_master:
  7237. case OMPD_critical:
  7238. case OMPD_taskgroup:
  7239. case OMPD_distribute:
  7240. case OMPD_ordered:
  7241. case OMPD_atomic:
  7242. case OMPD_distribute_simd:
  7243. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7244. case OMPD_unknown:
  7245. llvm_unreachable("Unknown OpenMP directive");
  7246. }
  7247. break;
  7248. case OMPC_thread_limit:
  7249. switch (DKind) {
  7250. case OMPD_target_teams:
  7251. case OMPD_target_teams_distribute:
  7252. case OMPD_target_teams_distribute_simd:
  7253. case OMPD_target_teams_distribute_parallel_for:
  7254. case OMPD_target_teams_distribute_parallel_for_simd:
  7255. CaptureRegion = OMPD_target;
  7256. break;
  7257. case OMPD_teams_distribute_parallel_for:
  7258. case OMPD_teams_distribute_parallel_for_simd:
  7259. case OMPD_teams:
  7260. case OMPD_teams_distribute:
  7261. case OMPD_teams_distribute_simd:
  7262. // Do not capture thread_limit-clause expressions.
  7263. break;
  7264. case OMPD_distribute_parallel_for:
  7265. case OMPD_distribute_parallel_for_simd:
  7266. case OMPD_task:
  7267. case OMPD_taskloop:
  7268. case OMPD_taskloop_simd:
  7269. case OMPD_target_data:
  7270. case OMPD_target_enter_data:
  7271. case OMPD_target_exit_data:
  7272. case OMPD_target_update:
  7273. case OMPD_cancel:
  7274. case OMPD_parallel:
  7275. case OMPD_parallel_sections:
  7276. case OMPD_parallel_for:
  7277. case OMPD_parallel_for_simd:
  7278. case OMPD_target:
  7279. case OMPD_target_simd:
  7280. case OMPD_target_parallel:
  7281. case OMPD_target_parallel_for:
  7282. case OMPD_target_parallel_for_simd:
  7283. case OMPD_threadprivate:
  7284. case OMPD_taskyield:
  7285. case OMPD_barrier:
  7286. case OMPD_taskwait:
  7287. case OMPD_cancellation_point:
  7288. case OMPD_flush:
  7289. case OMPD_declare_reduction:
  7290. case OMPD_declare_simd:
  7291. case OMPD_declare_target:
  7292. case OMPD_end_declare_target:
  7293. case OMPD_simd:
  7294. case OMPD_for:
  7295. case OMPD_for_simd:
  7296. case OMPD_sections:
  7297. case OMPD_section:
  7298. case OMPD_single:
  7299. case OMPD_master:
  7300. case OMPD_critical:
  7301. case OMPD_taskgroup:
  7302. case OMPD_distribute:
  7303. case OMPD_ordered:
  7304. case OMPD_atomic:
  7305. case OMPD_distribute_simd:
  7306. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7307. case OMPD_unknown:
  7308. llvm_unreachable("Unknown OpenMP directive");
  7309. }
  7310. break;
  7311. case OMPC_schedule:
  7312. switch (DKind) {
  7313. case OMPD_target_parallel_for:
  7314. case OMPD_target_parallel_for_simd:
  7315. case OMPD_target_teams_distribute_parallel_for:
  7316. case OMPD_target_teams_distribute_parallel_for_simd:
  7317. CaptureRegion = OMPD_target;
  7318. break;
  7319. case OMPD_teams_distribute_parallel_for:
  7320. case OMPD_teams_distribute_parallel_for_simd:
  7321. CaptureRegion = OMPD_teams;
  7322. break;
  7323. case OMPD_parallel_for:
  7324. case OMPD_parallel_for_simd:
  7325. case OMPD_distribute_parallel_for:
  7326. case OMPD_distribute_parallel_for_simd:
  7327. CaptureRegion = OMPD_parallel;
  7328. break;
  7329. case OMPD_for:
  7330. case OMPD_for_simd:
  7331. // Do not capture schedule-clause expressions.
  7332. break;
  7333. case OMPD_task:
  7334. case OMPD_taskloop:
  7335. case OMPD_taskloop_simd:
  7336. case OMPD_target_data:
  7337. case OMPD_target_enter_data:
  7338. case OMPD_target_exit_data:
  7339. case OMPD_target_update:
  7340. case OMPD_teams:
  7341. case OMPD_teams_distribute:
  7342. case OMPD_teams_distribute_simd:
  7343. case OMPD_target_teams_distribute:
  7344. case OMPD_target_teams_distribute_simd:
  7345. case OMPD_target:
  7346. case OMPD_target_simd:
  7347. case OMPD_target_parallel:
  7348. case OMPD_cancel:
  7349. case OMPD_parallel:
  7350. case OMPD_parallel_sections:
  7351. case OMPD_threadprivate:
  7352. case OMPD_taskyield:
  7353. case OMPD_barrier:
  7354. case OMPD_taskwait:
  7355. case OMPD_cancellation_point:
  7356. case OMPD_flush:
  7357. case OMPD_declare_reduction:
  7358. case OMPD_declare_simd:
  7359. case OMPD_declare_target:
  7360. case OMPD_end_declare_target:
  7361. case OMPD_simd:
  7362. case OMPD_sections:
  7363. case OMPD_section:
  7364. case OMPD_single:
  7365. case OMPD_master:
  7366. case OMPD_critical:
  7367. case OMPD_taskgroup:
  7368. case OMPD_distribute:
  7369. case OMPD_ordered:
  7370. case OMPD_atomic:
  7371. case OMPD_distribute_simd:
  7372. case OMPD_target_teams:
  7373. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7374. case OMPD_unknown:
  7375. llvm_unreachable("Unknown OpenMP directive");
  7376. }
  7377. break;
  7378. case OMPC_dist_schedule:
  7379. switch (DKind) {
  7380. case OMPD_teams_distribute_parallel_for:
  7381. case OMPD_teams_distribute_parallel_for_simd:
  7382. case OMPD_teams_distribute:
  7383. case OMPD_teams_distribute_simd:
  7384. CaptureRegion = OMPD_teams;
  7385. break;
  7386. case OMPD_target_teams_distribute_parallel_for:
  7387. case OMPD_target_teams_distribute_parallel_for_simd:
  7388. case OMPD_target_teams_distribute:
  7389. case OMPD_target_teams_distribute_simd:
  7390. CaptureRegion = OMPD_target;
  7391. break;
  7392. case OMPD_distribute_parallel_for:
  7393. case OMPD_distribute_parallel_for_simd:
  7394. CaptureRegion = OMPD_parallel;
  7395. break;
  7396. case OMPD_distribute:
  7397. case OMPD_distribute_simd:
  7398. // Do not capture thread_limit-clause expressions.
  7399. break;
  7400. case OMPD_parallel_for:
  7401. case OMPD_parallel_for_simd:
  7402. case OMPD_target_parallel_for_simd:
  7403. case OMPD_target_parallel_for:
  7404. case OMPD_task:
  7405. case OMPD_taskloop:
  7406. case OMPD_taskloop_simd:
  7407. case OMPD_target_data:
  7408. case OMPD_target_enter_data:
  7409. case OMPD_target_exit_data:
  7410. case OMPD_target_update:
  7411. case OMPD_teams:
  7412. case OMPD_target:
  7413. case OMPD_target_simd:
  7414. case OMPD_target_parallel:
  7415. case OMPD_cancel:
  7416. case OMPD_parallel:
  7417. case OMPD_parallel_sections:
  7418. case OMPD_threadprivate:
  7419. case OMPD_taskyield:
  7420. case OMPD_barrier:
  7421. case OMPD_taskwait:
  7422. case OMPD_cancellation_point:
  7423. case OMPD_flush:
  7424. case OMPD_declare_reduction:
  7425. case OMPD_declare_simd:
  7426. case OMPD_declare_target:
  7427. case OMPD_end_declare_target:
  7428. case OMPD_simd:
  7429. case OMPD_for:
  7430. case OMPD_for_simd:
  7431. case OMPD_sections:
  7432. case OMPD_section:
  7433. case OMPD_single:
  7434. case OMPD_master:
  7435. case OMPD_critical:
  7436. case OMPD_taskgroup:
  7437. case OMPD_ordered:
  7438. case OMPD_atomic:
  7439. case OMPD_target_teams:
  7440. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7441. case OMPD_unknown:
  7442. llvm_unreachable("Unknown OpenMP directive");
  7443. }
  7444. break;
  7445. case OMPC_device:
  7446. switch (DKind) {
  7447. case OMPD_target_teams:
  7448. case OMPD_target_teams_distribute:
  7449. case OMPD_target_teams_distribute_simd:
  7450. case OMPD_target_teams_distribute_parallel_for:
  7451. case OMPD_target_teams_distribute_parallel_for_simd:
  7452. case OMPD_target_data:
  7453. case OMPD_target_enter_data:
  7454. case OMPD_target_exit_data:
  7455. case OMPD_target_update:
  7456. case OMPD_target:
  7457. case OMPD_target_simd:
  7458. case OMPD_target_parallel:
  7459. case OMPD_target_parallel_for:
  7460. case OMPD_target_parallel_for_simd:
  7461. // Do not capture device-clause expressions.
  7462. break;
  7463. case OMPD_teams_distribute_parallel_for:
  7464. case OMPD_teams_distribute_parallel_for_simd:
  7465. case OMPD_teams:
  7466. case OMPD_teams_distribute:
  7467. case OMPD_teams_distribute_simd:
  7468. case OMPD_distribute_parallel_for:
  7469. case OMPD_distribute_parallel_for_simd:
  7470. case OMPD_task:
  7471. case OMPD_taskloop:
  7472. case OMPD_taskloop_simd:
  7473. case OMPD_cancel:
  7474. case OMPD_parallel:
  7475. case OMPD_parallel_sections:
  7476. case OMPD_parallel_for:
  7477. case OMPD_parallel_for_simd:
  7478. case OMPD_threadprivate:
  7479. case OMPD_taskyield:
  7480. case OMPD_barrier:
  7481. case OMPD_taskwait:
  7482. case OMPD_cancellation_point:
  7483. case OMPD_flush:
  7484. case OMPD_declare_reduction:
  7485. case OMPD_declare_simd:
  7486. case OMPD_declare_target:
  7487. case OMPD_end_declare_target:
  7488. case OMPD_simd:
  7489. case OMPD_for:
  7490. case OMPD_for_simd:
  7491. case OMPD_sections:
  7492. case OMPD_section:
  7493. case OMPD_single:
  7494. case OMPD_master:
  7495. case OMPD_critical:
  7496. case OMPD_taskgroup:
  7497. case OMPD_distribute:
  7498. case OMPD_ordered:
  7499. case OMPD_atomic:
  7500. case OMPD_distribute_simd:
  7501. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7502. case OMPD_unknown:
  7503. llvm_unreachable("Unknown OpenMP directive");
  7504. }
  7505. break;
  7506. case OMPC_firstprivate:
  7507. case OMPC_lastprivate:
  7508. case OMPC_reduction:
  7509. case OMPC_task_reduction:
  7510. case OMPC_in_reduction:
  7511. case OMPC_linear:
  7512. case OMPC_default:
  7513. case OMPC_proc_bind:
  7514. case OMPC_final:
  7515. case OMPC_safelen:
  7516. case OMPC_simdlen:
  7517. case OMPC_collapse:
  7518. case OMPC_private:
  7519. case OMPC_shared:
  7520. case OMPC_aligned:
  7521. case OMPC_copyin:
  7522. case OMPC_copyprivate:
  7523. case OMPC_ordered:
  7524. case OMPC_nowait:
  7525. case OMPC_untied:
  7526. case OMPC_mergeable:
  7527. case OMPC_threadprivate:
  7528. case OMPC_flush:
  7529. case OMPC_read:
  7530. case OMPC_write:
  7531. case OMPC_update:
  7532. case OMPC_capture:
  7533. case OMPC_seq_cst:
  7534. case OMPC_depend:
  7535. case OMPC_threads:
  7536. case OMPC_simd:
  7537. case OMPC_map:
  7538. case OMPC_priority:
  7539. case OMPC_grainsize:
  7540. case OMPC_nogroup:
  7541. case OMPC_num_tasks:
  7542. case OMPC_hint:
  7543. case OMPC_defaultmap:
  7544. case OMPC_unknown:
  7545. case OMPC_uniform:
  7546. case OMPC_to:
  7547. case OMPC_from:
  7548. case OMPC_use_device_ptr:
  7549. case OMPC_is_device_ptr:
  7550. llvm_unreachable("Unexpected OpenMP clause.");
  7551. }
  7552. return CaptureRegion;
  7553. }
  7554. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  7555. Expr *Condition, SourceLocation StartLoc,
  7556. SourceLocation LParenLoc,
  7557. SourceLocation NameModifierLoc,
  7558. SourceLocation ColonLoc,
  7559. SourceLocation EndLoc) {
  7560. Expr *ValExpr = Condition;
  7561. Stmt *HelperValStmt = nullptr;
  7562. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7563. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7564. !Condition->isInstantiationDependent() &&
  7565. !Condition->containsUnexpandedParameterPack()) {
  7566. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7567. if (Val.isInvalid())
  7568. return nullptr;
  7569. ValExpr = MakeFullExpr(Val.get()).get();
  7570. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7571. CaptureRegion =
  7572. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  7573. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7574. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7575. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7576. HelperValStmt = buildPreInits(Context, Captures);
  7577. }
  7578. }
  7579. return new (Context)
  7580. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  7581. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  7582. }
  7583. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  7584. SourceLocation StartLoc,
  7585. SourceLocation LParenLoc,
  7586. SourceLocation EndLoc) {
  7587. Expr *ValExpr = Condition;
  7588. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7589. !Condition->isInstantiationDependent() &&
  7590. !Condition->containsUnexpandedParameterPack()) {
  7591. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7592. if (Val.isInvalid())
  7593. return nullptr;
  7594. ValExpr = MakeFullExpr(Val.get()).get();
  7595. }
  7596. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  7597. }
  7598. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  7599. Expr *Op) {
  7600. if (!Op)
  7601. return ExprError();
  7602. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  7603. public:
  7604. IntConvertDiagnoser()
  7605. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  7606. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  7607. QualType T) override {
  7608. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  7609. }
  7610. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  7611. QualType T) override {
  7612. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  7613. }
  7614. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  7615. QualType T,
  7616. QualType ConvTy) override {
  7617. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  7618. }
  7619. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  7620. QualType ConvTy) override {
  7621. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7622. << ConvTy->isEnumeralType() << ConvTy;
  7623. }
  7624. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  7625. QualType T) override {
  7626. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  7627. }
  7628. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  7629. QualType ConvTy) override {
  7630. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7631. << ConvTy->isEnumeralType() << ConvTy;
  7632. }
  7633. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  7634. QualType) override {
  7635. llvm_unreachable("conversion functions are permitted");
  7636. }
  7637. } ConvertDiagnoser;
  7638. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  7639. }
  7640. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  7641. OpenMPClauseKind CKind,
  7642. bool StrictlyPositive) {
  7643. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  7644. !ValExpr->isInstantiationDependent()) {
  7645. SourceLocation Loc = ValExpr->getExprLoc();
  7646. ExprResult Value =
  7647. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  7648. if (Value.isInvalid())
  7649. return false;
  7650. ValExpr = Value.get();
  7651. // The expression must evaluate to a non-negative integer value.
  7652. llvm::APSInt Result;
  7653. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  7654. Result.isSigned() &&
  7655. !((!StrictlyPositive && Result.isNonNegative()) ||
  7656. (StrictlyPositive && Result.isStrictlyPositive()))) {
  7657. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  7658. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7659. << ValExpr->getSourceRange();
  7660. return false;
  7661. }
  7662. }
  7663. return true;
  7664. }
  7665. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  7666. SourceLocation StartLoc,
  7667. SourceLocation LParenLoc,
  7668. SourceLocation EndLoc) {
  7669. Expr *ValExpr = NumThreads;
  7670. Stmt *HelperValStmt = nullptr;
  7671. // OpenMP [2.5, Restrictions]
  7672. // The num_threads expression must evaluate to a positive integer value.
  7673. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  7674. /*StrictlyPositive=*/true))
  7675. return nullptr;
  7676. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7677. OpenMPDirectiveKind CaptureRegion =
  7678. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  7679. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7680. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7681. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7682. HelperValStmt = buildPreInits(Context, Captures);
  7683. }
  7684. return new (Context) OMPNumThreadsClause(
  7685. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  7686. }
  7687. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  7688. OpenMPClauseKind CKind,
  7689. bool StrictlyPositive) {
  7690. if (!E)
  7691. return ExprError();
  7692. if (E->isValueDependent() || E->isTypeDependent() ||
  7693. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  7694. return E;
  7695. llvm::APSInt Result;
  7696. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  7697. if (ICE.isInvalid())
  7698. return ExprError();
  7699. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  7700. (!StrictlyPositive && !Result.isNonNegative())) {
  7701. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  7702. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7703. << E->getSourceRange();
  7704. return ExprError();
  7705. }
  7706. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  7707. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  7708. << E->getSourceRange();
  7709. return ExprError();
  7710. }
  7711. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  7712. DSAStack->setAssociatedLoops(Result.getExtValue());
  7713. else if (CKind == OMPC_ordered)
  7714. DSAStack->setAssociatedLoops(Result.getExtValue());
  7715. return ICE;
  7716. }
  7717. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  7718. SourceLocation LParenLoc,
  7719. SourceLocation EndLoc) {
  7720. // OpenMP [2.8.1, simd construct, Description]
  7721. // The parameter of the safelen clause must be a constant
  7722. // positive integer expression.
  7723. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  7724. if (Safelen.isInvalid())
  7725. return nullptr;
  7726. return new (Context)
  7727. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  7728. }
  7729. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  7730. SourceLocation LParenLoc,
  7731. SourceLocation EndLoc) {
  7732. // OpenMP [2.8.1, simd construct, Description]
  7733. // The parameter of the simdlen clause must be a constant
  7734. // positive integer expression.
  7735. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  7736. if (Simdlen.isInvalid())
  7737. return nullptr;
  7738. return new (Context)
  7739. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  7740. }
  7741. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  7742. SourceLocation StartLoc,
  7743. SourceLocation LParenLoc,
  7744. SourceLocation EndLoc) {
  7745. // OpenMP [2.7.1, loop construct, Description]
  7746. // OpenMP [2.8.1, simd construct, Description]
  7747. // OpenMP [2.9.6, distribute construct, Description]
  7748. // The parameter of the collapse clause must be a constant
  7749. // positive integer expression.
  7750. ExprResult NumForLoopsResult =
  7751. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  7752. if (NumForLoopsResult.isInvalid())
  7753. return nullptr;
  7754. return new (Context)
  7755. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  7756. }
  7757. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  7758. SourceLocation EndLoc,
  7759. SourceLocation LParenLoc,
  7760. Expr *NumForLoops) {
  7761. // OpenMP [2.7.1, loop construct, Description]
  7762. // OpenMP [2.8.1, simd construct, Description]
  7763. // OpenMP [2.9.6, distribute construct, Description]
  7764. // The parameter of the ordered clause must be a constant
  7765. // positive integer expression if any.
  7766. if (NumForLoops && LParenLoc.isValid()) {
  7767. ExprResult NumForLoopsResult =
  7768. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  7769. if (NumForLoopsResult.isInvalid())
  7770. return nullptr;
  7771. NumForLoops = NumForLoopsResult.get();
  7772. } else
  7773. NumForLoops = nullptr;
  7774. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  7775. return new (Context)
  7776. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  7777. }
  7778. OMPClause *Sema::ActOnOpenMPSimpleClause(
  7779. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  7780. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  7781. OMPClause *Res = nullptr;
  7782. switch (Kind) {
  7783. case OMPC_default:
  7784. Res =
  7785. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  7786. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  7787. break;
  7788. case OMPC_proc_bind:
  7789. Res = ActOnOpenMPProcBindClause(
  7790. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  7791. LParenLoc, EndLoc);
  7792. break;
  7793. case OMPC_if:
  7794. case OMPC_final:
  7795. case OMPC_num_threads:
  7796. case OMPC_safelen:
  7797. case OMPC_simdlen:
  7798. case OMPC_collapse:
  7799. case OMPC_schedule:
  7800. case OMPC_private:
  7801. case OMPC_firstprivate:
  7802. case OMPC_lastprivate:
  7803. case OMPC_shared:
  7804. case OMPC_reduction:
  7805. case OMPC_task_reduction:
  7806. case OMPC_in_reduction:
  7807. case OMPC_linear:
  7808. case OMPC_aligned:
  7809. case OMPC_copyin:
  7810. case OMPC_copyprivate:
  7811. case OMPC_ordered:
  7812. case OMPC_nowait:
  7813. case OMPC_untied:
  7814. case OMPC_mergeable:
  7815. case OMPC_threadprivate:
  7816. case OMPC_flush:
  7817. case OMPC_read:
  7818. case OMPC_write:
  7819. case OMPC_update:
  7820. case OMPC_capture:
  7821. case OMPC_seq_cst:
  7822. case OMPC_depend:
  7823. case OMPC_device:
  7824. case OMPC_threads:
  7825. case OMPC_simd:
  7826. case OMPC_map:
  7827. case OMPC_num_teams:
  7828. case OMPC_thread_limit:
  7829. case OMPC_priority:
  7830. case OMPC_grainsize:
  7831. case OMPC_nogroup:
  7832. case OMPC_num_tasks:
  7833. case OMPC_hint:
  7834. case OMPC_dist_schedule:
  7835. case OMPC_defaultmap:
  7836. case OMPC_unknown:
  7837. case OMPC_uniform:
  7838. case OMPC_to:
  7839. case OMPC_from:
  7840. case OMPC_use_device_ptr:
  7841. case OMPC_is_device_ptr:
  7842. llvm_unreachable("Clause is not allowed.");
  7843. }
  7844. return Res;
  7845. }
  7846. static std::string
  7847. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  7848. ArrayRef<unsigned> Exclude = llvm::None) {
  7849. std::string Values;
  7850. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  7851. unsigned Skipped = Exclude.size();
  7852. auto S = Exclude.begin(), E = Exclude.end();
  7853. for (unsigned i = First; i < Last; ++i) {
  7854. if (std::find(S, E, i) != E) {
  7855. --Skipped;
  7856. continue;
  7857. }
  7858. Values += "'";
  7859. Values += getOpenMPSimpleClauseTypeName(K, i);
  7860. Values += "'";
  7861. if (i == Bound - Skipped)
  7862. Values += " or ";
  7863. else if (i != Bound + 1 - Skipped)
  7864. Values += ", ";
  7865. }
  7866. return Values;
  7867. }
  7868. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  7869. SourceLocation KindKwLoc,
  7870. SourceLocation StartLoc,
  7871. SourceLocation LParenLoc,
  7872. SourceLocation EndLoc) {
  7873. if (Kind == OMPC_DEFAULT_unknown) {
  7874. static_assert(OMPC_DEFAULT_unknown > 0,
  7875. "OMPC_DEFAULT_unknown not greater than 0");
  7876. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7877. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  7878. /*Last=*/OMPC_DEFAULT_unknown)
  7879. << getOpenMPClauseName(OMPC_default);
  7880. return nullptr;
  7881. }
  7882. switch (Kind) {
  7883. case OMPC_DEFAULT_none:
  7884. DSAStack->setDefaultDSANone(KindKwLoc);
  7885. break;
  7886. case OMPC_DEFAULT_shared:
  7887. DSAStack->setDefaultDSAShared(KindKwLoc);
  7888. break;
  7889. case OMPC_DEFAULT_unknown:
  7890. llvm_unreachable("Clause kind is not allowed.");
  7891. break;
  7892. }
  7893. return new (Context)
  7894. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7895. }
  7896. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  7897. SourceLocation KindKwLoc,
  7898. SourceLocation StartLoc,
  7899. SourceLocation LParenLoc,
  7900. SourceLocation EndLoc) {
  7901. if (Kind == OMPC_PROC_BIND_unknown) {
  7902. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7903. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  7904. /*Last=*/OMPC_PROC_BIND_unknown)
  7905. << getOpenMPClauseName(OMPC_proc_bind);
  7906. return nullptr;
  7907. }
  7908. return new (Context)
  7909. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7910. }
  7911. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  7912. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  7913. SourceLocation StartLoc, SourceLocation LParenLoc,
  7914. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  7915. SourceLocation EndLoc) {
  7916. OMPClause *Res = nullptr;
  7917. switch (Kind) {
  7918. case OMPC_schedule:
  7919. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  7920. assert(Argument.size() == NumberOfElements &&
  7921. ArgumentLoc.size() == NumberOfElements);
  7922. Res = ActOnOpenMPScheduleClause(
  7923. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  7924. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  7925. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  7926. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  7927. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  7928. break;
  7929. case OMPC_if:
  7930. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  7931. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  7932. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  7933. DelimLoc, EndLoc);
  7934. break;
  7935. case OMPC_dist_schedule:
  7936. Res = ActOnOpenMPDistScheduleClause(
  7937. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  7938. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  7939. break;
  7940. case OMPC_defaultmap:
  7941. enum { Modifier, DefaultmapKind };
  7942. Res = ActOnOpenMPDefaultmapClause(
  7943. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  7944. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  7945. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  7946. EndLoc);
  7947. break;
  7948. case OMPC_final:
  7949. case OMPC_num_threads:
  7950. case OMPC_safelen:
  7951. case OMPC_simdlen:
  7952. case OMPC_collapse:
  7953. case OMPC_default:
  7954. case OMPC_proc_bind:
  7955. case OMPC_private:
  7956. case OMPC_firstprivate:
  7957. case OMPC_lastprivate:
  7958. case OMPC_shared:
  7959. case OMPC_reduction:
  7960. case OMPC_task_reduction:
  7961. case OMPC_in_reduction:
  7962. case OMPC_linear:
  7963. case OMPC_aligned:
  7964. case OMPC_copyin:
  7965. case OMPC_copyprivate:
  7966. case OMPC_ordered:
  7967. case OMPC_nowait:
  7968. case OMPC_untied:
  7969. case OMPC_mergeable:
  7970. case OMPC_threadprivate:
  7971. case OMPC_flush:
  7972. case OMPC_read:
  7973. case OMPC_write:
  7974. case OMPC_update:
  7975. case OMPC_capture:
  7976. case OMPC_seq_cst:
  7977. case OMPC_depend:
  7978. case OMPC_device:
  7979. case OMPC_threads:
  7980. case OMPC_simd:
  7981. case OMPC_map:
  7982. case OMPC_num_teams:
  7983. case OMPC_thread_limit:
  7984. case OMPC_priority:
  7985. case OMPC_grainsize:
  7986. case OMPC_nogroup:
  7987. case OMPC_num_tasks:
  7988. case OMPC_hint:
  7989. case OMPC_unknown:
  7990. case OMPC_uniform:
  7991. case OMPC_to:
  7992. case OMPC_from:
  7993. case OMPC_use_device_ptr:
  7994. case OMPC_is_device_ptr:
  7995. llvm_unreachable("Clause is not allowed.");
  7996. }
  7997. return Res;
  7998. }
  7999. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8000. OpenMPScheduleClauseModifier M2,
  8001. SourceLocation M1Loc, SourceLocation M2Loc) {
  8002. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8003. SmallVector<unsigned, 2> Excluded;
  8004. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8005. Excluded.push_back(M2);
  8006. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8007. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8008. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8009. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8010. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8011. << getListOfPossibleValues(OMPC_schedule,
  8012. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8013. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8014. Excluded)
  8015. << getOpenMPClauseName(OMPC_schedule);
  8016. return true;
  8017. }
  8018. return false;
  8019. }
  8020. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8021. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8022. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8023. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8024. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8025. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8026. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8027. return nullptr;
  8028. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8029. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8030. // but not both.
  8031. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8032. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8033. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8034. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8035. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8036. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8037. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8038. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8039. return nullptr;
  8040. }
  8041. if (Kind == OMPC_SCHEDULE_unknown) {
  8042. std::string Values;
  8043. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8044. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8045. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8046. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8047. Exclude);
  8048. } else {
  8049. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8050. /*Last=*/OMPC_SCHEDULE_unknown);
  8051. }
  8052. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8053. << Values << getOpenMPClauseName(OMPC_schedule);
  8054. return nullptr;
  8055. }
  8056. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8057. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8058. // schedule(guided).
  8059. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8060. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8061. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8062. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8063. diag::err_omp_schedule_nonmonotonic_static);
  8064. return nullptr;
  8065. }
  8066. Expr *ValExpr = ChunkSize;
  8067. Stmt *HelperValStmt = nullptr;
  8068. if (ChunkSize) {
  8069. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8070. !ChunkSize->isInstantiationDependent() &&
  8071. !ChunkSize->containsUnexpandedParameterPack()) {
  8072. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  8073. ExprResult Val =
  8074. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8075. if (Val.isInvalid())
  8076. return nullptr;
  8077. ValExpr = Val.get();
  8078. // OpenMP [2.7.1, Restrictions]
  8079. // chunk_size must be a loop invariant integer expression with a positive
  8080. // value.
  8081. llvm::APSInt Result;
  8082. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8083. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8084. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8085. << "schedule" << 1 << ChunkSize->getSourceRange();
  8086. return nullptr;
  8087. }
  8088. } else if (getOpenMPCaptureRegionForClause(
  8089. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8090. OMPD_unknown &&
  8091. !CurContext->isDependentContext()) {
  8092. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  8093. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8094. HelperValStmt = buildPreInits(Context, Captures);
  8095. }
  8096. }
  8097. }
  8098. return new (Context)
  8099. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8100. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8101. }
  8102. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8103. SourceLocation StartLoc,
  8104. SourceLocation EndLoc) {
  8105. OMPClause *Res = nullptr;
  8106. switch (Kind) {
  8107. case OMPC_ordered:
  8108. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8109. break;
  8110. case OMPC_nowait:
  8111. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8112. break;
  8113. case OMPC_untied:
  8114. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8115. break;
  8116. case OMPC_mergeable:
  8117. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8118. break;
  8119. case OMPC_read:
  8120. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8121. break;
  8122. case OMPC_write:
  8123. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8124. break;
  8125. case OMPC_update:
  8126. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8127. break;
  8128. case OMPC_capture:
  8129. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8130. break;
  8131. case OMPC_seq_cst:
  8132. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8133. break;
  8134. case OMPC_threads:
  8135. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8136. break;
  8137. case OMPC_simd:
  8138. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8139. break;
  8140. case OMPC_nogroup:
  8141. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8142. break;
  8143. case OMPC_if:
  8144. case OMPC_final:
  8145. case OMPC_num_threads:
  8146. case OMPC_safelen:
  8147. case OMPC_simdlen:
  8148. case OMPC_collapse:
  8149. case OMPC_schedule:
  8150. case OMPC_private:
  8151. case OMPC_firstprivate:
  8152. case OMPC_lastprivate:
  8153. case OMPC_shared:
  8154. case OMPC_reduction:
  8155. case OMPC_task_reduction:
  8156. case OMPC_in_reduction:
  8157. case OMPC_linear:
  8158. case OMPC_aligned:
  8159. case OMPC_copyin:
  8160. case OMPC_copyprivate:
  8161. case OMPC_default:
  8162. case OMPC_proc_bind:
  8163. case OMPC_threadprivate:
  8164. case OMPC_flush:
  8165. case OMPC_depend:
  8166. case OMPC_device:
  8167. case OMPC_map:
  8168. case OMPC_num_teams:
  8169. case OMPC_thread_limit:
  8170. case OMPC_priority:
  8171. case OMPC_grainsize:
  8172. case OMPC_num_tasks:
  8173. case OMPC_hint:
  8174. case OMPC_dist_schedule:
  8175. case OMPC_defaultmap:
  8176. case OMPC_unknown:
  8177. case OMPC_uniform:
  8178. case OMPC_to:
  8179. case OMPC_from:
  8180. case OMPC_use_device_ptr:
  8181. case OMPC_is_device_ptr:
  8182. llvm_unreachable("Clause is not allowed.");
  8183. }
  8184. return Res;
  8185. }
  8186. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8187. SourceLocation EndLoc) {
  8188. DSAStack->setNowaitRegion();
  8189. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8190. }
  8191. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8192. SourceLocation EndLoc) {
  8193. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8194. }
  8195. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8196. SourceLocation EndLoc) {
  8197. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8198. }
  8199. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8200. SourceLocation EndLoc) {
  8201. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8202. }
  8203. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8204. SourceLocation EndLoc) {
  8205. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8206. }
  8207. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8208. SourceLocation EndLoc) {
  8209. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8210. }
  8211. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8212. SourceLocation EndLoc) {
  8213. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8214. }
  8215. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8216. SourceLocation EndLoc) {
  8217. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8218. }
  8219. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8220. SourceLocation EndLoc) {
  8221. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8222. }
  8223. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8224. SourceLocation EndLoc) {
  8225. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8226. }
  8227. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8228. SourceLocation EndLoc) {
  8229. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8230. }
  8231. OMPClause *Sema::ActOnOpenMPVarListClause(
  8232. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8233. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8234. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8235. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8236. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8237. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8238. SourceLocation DepLinMapLoc) {
  8239. OMPClause *Res = nullptr;
  8240. switch (Kind) {
  8241. case OMPC_private:
  8242. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8243. break;
  8244. case OMPC_firstprivate:
  8245. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8246. break;
  8247. case OMPC_lastprivate:
  8248. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8249. break;
  8250. case OMPC_shared:
  8251. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8252. break;
  8253. case OMPC_reduction:
  8254. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8255. EndLoc, ReductionIdScopeSpec, ReductionId);
  8256. break;
  8257. case OMPC_task_reduction:
  8258. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8259. EndLoc, ReductionIdScopeSpec,
  8260. ReductionId);
  8261. break;
  8262. case OMPC_in_reduction:
  8263. Res =
  8264. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8265. EndLoc, ReductionIdScopeSpec, ReductionId);
  8266. break;
  8267. case OMPC_linear:
  8268. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8269. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8270. break;
  8271. case OMPC_aligned:
  8272. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8273. ColonLoc, EndLoc);
  8274. break;
  8275. case OMPC_copyin:
  8276. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8277. break;
  8278. case OMPC_copyprivate:
  8279. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8280. break;
  8281. case OMPC_flush:
  8282. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8283. break;
  8284. case OMPC_depend:
  8285. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8286. StartLoc, LParenLoc, EndLoc);
  8287. break;
  8288. case OMPC_map:
  8289. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8290. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8291. LParenLoc, EndLoc);
  8292. break;
  8293. case OMPC_to:
  8294. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8295. break;
  8296. case OMPC_from:
  8297. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8298. break;
  8299. case OMPC_use_device_ptr:
  8300. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8301. break;
  8302. case OMPC_is_device_ptr:
  8303. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8304. break;
  8305. case OMPC_if:
  8306. case OMPC_final:
  8307. case OMPC_num_threads:
  8308. case OMPC_safelen:
  8309. case OMPC_simdlen:
  8310. case OMPC_collapse:
  8311. case OMPC_default:
  8312. case OMPC_proc_bind:
  8313. case OMPC_schedule:
  8314. case OMPC_ordered:
  8315. case OMPC_nowait:
  8316. case OMPC_untied:
  8317. case OMPC_mergeable:
  8318. case OMPC_threadprivate:
  8319. case OMPC_read:
  8320. case OMPC_write:
  8321. case OMPC_update:
  8322. case OMPC_capture:
  8323. case OMPC_seq_cst:
  8324. case OMPC_device:
  8325. case OMPC_threads:
  8326. case OMPC_simd:
  8327. case OMPC_num_teams:
  8328. case OMPC_thread_limit:
  8329. case OMPC_priority:
  8330. case OMPC_grainsize:
  8331. case OMPC_nogroup:
  8332. case OMPC_num_tasks:
  8333. case OMPC_hint:
  8334. case OMPC_dist_schedule:
  8335. case OMPC_defaultmap:
  8336. case OMPC_unknown:
  8337. case OMPC_uniform:
  8338. llvm_unreachable("Clause is not allowed.");
  8339. }
  8340. return Res;
  8341. }
  8342. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  8343. ExprObjectKind OK, SourceLocation Loc) {
  8344. ExprResult Res = BuildDeclRefExpr(
  8345. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  8346. if (!Res.isUsable())
  8347. return ExprError();
  8348. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  8349. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  8350. if (!Res.isUsable())
  8351. return ExprError();
  8352. }
  8353. if (VK != VK_LValue && Res.get()->isGLValue()) {
  8354. Res = DefaultLvalueConversion(Res.get());
  8355. if (!Res.isUsable())
  8356. return ExprError();
  8357. }
  8358. return Res;
  8359. }
  8360. static std::pair<ValueDecl *, bool>
  8361. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  8362. SourceRange &ERange, bool AllowArraySection = false) {
  8363. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  8364. RefExpr->containsUnexpandedParameterPack())
  8365. return std::make_pair(nullptr, true);
  8366. // OpenMP [3.1, C/C++]
  8367. // A list item is a variable name.
  8368. // OpenMP [2.9.3.3, Restrictions, p.1]
  8369. // A variable that is part of another variable (as an array or
  8370. // structure element) cannot appear in a private clause.
  8371. RefExpr = RefExpr->IgnoreParens();
  8372. enum {
  8373. NoArrayExpr = -1,
  8374. ArraySubscript = 0,
  8375. OMPArraySection = 1
  8376. } IsArrayExpr = NoArrayExpr;
  8377. if (AllowArraySection) {
  8378. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  8379. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  8380. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8381. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8382. RefExpr = Base;
  8383. IsArrayExpr = ArraySubscript;
  8384. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  8385. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  8386. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  8387. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  8388. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8389. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8390. RefExpr = Base;
  8391. IsArrayExpr = OMPArraySection;
  8392. }
  8393. }
  8394. ELoc = RefExpr->getExprLoc();
  8395. ERange = RefExpr->getSourceRange();
  8396. RefExpr = RefExpr->IgnoreParenImpCasts();
  8397. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  8398. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  8399. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  8400. (S.getCurrentThisType().isNull() || !ME ||
  8401. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  8402. !isa<FieldDecl>(ME->getMemberDecl()))) {
  8403. if (IsArrayExpr != NoArrayExpr)
  8404. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  8405. << ERange;
  8406. else {
  8407. S.Diag(ELoc,
  8408. AllowArraySection
  8409. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  8410. : diag::err_omp_expected_var_name_member_expr)
  8411. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  8412. }
  8413. return std::make_pair(nullptr, false);
  8414. }
  8415. return std::make_pair(
  8416. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  8417. }
  8418. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  8419. SourceLocation StartLoc,
  8420. SourceLocation LParenLoc,
  8421. SourceLocation EndLoc) {
  8422. SmallVector<Expr *, 8> Vars;
  8423. SmallVector<Expr *, 8> PrivateCopies;
  8424. for (auto &RefExpr : VarList) {
  8425. assert(RefExpr && "NULL expr in OpenMP private clause.");
  8426. SourceLocation ELoc;
  8427. SourceRange ERange;
  8428. Expr *SimpleRefExpr = RefExpr;
  8429. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8430. if (Res.second) {
  8431. // It will be analyzed later.
  8432. Vars.push_back(RefExpr);
  8433. PrivateCopies.push_back(nullptr);
  8434. }
  8435. ValueDecl *D = Res.first;
  8436. if (!D)
  8437. continue;
  8438. QualType Type = D->getType();
  8439. auto *VD = dyn_cast<VarDecl>(D);
  8440. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8441. // A variable that appears in a private clause must not have an incomplete
  8442. // type or a reference type.
  8443. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  8444. continue;
  8445. Type = Type.getNonReferenceType();
  8446. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8447. // in a Construct]
  8448. // Variables with the predetermined data-sharing attributes may not be
  8449. // listed in data-sharing attributes clauses, except for the cases
  8450. // listed below. For these exceptions only, listing a predetermined
  8451. // variable in a data-sharing attribute clause is allowed and overrides
  8452. // the variable's predetermined data-sharing attributes.
  8453. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8454. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  8455. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8456. << getOpenMPClauseName(OMPC_private);
  8457. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8458. continue;
  8459. }
  8460. auto CurrDir = DSAStack->getCurrentDirective();
  8461. // Variably modified types are not supported for tasks.
  8462. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8463. isOpenMPTaskingDirective(CurrDir)) {
  8464. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8465. << getOpenMPClauseName(OMPC_private) << Type
  8466. << getOpenMPDirectiveName(CurrDir);
  8467. bool IsDecl =
  8468. !VD ||
  8469. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8470. Diag(D->getLocation(),
  8471. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8472. << D;
  8473. continue;
  8474. }
  8475. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8476. // A list item cannot appear in both a map clause and a data-sharing
  8477. // attribute clause on the same construct
  8478. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  8479. CurrDir == OMPD_target_teams ||
  8480. CurrDir == OMPD_target_teams_distribute ||
  8481. CurrDir == OMPD_target_teams_distribute_parallel_for ||
  8482. CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
  8483. CurrDir == OMPD_target_teams_distribute_simd ||
  8484. CurrDir == OMPD_target_parallel_for_simd ||
  8485. CurrDir == OMPD_target_parallel_for) {
  8486. OpenMPClauseKind ConflictKind;
  8487. if (DSAStack->checkMappableExprComponentListsForDecl(
  8488. VD, /*CurrentRegionOnly=*/true,
  8489. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8490. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8491. ConflictKind = WhereFoundClauseKind;
  8492. return true;
  8493. })) {
  8494. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8495. << getOpenMPClauseName(OMPC_private)
  8496. << getOpenMPClauseName(ConflictKind)
  8497. << getOpenMPDirectiveName(CurrDir);
  8498. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8499. continue;
  8500. }
  8501. }
  8502. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  8503. // A variable of class type (or array thereof) that appears in a private
  8504. // clause requires an accessible, unambiguous default constructor for the
  8505. // class type.
  8506. // Generate helper private variable and initialize it with the default
  8507. // value. The address of the original variable is replaced by the address of
  8508. // the new private variable in CodeGen. This new variable is not added to
  8509. // IdResolver, so the code in the OpenMP region uses original variable for
  8510. // proper diagnostics.
  8511. Type = Type.getUnqualifiedType();
  8512. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8513. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8514. ActOnUninitializedDecl(VDPrivate);
  8515. if (VDPrivate->isInvalidDecl())
  8516. continue;
  8517. auto VDPrivateRefExpr = buildDeclRefExpr(
  8518. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  8519. DeclRefExpr *Ref = nullptr;
  8520. if (!VD && !CurContext->isDependentContext())
  8521. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8522. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  8523. Vars.push_back((VD || CurContext->isDependentContext())
  8524. ? RefExpr->IgnoreParens()
  8525. : Ref);
  8526. PrivateCopies.push_back(VDPrivateRefExpr);
  8527. }
  8528. if (Vars.empty())
  8529. return nullptr;
  8530. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8531. PrivateCopies);
  8532. }
  8533. namespace {
  8534. class DiagsUninitializedSeveretyRAII {
  8535. private:
  8536. DiagnosticsEngine &Diags;
  8537. SourceLocation SavedLoc;
  8538. bool IsIgnored;
  8539. public:
  8540. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  8541. bool IsIgnored)
  8542. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  8543. if (!IsIgnored) {
  8544. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  8545. /*Map*/ diag::Severity::Ignored, Loc);
  8546. }
  8547. }
  8548. ~DiagsUninitializedSeveretyRAII() {
  8549. if (!IsIgnored)
  8550. Diags.popMappings(SavedLoc);
  8551. }
  8552. };
  8553. }
  8554. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  8555. SourceLocation StartLoc,
  8556. SourceLocation LParenLoc,
  8557. SourceLocation EndLoc) {
  8558. SmallVector<Expr *, 8> Vars;
  8559. SmallVector<Expr *, 8> PrivateCopies;
  8560. SmallVector<Expr *, 8> Inits;
  8561. SmallVector<Decl *, 4> ExprCaptures;
  8562. bool IsImplicitClause =
  8563. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  8564. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  8565. for (auto &RefExpr : VarList) {
  8566. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  8567. SourceLocation ELoc;
  8568. SourceRange ERange;
  8569. Expr *SimpleRefExpr = RefExpr;
  8570. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8571. if (Res.second) {
  8572. // It will be analyzed later.
  8573. Vars.push_back(RefExpr);
  8574. PrivateCopies.push_back(nullptr);
  8575. Inits.push_back(nullptr);
  8576. }
  8577. ValueDecl *D = Res.first;
  8578. if (!D)
  8579. continue;
  8580. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  8581. QualType Type = D->getType();
  8582. auto *VD = dyn_cast<VarDecl>(D);
  8583. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8584. // A variable that appears in a private clause must not have an incomplete
  8585. // type or a reference type.
  8586. if (RequireCompleteType(ELoc, Type,
  8587. diag::err_omp_firstprivate_incomplete_type))
  8588. continue;
  8589. Type = Type.getNonReferenceType();
  8590. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  8591. // A variable of class type (or array thereof) that appears in a private
  8592. // clause requires an accessible, unambiguous copy constructor for the
  8593. // class type.
  8594. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8595. // If an implicit firstprivate variable found it was checked already.
  8596. DSAStackTy::DSAVarData TopDVar;
  8597. if (!IsImplicitClause) {
  8598. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8599. TopDVar = DVar;
  8600. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8601. bool IsConstant = ElemType.isConstant(Context);
  8602. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  8603. // A list item that specifies a given variable may not appear in more
  8604. // than one clause on the same directive, except that a variable may be
  8605. // specified in both firstprivate and lastprivate clauses.
  8606. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8607. // A list item may appear in a firstprivate or lastprivate clause but not
  8608. // both.
  8609. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  8610. (isOpenMPDistributeDirective(CurrDir) ||
  8611. DVar.CKind != OMPC_lastprivate) &&
  8612. DVar.RefExpr) {
  8613. Diag(ELoc, diag::err_omp_wrong_dsa)
  8614. << getOpenMPClauseName(DVar.CKind)
  8615. << getOpenMPClauseName(OMPC_firstprivate);
  8616. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8617. continue;
  8618. }
  8619. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8620. // in a Construct]
  8621. // Variables with the predetermined data-sharing attributes may not be
  8622. // listed in data-sharing attributes clauses, except for the cases
  8623. // listed below. For these exceptions only, listing a predetermined
  8624. // variable in a data-sharing attribute clause is allowed and overrides
  8625. // the variable's predetermined data-sharing attributes.
  8626. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8627. // in a Construct, C/C++, p.2]
  8628. // Variables with const-qualified type having no mutable member may be
  8629. // listed in a firstprivate clause, even if they are static data members.
  8630. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  8631. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  8632. Diag(ELoc, diag::err_omp_wrong_dsa)
  8633. << getOpenMPClauseName(DVar.CKind)
  8634. << getOpenMPClauseName(OMPC_firstprivate);
  8635. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8636. continue;
  8637. }
  8638. // OpenMP [2.9.3.4, Restrictions, p.2]
  8639. // A list item that is private within a parallel region must not appear
  8640. // in a firstprivate clause on a worksharing construct if any of the
  8641. // worksharing regions arising from the worksharing construct ever bind
  8642. // to any of the parallel regions arising from the parallel construct.
  8643. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8644. // A list item that is private within a teams region must not appear in a
  8645. // firstprivate clause on a distribute construct if any of the distribute
  8646. // regions arising from the distribute construct ever bind to any of the
  8647. // teams regions arising from the teams construct.
  8648. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8649. // A list item that appears in a reduction clause of a teams construct
  8650. // must not appear in a firstprivate clause on a distribute construct if
  8651. // any of the distribute regions arising from the distribute construct
  8652. // ever bind to any of the teams regions arising from the teams construct.
  8653. if ((isOpenMPWorksharingDirective(CurrDir) ||
  8654. isOpenMPDistributeDirective(CurrDir)) &&
  8655. !isOpenMPParallelDirective(CurrDir) &&
  8656. !isOpenMPTeamsDirective(CurrDir)) {
  8657. DVar = DSAStack->getImplicitDSA(D, true);
  8658. if (DVar.CKind != OMPC_shared &&
  8659. (isOpenMPParallelDirective(DVar.DKind) ||
  8660. isOpenMPTeamsDirective(DVar.DKind) ||
  8661. DVar.DKind == OMPD_unknown)) {
  8662. Diag(ELoc, diag::err_omp_required_access)
  8663. << getOpenMPClauseName(OMPC_firstprivate)
  8664. << getOpenMPClauseName(OMPC_shared);
  8665. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8666. continue;
  8667. }
  8668. }
  8669. // OpenMP [2.9.3.4, Restrictions, p.3]
  8670. // A list item that appears in a reduction clause of a parallel construct
  8671. // must not appear in a firstprivate clause on a worksharing or task
  8672. // construct if any of the worksharing or task regions arising from the
  8673. // worksharing or task construct ever bind to any of the parallel regions
  8674. // arising from the parallel construct.
  8675. // OpenMP [2.9.3.4, Restrictions, p.4]
  8676. // A list item that appears in a reduction clause in worksharing
  8677. // construct must not appear in a firstprivate clause in a task construct
  8678. // encountered during execution of any of the worksharing regions arising
  8679. // from the worksharing construct.
  8680. if (isOpenMPTaskingDirective(CurrDir)) {
  8681. DVar = DSAStack->hasInnermostDSA(
  8682. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  8683. [](OpenMPDirectiveKind K) -> bool {
  8684. return isOpenMPParallelDirective(K) ||
  8685. isOpenMPWorksharingDirective(K) ||
  8686. isOpenMPTeamsDirective(K);
  8687. },
  8688. /*FromParent=*/true);
  8689. if (DVar.CKind == OMPC_reduction &&
  8690. (isOpenMPParallelDirective(DVar.DKind) ||
  8691. isOpenMPWorksharingDirective(DVar.DKind) ||
  8692. isOpenMPTeamsDirective(DVar.DKind))) {
  8693. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  8694. << getOpenMPDirectiveName(DVar.DKind);
  8695. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8696. continue;
  8697. }
  8698. }
  8699. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8700. // A list item cannot appear in both a map clause and a data-sharing
  8701. // attribute clause on the same construct
  8702. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  8703. OpenMPClauseKind ConflictKind;
  8704. if (DSAStack->checkMappableExprComponentListsForDecl(
  8705. VD, /*CurrentRegionOnly=*/true,
  8706. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8707. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8708. ConflictKind = WhereFoundClauseKind;
  8709. return true;
  8710. })) {
  8711. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8712. << getOpenMPClauseName(OMPC_firstprivate)
  8713. << getOpenMPClauseName(ConflictKind)
  8714. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8715. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8716. continue;
  8717. }
  8718. }
  8719. }
  8720. // Variably modified types are not supported for tasks.
  8721. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8722. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  8723. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8724. << getOpenMPClauseName(OMPC_firstprivate) << Type
  8725. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8726. bool IsDecl =
  8727. !VD ||
  8728. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8729. Diag(D->getLocation(),
  8730. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8731. << D;
  8732. continue;
  8733. }
  8734. Type = Type.getUnqualifiedType();
  8735. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8736. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8737. // Generate helper private variable and initialize it with the value of the
  8738. // original variable. The address of the original variable is replaced by
  8739. // the address of the new private variable in the CodeGen. This new variable
  8740. // is not added to IdResolver, so the code in the OpenMP region uses
  8741. // original variable for proper diagnostics and variable capturing.
  8742. Expr *VDInitRefExpr = nullptr;
  8743. // For arrays generate initializer for single element and replace it by the
  8744. // original array element in CodeGen.
  8745. if (Type->isArrayType()) {
  8746. auto VDInit =
  8747. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  8748. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  8749. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  8750. ElemType = ElemType.getUnqualifiedType();
  8751. auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  8752. ".firstprivate.temp");
  8753. InitializedEntity Entity =
  8754. InitializedEntity::InitializeVariable(VDInitTemp);
  8755. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  8756. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  8757. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  8758. if (Result.isInvalid())
  8759. VDPrivate->setInvalidDecl();
  8760. else
  8761. VDPrivate->setInit(Result.getAs<Expr>());
  8762. // Remove temp variable declaration.
  8763. Context.Deallocate(VDInitTemp);
  8764. } else {
  8765. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  8766. ".firstprivate.temp");
  8767. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  8768. RefExpr->getExprLoc());
  8769. AddInitializerToDecl(VDPrivate,
  8770. DefaultLvalueConversion(VDInitRefExpr).get(),
  8771. /*DirectInit=*/false);
  8772. }
  8773. if (VDPrivate->isInvalidDecl()) {
  8774. if (IsImplicitClause) {
  8775. Diag(RefExpr->getExprLoc(),
  8776. diag::note_omp_task_predetermined_firstprivate_here);
  8777. }
  8778. continue;
  8779. }
  8780. CurContext->addDecl(VDPrivate);
  8781. auto VDPrivateRefExpr = buildDeclRefExpr(
  8782. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  8783. RefExpr->getExprLoc());
  8784. DeclRefExpr *Ref = nullptr;
  8785. if (!VD && !CurContext->isDependentContext()) {
  8786. if (TopDVar.CKind == OMPC_lastprivate)
  8787. Ref = TopDVar.PrivateCopy;
  8788. else {
  8789. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8790. if (!IsOpenMPCapturedDecl(D))
  8791. ExprCaptures.push_back(Ref->getDecl());
  8792. }
  8793. }
  8794. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  8795. Vars.push_back((VD || CurContext->isDependentContext())
  8796. ? RefExpr->IgnoreParens()
  8797. : Ref);
  8798. PrivateCopies.push_back(VDPrivateRefExpr);
  8799. Inits.push_back(VDInitRefExpr);
  8800. }
  8801. if (Vars.empty())
  8802. return nullptr;
  8803. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8804. Vars, PrivateCopies, Inits,
  8805. buildPreInits(Context, ExprCaptures));
  8806. }
  8807. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  8808. SourceLocation StartLoc,
  8809. SourceLocation LParenLoc,
  8810. SourceLocation EndLoc) {
  8811. SmallVector<Expr *, 8> Vars;
  8812. SmallVector<Expr *, 8> SrcExprs;
  8813. SmallVector<Expr *, 8> DstExprs;
  8814. SmallVector<Expr *, 8> AssignmentOps;
  8815. SmallVector<Decl *, 4> ExprCaptures;
  8816. SmallVector<Expr *, 4> ExprPostUpdates;
  8817. for (auto &RefExpr : VarList) {
  8818. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8819. SourceLocation ELoc;
  8820. SourceRange ERange;
  8821. Expr *SimpleRefExpr = RefExpr;
  8822. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8823. if (Res.second) {
  8824. // It will be analyzed later.
  8825. Vars.push_back(RefExpr);
  8826. SrcExprs.push_back(nullptr);
  8827. DstExprs.push_back(nullptr);
  8828. AssignmentOps.push_back(nullptr);
  8829. }
  8830. ValueDecl *D = Res.first;
  8831. if (!D)
  8832. continue;
  8833. QualType Type = D->getType();
  8834. auto *VD = dyn_cast<VarDecl>(D);
  8835. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  8836. // A variable that appears in a lastprivate clause must not have an
  8837. // incomplete type or a reference type.
  8838. if (RequireCompleteType(ELoc, Type,
  8839. diag::err_omp_lastprivate_incomplete_type))
  8840. continue;
  8841. Type = Type.getNonReferenceType();
  8842. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8843. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  8844. // in a Construct]
  8845. // Variables with the predetermined data-sharing attributes may not be
  8846. // listed in data-sharing attributes clauses, except for the cases
  8847. // listed below.
  8848. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8849. // A list item may appear in a firstprivate or lastprivate clause but not
  8850. // both.
  8851. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8852. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  8853. (isOpenMPDistributeDirective(CurrDir) ||
  8854. DVar.CKind != OMPC_firstprivate) &&
  8855. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  8856. Diag(ELoc, diag::err_omp_wrong_dsa)
  8857. << getOpenMPClauseName(DVar.CKind)
  8858. << getOpenMPClauseName(OMPC_lastprivate);
  8859. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8860. continue;
  8861. }
  8862. // OpenMP [2.14.3.5, Restrictions, p.2]
  8863. // A list item that is private within a parallel region, or that appears in
  8864. // the reduction clause of a parallel construct, must not appear in a
  8865. // lastprivate clause on a worksharing construct if any of the corresponding
  8866. // worksharing regions ever binds to any of the corresponding parallel
  8867. // regions.
  8868. DSAStackTy::DSAVarData TopDVar = DVar;
  8869. if (isOpenMPWorksharingDirective(CurrDir) &&
  8870. !isOpenMPParallelDirective(CurrDir) &&
  8871. !isOpenMPTeamsDirective(CurrDir)) {
  8872. DVar = DSAStack->getImplicitDSA(D, true);
  8873. if (DVar.CKind != OMPC_shared) {
  8874. Diag(ELoc, diag::err_omp_required_access)
  8875. << getOpenMPClauseName(OMPC_lastprivate)
  8876. << getOpenMPClauseName(OMPC_shared);
  8877. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8878. continue;
  8879. }
  8880. }
  8881. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  8882. // A variable of class type (or array thereof) that appears in a
  8883. // lastprivate clause requires an accessible, unambiguous default
  8884. // constructor for the class type, unless the list item is also specified
  8885. // in a firstprivate clause.
  8886. // A variable of class type (or array thereof) that appears in a
  8887. // lastprivate clause requires an accessible, unambiguous copy assignment
  8888. // operator for the class type.
  8889. Type = Context.getBaseElementType(Type).getNonReferenceType();
  8890. auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  8891. Type.getUnqualifiedType(), ".lastprivate.src",
  8892. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8893. auto *PseudoSrcExpr =
  8894. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  8895. auto *DstVD =
  8896. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  8897. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8898. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  8899. // For arrays generate assignment operation for single element and replace
  8900. // it by the original array element in CodeGen.
  8901. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  8902. PseudoDstExpr, PseudoSrcExpr);
  8903. if (AssignmentOp.isInvalid())
  8904. continue;
  8905. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  8906. /*DiscardedValue=*/true);
  8907. if (AssignmentOp.isInvalid())
  8908. continue;
  8909. DeclRefExpr *Ref = nullptr;
  8910. if (!VD && !CurContext->isDependentContext()) {
  8911. if (TopDVar.CKind == OMPC_firstprivate)
  8912. Ref = TopDVar.PrivateCopy;
  8913. else {
  8914. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8915. if (!IsOpenMPCapturedDecl(D))
  8916. ExprCaptures.push_back(Ref->getDecl());
  8917. }
  8918. if (TopDVar.CKind == OMPC_firstprivate ||
  8919. (!IsOpenMPCapturedDecl(D) &&
  8920. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  8921. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8922. if (!RefRes.isUsable())
  8923. continue;
  8924. ExprResult PostUpdateRes =
  8925. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  8926. RefRes.get());
  8927. if (!PostUpdateRes.isUsable())
  8928. continue;
  8929. ExprPostUpdates.push_back(
  8930. IgnoredValueConversions(PostUpdateRes.get()).get());
  8931. }
  8932. }
  8933. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  8934. Vars.push_back((VD || CurContext->isDependentContext())
  8935. ? RefExpr->IgnoreParens()
  8936. : Ref);
  8937. SrcExprs.push_back(PseudoSrcExpr);
  8938. DstExprs.push_back(PseudoDstExpr);
  8939. AssignmentOps.push_back(AssignmentOp.get());
  8940. }
  8941. if (Vars.empty())
  8942. return nullptr;
  8943. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8944. Vars, SrcExprs, DstExprs, AssignmentOps,
  8945. buildPreInits(Context, ExprCaptures),
  8946. buildPostUpdate(*this, ExprPostUpdates));
  8947. }
  8948. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  8949. SourceLocation StartLoc,
  8950. SourceLocation LParenLoc,
  8951. SourceLocation EndLoc) {
  8952. SmallVector<Expr *, 8> Vars;
  8953. for (auto &RefExpr : VarList) {
  8954. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8955. SourceLocation ELoc;
  8956. SourceRange ERange;
  8957. Expr *SimpleRefExpr = RefExpr;
  8958. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8959. if (Res.second) {
  8960. // It will be analyzed later.
  8961. Vars.push_back(RefExpr);
  8962. }
  8963. ValueDecl *D = Res.first;
  8964. if (!D)
  8965. continue;
  8966. auto *VD = dyn_cast<VarDecl>(D);
  8967. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8968. // in a Construct]
  8969. // Variables with the predetermined data-sharing attributes may not be
  8970. // listed in data-sharing attributes clauses, except for the cases
  8971. // listed below. For these exceptions only, listing a predetermined
  8972. // variable in a data-sharing attribute clause is allowed and overrides
  8973. // the variable's predetermined data-sharing attributes.
  8974. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8975. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  8976. DVar.RefExpr) {
  8977. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8978. << getOpenMPClauseName(OMPC_shared);
  8979. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8980. continue;
  8981. }
  8982. DeclRefExpr *Ref = nullptr;
  8983. if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  8984. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8985. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  8986. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  8987. ? RefExpr->IgnoreParens()
  8988. : Ref);
  8989. }
  8990. if (Vars.empty())
  8991. return nullptr;
  8992. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  8993. }
  8994. namespace {
  8995. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  8996. DSAStackTy *Stack;
  8997. public:
  8998. bool VisitDeclRefExpr(DeclRefExpr *E) {
  8999. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9000. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  9001. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9002. return false;
  9003. if (DVar.CKind != OMPC_unknown)
  9004. return true;
  9005. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9006. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  9007. /*FromParent=*/true);
  9008. if (DVarPrivate.CKind != OMPC_unknown)
  9009. return true;
  9010. return false;
  9011. }
  9012. return false;
  9013. }
  9014. bool VisitStmt(Stmt *S) {
  9015. for (auto Child : S->children()) {
  9016. if (Child && Visit(Child))
  9017. return true;
  9018. }
  9019. return false;
  9020. }
  9021. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9022. };
  9023. } // namespace
  9024. namespace {
  9025. // Transform MemberExpression for specified FieldDecl of current class to
  9026. // DeclRefExpr to specified OMPCapturedExprDecl.
  9027. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9028. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9029. ValueDecl *Field;
  9030. DeclRefExpr *CapturedExpr;
  9031. public:
  9032. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9033. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9034. ExprResult TransformMemberExpr(MemberExpr *E) {
  9035. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9036. E->getMemberDecl() == Field) {
  9037. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9038. return CapturedExpr;
  9039. }
  9040. return BaseTransform::TransformMemberExpr(E);
  9041. }
  9042. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9043. };
  9044. } // namespace
  9045. template <typename T>
  9046. static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
  9047. const llvm::function_ref<T(ValueDecl *)> &Gen) {
  9048. for (auto &Set : Lookups) {
  9049. for (auto *D : Set) {
  9050. if (auto Res = Gen(cast<ValueDecl>(D)))
  9051. return Res;
  9052. }
  9053. }
  9054. return T();
  9055. }
  9056. static ExprResult
  9057. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9058. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9059. const DeclarationNameInfo &ReductionId, QualType Ty,
  9060. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9061. if (ReductionIdScopeSpec.isInvalid())
  9062. return ExprError();
  9063. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9064. if (S) {
  9065. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9066. Lookup.suppressDiagnostics();
  9067. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9068. auto *D = Lookup.getRepresentativeDecl();
  9069. do {
  9070. S = S->getParent();
  9071. } while (S && !S->isDeclScope(D));
  9072. if (S)
  9073. S = S->getParent();
  9074. Lookups.push_back(UnresolvedSet<8>());
  9075. Lookups.back().append(Lookup.begin(), Lookup.end());
  9076. Lookup.clear();
  9077. }
  9078. } else if (auto *ULE =
  9079. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9080. Lookups.push_back(UnresolvedSet<8>());
  9081. Decl *PrevD = nullptr;
  9082. for (auto *D : ULE->decls()) {
  9083. if (D == PrevD)
  9084. Lookups.push_back(UnresolvedSet<8>());
  9085. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9086. Lookups.back().addDecl(DRD);
  9087. PrevD = D;
  9088. }
  9089. }
  9090. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9091. Ty->isInstantiationDependentType() ||
  9092. Ty->containsUnexpandedParameterPack() ||
  9093. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
  9094. return !D->isInvalidDecl() &&
  9095. (D->getType()->isDependentType() ||
  9096. D->getType()->isInstantiationDependentType() ||
  9097. D->getType()->containsUnexpandedParameterPack());
  9098. })) {
  9099. UnresolvedSet<8> ResSet;
  9100. for (auto &Set : Lookups) {
  9101. ResSet.append(Set.begin(), Set.end());
  9102. // The last item marks the end of all declarations at the specified scope.
  9103. ResSet.addDecl(Set[Set.size() - 1]);
  9104. }
  9105. return UnresolvedLookupExpr::Create(
  9106. SemaRef.Context, /*NamingClass=*/nullptr,
  9107. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9108. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9109. }
  9110. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9111. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9112. if (!D->isInvalidDecl() &&
  9113. SemaRef.Context.hasSameType(D->getType(), Ty))
  9114. return D;
  9115. return nullptr;
  9116. }))
  9117. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9118. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9119. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9120. if (!D->isInvalidDecl() &&
  9121. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9122. !Ty.isMoreQualifiedThan(D->getType()))
  9123. return D;
  9124. return nullptr;
  9125. })) {
  9126. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9127. /*DetectVirtual=*/false);
  9128. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9129. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9130. VD->getType().getUnqualifiedType()))) {
  9131. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9132. /*DiagID=*/0) !=
  9133. Sema::AR_inaccessible) {
  9134. SemaRef.BuildBasePathArray(Paths, BasePath);
  9135. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9136. }
  9137. }
  9138. }
  9139. }
  9140. if (ReductionIdScopeSpec.isSet()) {
  9141. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9142. return ExprError();
  9143. }
  9144. return ExprEmpty();
  9145. }
  9146. namespace {
  9147. /// Data for the reduction-based clauses.
  9148. struct ReductionData {
  9149. /// List of original reduction items.
  9150. SmallVector<Expr *, 8> Vars;
  9151. /// List of private copies of the reduction items.
  9152. SmallVector<Expr *, 8> Privates;
  9153. /// LHS expressions for the reduction_op expressions.
  9154. SmallVector<Expr *, 8> LHSs;
  9155. /// RHS expressions for the reduction_op expressions.
  9156. SmallVector<Expr *, 8> RHSs;
  9157. /// Reduction operation expression.
  9158. SmallVector<Expr *, 8> ReductionOps;
  9159. /// Taskgroup descriptors for the corresponding reduction items in
  9160. /// in_reduction clauses.
  9161. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9162. /// List of captures for clause.
  9163. SmallVector<Decl *, 4> ExprCaptures;
  9164. /// List of postupdate expressions.
  9165. SmallVector<Expr *, 4> ExprPostUpdates;
  9166. ReductionData() = delete;
  9167. /// Reserves required memory for the reduction data.
  9168. ReductionData(unsigned Size) {
  9169. Vars.reserve(Size);
  9170. Privates.reserve(Size);
  9171. LHSs.reserve(Size);
  9172. RHSs.reserve(Size);
  9173. ReductionOps.reserve(Size);
  9174. TaskgroupDescriptors.reserve(Size);
  9175. ExprCaptures.reserve(Size);
  9176. ExprPostUpdates.reserve(Size);
  9177. }
  9178. /// Stores reduction item and reduction operation only (required for dependent
  9179. /// reduction item).
  9180. void push(Expr *Item, Expr *ReductionOp) {
  9181. Vars.emplace_back(Item);
  9182. Privates.emplace_back(nullptr);
  9183. LHSs.emplace_back(nullptr);
  9184. RHSs.emplace_back(nullptr);
  9185. ReductionOps.emplace_back(ReductionOp);
  9186. TaskgroupDescriptors.emplace_back(nullptr);
  9187. }
  9188. /// Stores reduction data.
  9189. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9190. Expr *TaskgroupDescriptor) {
  9191. Vars.emplace_back(Item);
  9192. Privates.emplace_back(Private);
  9193. LHSs.emplace_back(LHS);
  9194. RHSs.emplace_back(RHS);
  9195. ReductionOps.emplace_back(ReductionOp);
  9196. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9197. }
  9198. };
  9199. } // namespace
  9200. static bool CheckOMPArraySectionConstantForReduction(
  9201. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9202. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9203. const Expr *Length = OASE->getLength();
  9204. if (Length == nullptr) {
  9205. // For array sections of the form [1:] or [:], we would need to analyze
  9206. // the lower bound...
  9207. if (OASE->getColonLoc().isValid())
  9208. return false;
  9209. // This is an array subscript which has implicit length 1!
  9210. SingleElement = true;
  9211. ArraySizes.push_back(llvm::APSInt::get(1));
  9212. } else {
  9213. llvm::APSInt ConstantLengthValue;
  9214. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9215. return false;
  9216. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9217. ArraySizes.push_back(ConstantLengthValue);
  9218. }
  9219. // Get the base of this array section and walk up from there.
  9220. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9221. // We require length = 1 for all array sections except the right-most to
  9222. // guarantee that the memory region is contiguous and has no holes in it.
  9223. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  9224. Length = TempOASE->getLength();
  9225. if (Length == nullptr) {
  9226. // For array sections of the form [1:] or [:], we would need to analyze
  9227. // the lower bound...
  9228. if (OASE->getColonLoc().isValid())
  9229. return false;
  9230. // This is an array subscript which has implicit length 1!
  9231. ArraySizes.push_back(llvm::APSInt::get(1));
  9232. } else {
  9233. llvm::APSInt ConstantLengthValue;
  9234. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  9235. ConstantLengthValue.getSExtValue() != 1)
  9236. return false;
  9237. ArraySizes.push_back(ConstantLengthValue);
  9238. }
  9239. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9240. }
  9241. // If we have a single element, we don't need to add the implicit lengths.
  9242. if (!SingleElement) {
  9243. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  9244. // Has implicit length 1!
  9245. ArraySizes.push_back(llvm::APSInt::get(1));
  9246. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9247. }
  9248. }
  9249. // This array section can be privatized as a single value or as a constant
  9250. // sized array.
  9251. return true;
  9252. }
  9253. static bool ActOnOMPReductionKindClause(
  9254. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  9255. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9256. SourceLocation ColonLoc, SourceLocation EndLoc,
  9257. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9258. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  9259. auto DN = ReductionId.getName();
  9260. auto OOK = DN.getCXXOverloadedOperator();
  9261. BinaryOperatorKind BOK = BO_Comma;
  9262. ASTContext &Context = S.Context;
  9263. // OpenMP [2.14.3.6, reduction clause]
  9264. // C
  9265. // reduction-identifier is either an identifier or one of the following
  9266. // operators: +, -, *, &, |, ^, && and ||
  9267. // C++
  9268. // reduction-identifier is either an id-expression or one of the following
  9269. // operators: +, -, *, &, |, ^, && and ||
  9270. switch (OOK) {
  9271. case OO_Plus:
  9272. case OO_Minus:
  9273. BOK = BO_Add;
  9274. break;
  9275. case OO_Star:
  9276. BOK = BO_Mul;
  9277. break;
  9278. case OO_Amp:
  9279. BOK = BO_And;
  9280. break;
  9281. case OO_Pipe:
  9282. BOK = BO_Or;
  9283. break;
  9284. case OO_Caret:
  9285. BOK = BO_Xor;
  9286. break;
  9287. case OO_AmpAmp:
  9288. BOK = BO_LAnd;
  9289. break;
  9290. case OO_PipePipe:
  9291. BOK = BO_LOr;
  9292. break;
  9293. case OO_New:
  9294. case OO_Delete:
  9295. case OO_Array_New:
  9296. case OO_Array_Delete:
  9297. case OO_Slash:
  9298. case OO_Percent:
  9299. case OO_Tilde:
  9300. case OO_Exclaim:
  9301. case OO_Equal:
  9302. case OO_Less:
  9303. case OO_Greater:
  9304. case OO_LessEqual:
  9305. case OO_GreaterEqual:
  9306. case OO_PlusEqual:
  9307. case OO_MinusEqual:
  9308. case OO_StarEqual:
  9309. case OO_SlashEqual:
  9310. case OO_PercentEqual:
  9311. case OO_CaretEqual:
  9312. case OO_AmpEqual:
  9313. case OO_PipeEqual:
  9314. case OO_LessLess:
  9315. case OO_GreaterGreater:
  9316. case OO_LessLessEqual:
  9317. case OO_GreaterGreaterEqual:
  9318. case OO_EqualEqual:
  9319. case OO_ExclaimEqual:
  9320. case OO_Spaceship:
  9321. case OO_PlusPlus:
  9322. case OO_MinusMinus:
  9323. case OO_Comma:
  9324. case OO_ArrowStar:
  9325. case OO_Arrow:
  9326. case OO_Call:
  9327. case OO_Subscript:
  9328. case OO_Conditional:
  9329. case OO_Coawait:
  9330. case NUM_OVERLOADED_OPERATORS:
  9331. llvm_unreachable("Unexpected reduction identifier");
  9332. case OO_None:
  9333. if (auto *II = DN.getAsIdentifierInfo()) {
  9334. if (II->isStr("max"))
  9335. BOK = BO_GT;
  9336. else if (II->isStr("min"))
  9337. BOK = BO_LT;
  9338. }
  9339. break;
  9340. }
  9341. SourceRange ReductionIdRange;
  9342. if (ReductionIdScopeSpec.isValid())
  9343. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  9344. else
  9345. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  9346. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  9347. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  9348. bool FirstIter = true;
  9349. for (auto RefExpr : VarList) {
  9350. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  9351. // OpenMP [2.1, C/C++]
  9352. // A list item is a variable or array section, subject to the restrictions
  9353. // specified in Section 2.4 on page 42 and in each of the sections
  9354. // describing clauses and directives for which a list appears.
  9355. // OpenMP [2.14.3.3, Restrictions, p.1]
  9356. // A variable that is part of another variable (as an array or
  9357. // structure element) cannot appear in a private clause.
  9358. if (!FirstIter && IR != ER)
  9359. ++IR;
  9360. FirstIter = false;
  9361. SourceLocation ELoc;
  9362. SourceRange ERange;
  9363. Expr *SimpleRefExpr = RefExpr;
  9364. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  9365. /*AllowArraySection=*/true);
  9366. if (Res.second) {
  9367. // Try to find 'declare reduction' corresponding construct before using
  9368. // builtin/overloaded operators.
  9369. QualType Type = Context.DependentTy;
  9370. CXXCastPath BasePath;
  9371. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9372. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9373. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9374. Expr *ReductionOp = nullptr;
  9375. if (S.CurContext->isDependentContext() &&
  9376. (DeclareReductionRef.isUnset() ||
  9377. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  9378. ReductionOp = DeclareReductionRef.get();
  9379. // It will be analyzed later.
  9380. RD.push(RefExpr, ReductionOp);
  9381. }
  9382. ValueDecl *D = Res.first;
  9383. if (!D)
  9384. continue;
  9385. Expr *TaskgroupDescriptor = nullptr;
  9386. QualType Type;
  9387. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  9388. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  9389. if (ASE)
  9390. Type = ASE->getType().getNonReferenceType();
  9391. else if (OASE) {
  9392. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  9393. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  9394. Type = ATy->getElementType();
  9395. else
  9396. Type = BaseType->getPointeeType();
  9397. Type = Type.getNonReferenceType();
  9398. } else
  9399. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  9400. auto *VD = dyn_cast<VarDecl>(D);
  9401. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9402. // A variable that appears in a private clause must not have an incomplete
  9403. // type or a reference type.
  9404. if (S.RequireCompleteType(ELoc, Type,
  9405. diag::err_omp_reduction_incomplete_type))
  9406. continue;
  9407. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9408. // A list item that appears in a reduction clause must not be
  9409. // const-qualified.
  9410. if (Type.getNonReferenceType().isConstant(Context)) {
  9411. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  9412. if (!ASE && !OASE) {
  9413. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9414. VarDecl::DeclarationOnly;
  9415. S.Diag(D->getLocation(),
  9416. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9417. << D;
  9418. }
  9419. continue;
  9420. }
  9421. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  9422. // If a list-item is a reference type then it must bind to the same object
  9423. // for all threads of the team.
  9424. if (!ASE && !OASE && VD) {
  9425. VarDecl *VDDef = VD->getDefinition();
  9426. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  9427. DSARefChecker Check(Stack);
  9428. if (Check.Visit(VDDef->getInit())) {
  9429. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  9430. << getOpenMPClauseName(ClauseKind) << ERange;
  9431. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  9432. continue;
  9433. }
  9434. }
  9435. }
  9436. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9437. // in a Construct]
  9438. // Variables with the predetermined data-sharing attributes may not be
  9439. // listed in data-sharing attributes clauses, except for the cases
  9440. // listed below. For these exceptions only, listing a predetermined
  9441. // variable in a data-sharing attribute clause is allowed and overrides
  9442. // the variable's predetermined data-sharing attributes.
  9443. // OpenMP [2.14.3.6, Restrictions, p.3]
  9444. // Any number of reduction clauses can be specified on the directive,
  9445. // but a list item can appear only once in the reduction clauses for that
  9446. // directive.
  9447. DSAStackTy::DSAVarData DVar;
  9448. DVar = Stack->getTopDSA(D, false);
  9449. if (DVar.CKind == OMPC_reduction) {
  9450. S.Diag(ELoc, diag::err_omp_once_referenced)
  9451. << getOpenMPClauseName(ClauseKind);
  9452. if (DVar.RefExpr)
  9453. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  9454. continue;
  9455. } else if (DVar.CKind != OMPC_unknown) {
  9456. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  9457. << getOpenMPClauseName(DVar.CKind)
  9458. << getOpenMPClauseName(OMPC_reduction);
  9459. ReportOriginalDSA(S, Stack, D, DVar);
  9460. continue;
  9461. }
  9462. // OpenMP [2.14.3.6, Restrictions, p.1]
  9463. // A list item that appears in a reduction clause of a worksharing
  9464. // construct must be shared in the parallel regions to which any of the
  9465. // worksharing regions arising from the worksharing construct bind.
  9466. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  9467. if (isOpenMPWorksharingDirective(CurrDir) &&
  9468. !isOpenMPParallelDirective(CurrDir) &&
  9469. !isOpenMPTeamsDirective(CurrDir)) {
  9470. DVar = Stack->getImplicitDSA(D, true);
  9471. if (DVar.CKind != OMPC_shared) {
  9472. S.Diag(ELoc, diag::err_omp_required_access)
  9473. << getOpenMPClauseName(OMPC_reduction)
  9474. << getOpenMPClauseName(OMPC_shared);
  9475. ReportOriginalDSA(S, Stack, D, DVar);
  9476. continue;
  9477. }
  9478. }
  9479. // Try to find 'declare reduction' corresponding construct before using
  9480. // builtin/overloaded operators.
  9481. CXXCastPath BasePath;
  9482. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9483. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9484. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9485. if (DeclareReductionRef.isInvalid())
  9486. continue;
  9487. if (S.CurContext->isDependentContext() &&
  9488. (DeclareReductionRef.isUnset() ||
  9489. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  9490. RD.push(RefExpr, DeclareReductionRef.get());
  9491. continue;
  9492. }
  9493. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  9494. // Not allowed reduction identifier is found.
  9495. S.Diag(ReductionId.getLocStart(),
  9496. diag::err_omp_unknown_reduction_identifier)
  9497. << Type << ReductionIdRange;
  9498. continue;
  9499. }
  9500. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9501. // The type of a list item that appears in a reduction clause must be valid
  9502. // for the reduction-identifier. For a max or min reduction in C, the type
  9503. // of the list item must be an allowed arithmetic data type: char, int,
  9504. // float, double, or _Bool, possibly modified with long, short, signed, or
  9505. // unsigned. For a max or min reduction in C++, the type of the list item
  9506. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  9507. // double, or bool, possibly modified with long, short, signed, or unsigned.
  9508. if (DeclareReductionRef.isUnset()) {
  9509. if ((BOK == BO_GT || BOK == BO_LT) &&
  9510. !(Type->isScalarType() ||
  9511. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  9512. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  9513. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  9514. if (!ASE && !OASE) {
  9515. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9516. VarDecl::DeclarationOnly;
  9517. S.Diag(D->getLocation(),
  9518. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9519. << D;
  9520. }
  9521. continue;
  9522. }
  9523. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  9524. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  9525. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  9526. << getOpenMPClauseName(ClauseKind);
  9527. if (!ASE && !OASE) {
  9528. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9529. VarDecl::DeclarationOnly;
  9530. S.Diag(D->getLocation(),
  9531. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9532. << D;
  9533. }
  9534. continue;
  9535. }
  9536. }
  9537. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  9538. auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  9539. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9540. auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  9541. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9542. auto PrivateTy = Type;
  9543. // Try if we can determine constant lengths for all array sections and avoid
  9544. // the VLA.
  9545. bool ConstantLengthOASE = false;
  9546. if (OASE) {
  9547. bool SingleElement;
  9548. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  9549. ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
  9550. Context, OASE, SingleElement, ArraySizes);
  9551. // If we don't have a single element, we must emit a constant array type.
  9552. if (ConstantLengthOASE && !SingleElement) {
  9553. for (auto &Size : ArraySizes) {
  9554. PrivateTy = Context.getConstantArrayType(
  9555. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  9556. }
  9557. }
  9558. }
  9559. if ((OASE && !ConstantLengthOASE) ||
  9560. (!OASE && !ASE &&
  9561. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  9562. if (!Context.getTargetInfo().isVLASupported() &&
  9563. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  9564. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  9565. S.Diag(ELoc, diag::note_vla_unsupported);
  9566. continue;
  9567. }
  9568. // For arrays/array sections only:
  9569. // Create pseudo array type for private copy. The size for this array will
  9570. // be generated during codegen.
  9571. // For array subscripts or single variables Private Ty is the same as Type
  9572. // (type of the variable or single array element).
  9573. PrivateTy = Context.getVariableArrayType(
  9574. Type,
  9575. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  9576. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  9577. } else if (!ASE && !OASE &&
  9578. Context.getAsArrayType(D->getType().getNonReferenceType()))
  9579. PrivateTy = D->getType().getNonReferenceType();
  9580. // Private copy.
  9581. auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  9582. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9583. // Add initializer for private variable.
  9584. Expr *Init = nullptr;
  9585. auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  9586. auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  9587. if (DeclareReductionRef.isUsable()) {
  9588. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  9589. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  9590. if (DRD->getInitializer()) {
  9591. Init = DRDRef;
  9592. RHSVD->setInit(DRDRef);
  9593. RHSVD->setInitStyle(VarDecl::CallInit);
  9594. }
  9595. } else {
  9596. switch (BOK) {
  9597. case BO_Add:
  9598. case BO_Xor:
  9599. case BO_Or:
  9600. case BO_LOr:
  9601. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  9602. if (Type->isScalarType() || Type->isAnyComplexType())
  9603. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  9604. break;
  9605. case BO_Mul:
  9606. case BO_LAnd:
  9607. if (Type->isScalarType() || Type->isAnyComplexType()) {
  9608. // '*' and '&&' reduction ops - initializer is '1'.
  9609. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  9610. }
  9611. break;
  9612. case BO_And: {
  9613. // '&' reduction op - initializer is '~0'.
  9614. QualType OrigType = Type;
  9615. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  9616. Type = ComplexTy->getElementType();
  9617. if (Type->isRealFloatingType()) {
  9618. llvm::APFloat InitValue =
  9619. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  9620. /*isIEEE=*/true);
  9621. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9622. Type, ELoc);
  9623. } else if (Type->isScalarType()) {
  9624. auto Size = Context.getTypeSize(Type);
  9625. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  9626. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  9627. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9628. }
  9629. if (Init && OrigType->isAnyComplexType()) {
  9630. // Init = 0xFFFF + 0xFFFFi;
  9631. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  9632. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  9633. }
  9634. Type = OrigType;
  9635. break;
  9636. }
  9637. case BO_LT:
  9638. case BO_GT: {
  9639. // 'min' reduction op - initializer is 'Largest representable number in
  9640. // the reduction list item type'.
  9641. // 'max' reduction op - initializer is 'Least representable number in
  9642. // the reduction list item type'.
  9643. if (Type->isIntegerType() || Type->isPointerType()) {
  9644. bool IsSigned = Type->hasSignedIntegerRepresentation();
  9645. auto Size = Context.getTypeSize(Type);
  9646. QualType IntTy =
  9647. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  9648. llvm::APInt InitValue =
  9649. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  9650. : llvm::APInt::getMinValue(Size)
  9651. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  9652. : llvm::APInt::getMaxValue(Size);
  9653. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9654. if (Type->isPointerType()) {
  9655. // Cast to pointer type.
  9656. auto CastExpr = S.BuildCStyleCastExpr(
  9657. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  9658. if (CastExpr.isInvalid())
  9659. continue;
  9660. Init = CastExpr.get();
  9661. }
  9662. } else if (Type->isRealFloatingType()) {
  9663. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  9664. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  9665. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9666. Type, ELoc);
  9667. }
  9668. break;
  9669. }
  9670. case BO_PtrMemD:
  9671. case BO_PtrMemI:
  9672. case BO_MulAssign:
  9673. case BO_Div:
  9674. case BO_Rem:
  9675. case BO_Sub:
  9676. case BO_Shl:
  9677. case BO_Shr:
  9678. case BO_LE:
  9679. case BO_GE:
  9680. case BO_EQ:
  9681. case BO_NE:
  9682. case BO_Cmp:
  9683. case BO_AndAssign:
  9684. case BO_XorAssign:
  9685. case BO_OrAssign:
  9686. case BO_Assign:
  9687. case BO_AddAssign:
  9688. case BO_SubAssign:
  9689. case BO_DivAssign:
  9690. case BO_RemAssign:
  9691. case BO_ShlAssign:
  9692. case BO_ShrAssign:
  9693. case BO_Comma:
  9694. llvm_unreachable("Unexpected reduction operation");
  9695. }
  9696. }
  9697. if (Init && DeclareReductionRef.isUnset())
  9698. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  9699. else if (!Init)
  9700. S.ActOnUninitializedDecl(RHSVD);
  9701. if (RHSVD->isInvalidDecl())
  9702. continue;
  9703. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  9704. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  9705. << Type << ReductionIdRange;
  9706. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9707. VarDecl::DeclarationOnly;
  9708. S.Diag(D->getLocation(),
  9709. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9710. << D;
  9711. continue;
  9712. }
  9713. // Store initializer for single element in private copy. Will be used during
  9714. // codegen.
  9715. PrivateVD->setInit(RHSVD->getInit());
  9716. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  9717. auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  9718. ExprResult ReductionOp;
  9719. if (DeclareReductionRef.isUsable()) {
  9720. QualType RedTy = DeclareReductionRef.get()->getType();
  9721. QualType PtrRedTy = Context.getPointerType(RedTy);
  9722. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  9723. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  9724. if (!BasePath.empty()) {
  9725. LHS = S.DefaultLvalueConversion(LHS.get());
  9726. RHS = S.DefaultLvalueConversion(RHS.get());
  9727. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9728. CK_UncheckedDerivedToBase, LHS.get(),
  9729. &BasePath, LHS.get()->getValueKind());
  9730. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9731. CK_UncheckedDerivedToBase, RHS.get(),
  9732. &BasePath, RHS.get()->getValueKind());
  9733. }
  9734. FunctionProtoType::ExtProtoInfo EPI;
  9735. QualType Params[] = {PtrRedTy, PtrRedTy};
  9736. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  9737. auto *OVE = new (Context) OpaqueValueExpr(
  9738. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  9739. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  9740. Expr *Args[] = {LHS.get(), RHS.get()};
  9741. ReductionOp = new (Context)
  9742. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  9743. } else {
  9744. ReductionOp = S.BuildBinOp(
  9745. Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  9746. if (ReductionOp.isUsable()) {
  9747. if (BOK != BO_LT && BOK != BO_GT) {
  9748. ReductionOp =
  9749. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9750. BO_Assign, LHSDRE, ReductionOp.get());
  9751. } else {
  9752. auto *ConditionalOp = new (Context)
  9753. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  9754. Type, VK_LValue, OK_Ordinary);
  9755. ReductionOp =
  9756. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9757. BO_Assign, LHSDRE, ConditionalOp);
  9758. }
  9759. if (ReductionOp.isUsable())
  9760. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  9761. }
  9762. if (!ReductionOp.isUsable())
  9763. continue;
  9764. }
  9765. // OpenMP [2.15.4.6, Restrictions, p.2]
  9766. // A list item that appears in an in_reduction clause of a task construct
  9767. // must appear in a task_reduction clause of a construct associated with a
  9768. // taskgroup region that includes the participating task in its taskgroup
  9769. // set. The construct associated with the innermost region that meets this
  9770. // condition must specify the same reduction-identifier as the in_reduction
  9771. // clause.
  9772. if (ClauseKind == OMPC_in_reduction) {
  9773. SourceRange ParentSR;
  9774. BinaryOperatorKind ParentBOK;
  9775. const Expr *ParentReductionOp;
  9776. Expr *ParentBOKTD, *ParentReductionOpTD;
  9777. DSAStackTy::DSAVarData ParentBOKDSA =
  9778. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  9779. ParentBOKTD);
  9780. DSAStackTy::DSAVarData ParentReductionOpDSA =
  9781. Stack->getTopMostTaskgroupReductionData(
  9782. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  9783. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  9784. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  9785. if (!IsParentBOK && !IsParentReductionOp) {
  9786. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  9787. continue;
  9788. }
  9789. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  9790. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  9791. IsParentReductionOp) {
  9792. bool EmitError = true;
  9793. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  9794. llvm::FoldingSetNodeID RedId, ParentRedId;
  9795. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  9796. DeclareReductionRef.get()->Profile(RedId, Context,
  9797. /*Canonical=*/true);
  9798. EmitError = RedId != ParentRedId;
  9799. }
  9800. if (EmitError) {
  9801. S.Diag(ReductionId.getLocStart(),
  9802. diag::err_omp_reduction_identifier_mismatch)
  9803. << ReductionIdRange << RefExpr->getSourceRange();
  9804. S.Diag(ParentSR.getBegin(),
  9805. diag::note_omp_previous_reduction_identifier)
  9806. << ParentSR
  9807. << (IsParentBOK ? ParentBOKDSA.RefExpr
  9808. : ParentReductionOpDSA.RefExpr)
  9809. ->getSourceRange();
  9810. continue;
  9811. }
  9812. }
  9813. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  9814. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  9815. }
  9816. DeclRefExpr *Ref = nullptr;
  9817. Expr *VarsExpr = RefExpr->IgnoreParens();
  9818. if (!VD && !S.CurContext->isDependentContext()) {
  9819. if (ASE || OASE) {
  9820. TransformExprToCaptures RebuildToCapture(S, D);
  9821. VarsExpr =
  9822. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  9823. Ref = RebuildToCapture.getCapturedExpr();
  9824. } else {
  9825. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  9826. }
  9827. if (!S.IsOpenMPCapturedDecl(D)) {
  9828. RD.ExprCaptures.emplace_back(Ref->getDecl());
  9829. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9830. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  9831. if (!RefRes.isUsable())
  9832. continue;
  9833. ExprResult PostUpdateRes =
  9834. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9835. RefRes.get());
  9836. if (!PostUpdateRes.isUsable())
  9837. continue;
  9838. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  9839. Stack->getCurrentDirective() == OMPD_taskgroup) {
  9840. S.Diag(RefExpr->getExprLoc(),
  9841. diag::err_omp_reduction_non_addressable_expression)
  9842. << RefExpr->getSourceRange();
  9843. continue;
  9844. }
  9845. RD.ExprPostUpdates.emplace_back(
  9846. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  9847. }
  9848. }
  9849. }
  9850. // All reduction items are still marked as reduction (to do not increase
  9851. // code base size).
  9852. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  9853. if (CurrDir == OMPD_taskgroup) {
  9854. if (DeclareReductionRef.isUsable())
  9855. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  9856. DeclareReductionRef.get());
  9857. else
  9858. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  9859. }
  9860. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  9861. TaskgroupDescriptor);
  9862. }
  9863. return RD.Vars.empty();
  9864. }
  9865. OMPClause *Sema::ActOnOpenMPReductionClause(
  9866. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9867. SourceLocation ColonLoc, SourceLocation EndLoc,
  9868. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9869. ArrayRef<Expr *> UnresolvedReductions) {
  9870. ReductionData RD(VarList.size());
  9871. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  9872. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9873. ReductionIdScopeSpec, ReductionId,
  9874. UnresolvedReductions, RD))
  9875. return nullptr;
  9876. return OMPReductionClause::Create(
  9877. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9878. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9879. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9880. buildPreInits(Context, RD.ExprCaptures),
  9881. buildPostUpdate(*this, RD.ExprPostUpdates));
  9882. }
  9883. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  9884. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9885. SourceLocation ColonLoc, SourceLocation EndLoc,
  9886. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9887. ArrayRef<Expr *> UnresolvedReductions) {
  9888. ReductionData RD(VarList.size());
  9889. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
  9890. VarList, StartLoc, LParenLoc, ColonLoc,
  9891. EndLoc, ReductionIdScopeSpec, ReductionId,
  9892. UnresolvedReductions, RD))
  9893. return nullptr;
  9894. return OMPTaskReductionClause::Create(
  9895. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9896. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9897. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9898. buildPreInits(Context, RD.ExprCaptures),
  9899. buildPostUpdate(*this, RD.ExprPostUpdates));
  9900. }
  9901. OMPClause *Sema::ActOnOpenMPInReductionClause(
  9902. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9903. SourceLocation ColonLoc, SourceLocation EndLoc,
  9904. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9905. ArrayRef<Expr *> UnresolvedReductions) {
  9906. ReductionData RD(VarList.size());
  9907. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  9908. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9909. ReductionIdScopeSpec, ReductionId,
  9910. UnresolvedReductions, RD))
  9911. return nullptr;
  9912. return OMPInReductionClause::Create(
  9913. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9914. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9915. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  9916. buildPreInits(Context, RD.ExprCaptures),
  9917. buildPostUpdate(*this, RD.ExprPostUpdates));
  9918. }
  9919. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  9920. SourceLocation LinLoc) {
  9921. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  9922. LinKind == OMPC_LINEAR_unknown) {
  9923. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  9924. return true;
  9925. }
  9926. return false;
  9927. }
  9928. bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
  9929. OpenMPLinearClauseKind LinKind,
  9930. QualType Type) {
  9931. auto *VD = dyn_cast_or_null<VarDecl>(D);
  9932. // A variable must not have an incomplete type or a reference type.
  9933. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  9934. return true;
  9935. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  9936. !Type->isReferenceType()) {
  9937. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  9938. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  9939. return true;
  9940. }
  9941. Type = Type.getNonReferenceType();
  9942. // A list item must not be const-qualified.
  9943. if (Type.isConstant(Context)) {
  9944. Diag(ELoc, diag::err_omp_const_variable)
  9945. << getOpenMPClauseName(OMPC_linear);
  9946. if (D) {
  9947. bool IsDecl =
  9948. !VD ||
  9949. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9950. Diag(D->getLocation(),
  9951. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9952. << D;
  9953. }
  9954. return true;
  9955. }
  9956. // A list item must be of integral or pointer type.
  9957. Type = Type.getUnqualifiedType().getCanonicalType();
  9958. const auto *Ty = Type.getTypePtrOrNull();
  9959. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  9960. !Ty->isPointerType())) {
  9961. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  9962. if (D) {
  9963. bool IsDecl =
  9964. !VD ||
  9965. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9966. Diag(D->getLocation(),
  9967. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9968. << D;
  9969. }
  9970. return true;
  9971. }
  9972. return false;
  9973. }
  9974. OMPClause *Sema::ActOnOpenMPLinearClause(
  9975. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  9976. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  9977. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  9978. SmallVector<Expr *, 8> Vars;
  9979. SmallVector<Expr *, 8> Privates;
  9980. SmallVector<Expr *, 8> Inits;
  9981. SmallVector<Decl *, 4> ExprCaptures;
  9982. SmallVector<Expr *, 4> ExprPostUpdates;
  9983. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  9984. LinKind = OMPC_LINEAR_val;
  9985. for (auto &RefExpr : VarList) {
  9986. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9987. SourceLocation ELoc;
  9988. SourceRange ERange;
  9989. Expr *SimpleRefExpr = RefExpr;
  9990. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9991. /*AllowArraySection=*/false);
  9992. if (Res.second) {
  9993. // It will be analyzed later.
  9994. Vars.push_back(RefExpr);
  9995. Privates.push_back(nullptr);
  9996. Inits.push_back(nullptr);
  9997. }
  9998. ValueDecl *D = Res.first;
  9999. if (!D)
  10000. continue;
  10001. QualType Type = D->getType();
  10002. auto *VD = dyn_cast<VarDecl>(D);
  10003. // OpenMP [2.14.3.7, linear clause]
  10004. // A list-item cannot appear in more than one linear clause.
  10005. // A list-item that appears in a linear clause cannot appear in any
  10006. // other data-sharing attribute clause.
  10007. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  10008. if (DVar.RefExpr) {
  10009. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10010. << getOpenMPClauseName(OMPC_linear);
  10011. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10012. continue;
  10013. }
  10014. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  10015. continue;
  10016. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10017. // Build private copy of original var.
  10018. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
  10019. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10020. auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10021. // Build var to save initial value.
  10022. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10023. Expr *InitExpr;
  10024. DeclRefExpr *Ref = nullptr;
  10025. if (!VD && !CurContext->isDependentContext()) {
  10026. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10027. if (!IsOpenMPCapturedDecl(D)) {
  10028. ExprCaptures.push_back(Ref->getDecl());
  10029. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10030. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10031. if (!RefRes.isUsable())
  10032. continue;
  10033. ExprResult PostUpdateRes =
  10034. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10035. SimpleRefExpr, RefRes.get());
  10036. if (!PostUpdateRes.isUsable())
  10037. continue;
  10038. ExprPostUpdates.push_back(
  10039. IgnoredValueConversions(PostUpdateRes.get()).get());
  10040. }
  10041. }
  10042. }
  10043. if (LinKind == OMPC_LINEAR_uval)
  10044. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10045. else
  10046. InitExpr = VD ? SimpleRefExpr : Ref;
  10047. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10048. /*DirectInit=*/false);
  10049. auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10050. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10051. Vars.push_back((VD || CurContext->isDependentContext())
  10052. ? RefExpr->IgnoreParens()
  10053. : Ref);
  10054. Privates.push_back(PrivateRef);
  10055. Inits.push_back(InitRef);
  10056. }
  10057. if (Vars.empty())
  10058. return nullptr;
  10059. Expr *StepExpr = Step;
  10060. Expr *CalcStepExpr = nullptr;
  10061. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10062. !Step->isInstantiationDependent() &&
  10063. !Step->containsUnexpandedParameterPack()) {
  10064. SourceLocation StepLoc = Step->getLocStart();
  10065. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10066. if (Val.isInvalid())
  10067. return nullptr;
  10068. StepExpr = Val.get();
  10069. // Build var to save the step value.
  10070. VarDecl *SaveVar =
  10071. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10072. ExprResult SaveRef =
  10073. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10074. ExprResult CalcStep =
  10075. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10076. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10077. // Warn about zero linear step (it would be probably better specified as
  10078. // making corresponding variables 'const').
  10079. llvm::APSInt Result;
  10080. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10081. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10082. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10083. << (Vars.size() > 1);
  10084. if (!IsConstant && CalcStep.isUsable()) {
  10085. // Calculate the step beforehand instead of doing this on each iteration.
  10086. // (This is not used if the number of iterations may be kfold-ed).
  10087. CalcStepExpr = CalcStep.get();
  10088. }
  10089. }
  10090. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10091. ColonLoc, EndLoc, Vars, Privates, Inits,
  10092. StepExpr, CalcStepExpr,
  10093. buildPreInits(Context, ExprCaptures),
  10094. buildPostUpdate(*this, ExprPostUpdates));
  10095. }
  10096. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10097. Expr *NumIterations, Sema &SemaRef,
  10098. Scope *S, DSAStackTy *Stack) {
  10099. // Walk the vars and build update/final expressions for the CodeGen.
  10100. SmallVector<Expr *, 8> Updates;
  10101. SmallVector<Expr *, 8> Finals;
  10102. Expr *Step = Clause.getStep();
  10103. Expr *CalcStep = Clause.getCalcStep();
  10104. // OpenMP [2.14.3.7, linear clause]
  10105. // If linear-step is not specified it is assumed to be 1.
  10106. if (Step == nullptr)
  10107. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10108. else if (CalcStep) {
  10109. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10110. }
  10111. bool HasErrors = false;
  10112. auto CurInit = Clause.inits().begin();
  10113. auto CurPrivate = Clause.privates().begin();
  10114. auto LinKind = Clause.getModifier();
  10115. for (auto &RefExpr : Clause.varlists()) {
  10116. SourceLocation ELoc;
  10117. SourceRange ERange;
  10118. Expr *SimpleRefExpr = RefExpr;
  10119. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  10120. /*AllowArraySection=*/false);
  10121. ValueDecl *D = Res.first;
  10122. if (Res.second || !D) {
  10123. Updates.push_back(nullptr);
  10124. Finals.push_back(nullptr);
  10125. HasErrors = true;
  10126. continue;
  10127. }
  10128. auto &&Info = Stack->isLoopControlVariable(D);
  10129. // OpenMP [2.15.11, distribute simd Construct]
  10130. // A list item may not appear in a linear clause, unless it is the loop
  10131. // iteration variable.
  10132. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10133. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10134. SemaRef.Diag(ELoc,
  10135. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10136. Updates.push_back(nullptr);
  10137. Finals.push_back(nullptr);
  10138. HasErrors = true;
  10139. continue;
  10140. }
  10141. Expr *InitExpr = *CurInit;
  10142. // Build privatized reference to the current linear var.
  10143. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10144. Expr *CapturedRef;
  10145. if (LinKind == OMPC_LINEAR_uval)
  10146. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10147. else
  10148. CapturedRef =
  10149. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10150. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10151. /*RefersToCapture=*/true);
  10152. // Build update: Var = InitExpr + IV * Step
  10153. ExprResult Update;
  10154. if (!Info.first) {
  10155. Update =
  10156. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10157. InitExpr, IV, Step, /* Subtract */ false);
  10158. } else
  10159. Update = *CurPrivate;
  10160. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  10161. /*DiscardedValue=*/true);
  10162. // Build final: Var = InitExpr + NumIterations * Step
  10163. ExprResult Final;
  10164. if (!Info.first) {
  10165. Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10166. InitExpr, NumIterations, Step,
  10167. /* Subtract */ false);
  10168. } else
  10169. Final = *CurPrivate;
  10170. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  10171. /*DiscardedValue=*/true);
  10172. if (!Update.isUsable() || !Final.isUsable()) {
  10173. Updates.push_back(nullptr);
  10174. Finals.push_back(nullptr);
  10175. HasErrors = true;
  10176. } else {
  10177. Updates.push_back(Update.get());
  10178. Finals.push_back(Final.get());
  10179. }
  10180. ++CurInit;
  10181. ++CurPrivate;
  10182. }
  10183. Clause.setUpdates(Updates);
  10184. Clause.setFinals(Finals);
  10185. return HasErrors;
  10186. }
  10187. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10188. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10189. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10190. SmallVector<Expr *, 8> Vars;
  10191. for (auto &RefExpr : VarList) {
  10192. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10193. SourceLocation ELoc;
  10194. SourceRange ERange;
  10195. Expr *SimpleRefExpr = RefExpr;
  10196. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10197. /*AllowArraySection=*/false);
  10198. if (Res.second) {
  10199. // It will be analyzed later.
  10200. Vars.push_back(RefExpr);
  10201. }
  10202. ValueDecl *D = Res.first;
  10203. if (!D)
  10204. continue;
  10205. QualType QType = D->getType();
  10206. auto *VD = dyn_cast<VarDecl>(D);
  10207. // OpenMP [2.8.1, simd construct, Restrictions]
  10208. // The type of list items appearing in the aligned clause must be
  10209. // array, pointer, reference to array, or reference to pointer.
  10210. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10211. const Type *Ty = QType.getTypePtrOrNull();
  10212. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10213. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10214. << QType << getLangOpts().CPlusPlus << ERange;
  10215. bool IsDecl =
  10216. !VD ||
  10217. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10218. Diag(D->getLocation(),
  10219. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10220. << D;
  10221. continue;
  10222. }
  10223. // OpenMP [2.8.1, simd construct, Restrictions]
  10224. // A list-item cannot appear in more than one aligned clause.
  10225. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  10226. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  10227. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  10228. << getOpenMPClauseName(OMPC_aligned);
  10229. continue;
  10230. }
  10231. DeclRefExpr *Ref = nullptr;
  10232. if (!VD && IsOpenMPCapturedDecl(D))
  10233. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10234. Vars.push_back(DefaultFunctionArrayConversion(
  10235. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  10236. .get());
  10237. }
  10238. // OpenMP [2.8.1, simd construct, Description]
  10239. // The parameter of the aligned clause, alignment, must be a constant
  10240. // positive integer expression.
  10241. // If no optional parameter is specified, implementation-defined default
  10242. // alignments for SIMD instructions on the target platforms are assumed.
  10243. if (Alignment != nullptr) {
  10244. ExprResult AlignResult =
  10245. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  10246. if (AlignResult.isInvalid())
  10247. return nullptr;
  10248. Alignment = AlignResult.get();
  10249. }
  10250. if (Vars.empty())
  10251. return nullptr;
  10252. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  10253. EndLoc, Vars, Alignment);
  10254. }
  10255. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  10256. SourceLocation StartLoc,
  10257. SourceLocation LParenLoc,
  10258. SourceLocation EndLoc) {
  10259. SmallVector<Expr *, 8> Vars;
  10260. SmallVector<Expr *, 8> SrcExprs;
  10261. SmallVector<Expr *, 8> DstExprs;
  10262. SmallVector<Expr *, 8> AssignmentOps;
  10263. for (auto &RefExpr : VarList) {
  10264. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  10265. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10266. // It will be analyzed later.
  10267. Vars.push_back(RefExpr);
  10268. SrcExprs.push_back(nullptr);
  10269. DstExprs.push_back(nullptr);
  10270. AssignmentOps.push_back(nullptr);
  10271. continue;
  10272. }
  10273. SourceLocation ELoc = RefExpr->getExprLoc();
  10274. // OpenMP [2.1, C/C++]
  10275. // A list item is a variable name.
  10276. // OpenMP [2.14.4.1, Restrictions, p.1]
  10277. // A list item that appears in a copyin clause must be threadprivate.
  10278. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  10279. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  10280. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  10281. << 0 << RefExpr->getSourceRange();
  10282. continue;
  10283. }
  10284. Decl *D = DE->getDecl();
  10285. VarDecl *VD = cast<VarDecl>(D);
  10286. QualType Type = VD->getType();
  10287. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  10288. // It will be analyzed later.
  10289. Vars.push_back(DE);
  10290. SrcExprs.push_back(nullptr);
  10291. DstExprs.push_back(nullptr);
  10292. AssignmentOps.push_back(nullptr);
  10293. continue;
  10294. }
  10295. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  10296. // A list item that appears in a copyin clause must be threadprivate.
  10297. if (!DSAStack->isThreadPrivate(VD)) {
  10298. Diag(ELoc, diag::err_omp_required_access)
  10299. << getOpenMPClauseName(OMPC_copyin)
  10300. << getOpenMPDirectiveName(OMPD_threadprivate);
  10301. continue;
  10302. }
  10303. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10304. // A variable of class type (or array thereof) that appears in a
  10305. // copyin clause requires an accessible, unambiguous copy assignment
  10306. // operator for the class type.
  10307. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  10308. auto *SrcVD =
  10309. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  10310. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10311. auto *PseudoSrcExpr = buildDeclRefExpr(
  10312. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  10313. auto *DstVD =
  10314. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  10315. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10316. auto *PseudoDstExpr =
  10317. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  10318. // For arrays generate assignment operation for single element and replace
  10319. // it by the original array element in CodeGen.
  10320. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  10321. PseudoDstExpr, PseudoSrcExpr);
  10322. if (AssignmentOp.isInvalid())
  10323. continue;
  10324. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  10325. /*DiscardedValue=*/true);
  10326. if (AssignmentOp.isInvalid())
  10327. continue;
  10328. DSAStack->addDSA(VD, DE, OMPC_copyin);
  10329. Vars.push_back(DE);
  10330. SrcExprs.push_back(PseudoSrcExpr);
  10331. DstExprs.push_back(PseudoDstExpr);
  10332. AssignmentOps.push_back(AssignmentOp.get());
  10333. }
  10334. if (Vars.empty())
  10335. return nullptr;
  10336. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  10337. SrcExprs, DstExprs, AssignmentOps);
  10338. }
  10339. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  10340. SourceLocation StartLoc,
  10341. SourceLocation LParenLoc,
  10342. SourceLocation EndLoc) {
  10343. SmallVector<Expr *, 8> Vars;
  10344. SmallVector<Expr *, 8> SrcExprs;
  10345. SmallVector<Expr *, 8> DstExprs;
  10346. SmallVector<Expr *, 8> AssignmentOps;
  10347. for (auto &RefExpr : VarList) {
  10348. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10349. SourceLocation ELoc;
  10350. SourceRange ERange;
  10351. Expr *SimpleRefExpr = RefExpr;
  10352. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10353. /*AllowArraySection=*/false);
  10354. if (Res.second) {
  10355. // It will be analyzed later.
  10356. Vars.push_back(RefExpr);
  10357. SrcExprs.push_back(nullptr);
  10358. DstExprs.push_back(nullptr);
  10359. AssignmentOps.push_back(nullptr);
  10360. }
  10361. ValueDecl *D = Res.first;
  10362. if (!D)
  10363. continue;
  10364. QualType Type = D->getType();
  10365. auto *VD = dyn_cast<VarDecl>(D);
  10366. // OpenMP [2.14.4.2, Restrictions, p.2]
  10367. // A list item that appears in a copyprivate clause may not appear in a
  10368. // private or firstprivate clause on the single construct.
  10369. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  10370. auto DVar = DSAStack->getTopDSA(D, false);
  10371. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  10372. DVar.RefExpr) {
  10373. Diag(ELoc, diag::err_omp_wrong_dsa)
  10374. << getOpenMPClauseName(DVar.CKind)
  10375. << getOpenMPClauseName(OMPC_copyprivate);
  10376. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10377. continue;
  10378. }
  10379. // OpenMP [2.11.4.2, Restrictions, p.1]
  10380. // All list items that appear in a copyprivate clause must be either
  10381. // threadprivate or private in the enclosing context.
  10382. if (DVar.CKind == OMPC_unknown) {
  10383. DVar = DSAStack->getImplicitDSA(D, false);
  10384. if (DVar.CKind == OMPC_shared) {
  10385. Diag(ELoc, diag::err_omp_required_access)
  10386. << getOpenMPClauseName(OMPC_copyprivate)
  10387. << "threadprivate or private in the enclosing context";
  10388. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10389. continue;
  10390. }
  10391. }
  10392. }
  10393. // Variably modified types are not supported.
  10394. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  10395. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10396. << getOpenMPClauseName(OMPC_copyprivate) << Type
  10397. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10398. bool IsDecl =
  10399. !VD ||
  10400. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10401. Diag(D->getLocation(),
  10402. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10403. << D;
  10404. continue;
  10405. }
  10406. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10407. // A variable of class type (or array thereof) that appears in a
  10408. // copyin clause requires an accessible, unambiguous copy assignment
  10409. // operator for the class type.
  10410. Type = Context.getBaseElementType(Type.getNonReferenceType())
  10411. .getUnqualifiedType();
  10412. auto *SrcVD =
  10413. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  10414. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10415. auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  10416. auto *DstVD =
  10417. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  10418. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10419. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10420. auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10421. PseudoDstExpr, PseudoSrcExpr);
  10422. if (AssignmentOp.isInvalid())
  10423. continue;
  10424. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  10425. /*DiscardedValue=*/true);
  10426. if (AssignmentOp.isInvalid())
  10427. continue;
  10428. // No need to mark vars as copyprivate, they are already threadprivate or
  10429. // implicitly private.
  10430. assert(VD || IsOpenMPCapturedDecl(D));
  10431. Vars.push_back(
  10432. VD ? RefExpr->IgnoreParens()
  10433. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  10434. SrcExprs.push_back(PseudoSrcExpr);
  10435. DstExprs.push_back(PseudoDstExpr);
  10436. AssignmentOps.push_back(AssignmentOp.get());
  10437. }
  10438. if (Vars.empty())
  10439. return nullptr;
  10440. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10441. Vars, SrcExprs, DstExprs, AssignmentOps);
  10442. }
  10443. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  10444. SourceLocation StartLoc,
  10445. SourceLocation LParenLoc,
  10446. SourceLocation EndLoc) {
  10447. if (VarList.empty())
  10448. return nullptr;
  10449. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  10450. }
  10451. OMPClause *
  10452. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  10453. SourceLocation DepLoc, SourceLocation ColonLoc,
  10454. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  10455. SourceLocation LParenLoc, SourceLocation EndLoc) {
  10456. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  10457. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  10458. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10459. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  10460. return nullptr;
  10461. }
  10462. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  10463. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  10464. DepKind == OMPC_DEPEND_sink)) {
  10465. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  10466. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10467. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  10468. /*Last=*/OMPC_DEPEND_unknown, Except)
  10469. << getOpenMPClauseName(OMPC_depend);
  10470. return nullptr;
  10471. }
  10472. SmallVector<Expr *, 8> Vars;
  10473. DSAStackTy::OperatorOffsetTy OpsOffs;
  10474. llvm::APSInt DepCounter(/*BitWidth=*/32);
  10475. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  10476. if (DepKind == OMPC_DEPEND_sink) {
  10477. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  10478. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  10479. TotalDepCount.setIsUnsigned(/*Val=*/true);
  10480. }
  10481. }
  10482. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  10483. DSAStack->getParentOrderedRegionParam()) {
  10484. for (auto &RefExpr : VarList) {
  10485. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  10486. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10487. // It will be analyzed later.
  10488. Vars.push_back(RefExpr);
  10489. continue;
  10490. }
  10491. SourceLocation ELoc = RefExpr->getExprLoc();
  10492. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  10493. if (DepKind == OMPC_DEPEND_sink) {
  10494. if (DepCounter >= TotalDepCount) {
  10495. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  10496. continue;
  10497. }
  10498. ++DepCounter;
  10499. // OpenMP [2.13.9, Summary]
  10500. // depend(dependence-type : vec), where dependence-type is:
  10501. // 'sink' and where vec is the iteration vector, which has the form:
  10502. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  10503. // where n is the value specified by the ordered clause in the loop
  10504. // directive, xi denotes the loop iteration variable of the i-th nested
  10505. // loop associated with the loop directive, and di is a constant
  10506. // non-negative integer.
  10507. if (CurContext->isDependentContext()) {
  10508. // It will be analyzed later.
  10509. Vars.push_back(RefExpr);
  10510. continue;
  10511. }
  10512. SimpleExpr = SimpleExpr->IgnoreImplicit();
  10513. OverloadedOperatorKind OOK = OO_None;
  10514. SourceLocation OOLoc;
  10515. Expr *LHS = SimpleExpr;
  10516. Expr *RHS = nullptr;
  10517. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  10518. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  10519. OOLoc = BO->getOperatorLoc();
  10520. LHS = BO->getLHS()->IgnoreParenImpCasts();
  10521. RHS = BO->getRHS()->IgnoreParenImpCasts();
  10522. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  10523. OOK = OCE->getOperator();
  10524. OOLoc = OCE->getOperatorLoc();
  10525. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10526. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  10527. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  10528. OOK = MCE->getMethodDecl()
  10529. ->getNameInfo()
  10530. .getName()
  10531. .getCXXOverloadedOperator();
  10532. OOLoc = MCE->getCallee()->getExprLoc();
  10533. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  10534. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10535. }
  10536. SourceLocation ELoc;
  10537. SourceRange ERange;
  10538. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  10539. /*AllowArraySection=*/false);
  10540. if (Res.second) {
  10541. // It will be analyzed later.
  10542. Vars.push_back(RefExpr);
  10543. }
  10544. ValueDecl *D = Res.first;
  10545. if (!D)
  10546. continue;
  10547. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  10548. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  10549. continue;
  10550. }
  10551. if (RHS) {
  10552. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  10553. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  10554. if (RHSRes.isInvalid())
  10555. continue;
  10556. }
  10557. if (!CurContext->isDependentContext() &&
  10558. DSAStack->getParentOrderedRegionParam() &&
  10559. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  10560. ValueDecl* VD = DSAStack->getParentLoopControlVariable(
  10561. DepCounter.getZExtValue());
  10562. if (VD) {
  10563. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10564. << 1 << VD;
  10565. } else {
  10566. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  10567. }
  10568. continue;
  10569. }
  10570. OpsOffs.push_back({RHS, OOK});
  10571. } else {
  10572. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  10573. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  10574. (ASE &&
  10575. !ASE->getBase()
  10576. ->getType()
  10577. .getNonReferenceType()
  10578. ->isPointerType() &&
  10579. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  10580. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10581. << RefExpr->getSourceRange();
  10582. continue;
  10583. }
  10584. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  10585. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  10586. ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  10587. RefExpr->IgnoreParenImpCasts());
  10588. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  10589. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  10590. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10591. << RefExpr->getSourceRange();
  10592. continue;
  10593. }
  10594. }
  10595. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  10596. }
  10597. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  10598. TotalDepCount > VarList.size() &&
  10599. DSAStack->getParentOrderedRegionParam() &&
  10600. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  10601. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
  10602. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  10603. }
  10604. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  10605. Vars.empty())
  10606. return nullptr;
  10607. }
  10608. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10609. DepKind, DepLoc, ColonLoc, Vars);
  10610. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
  10611. DSAStack->addDoacrossDependClause(C, OpsOffs);
  10612. return C;
  10613. }
  10614. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  10615. SourceLocation LParenLoc,
  10616. SourceLocation EndLoc) {
  10617. Expr *ValExpr = Device;
  10618. Stmt *HelperValStmt = nullptr;
  10619. // OpenMP [2.9.1, Restrictions]
  10620. // The device expression must evaluate to a non-negative integer value.
  10621. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  10622. /*StrictlyPositive=*/false))
  10623. return nullptr;
  10624. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10625. OpenMPDirectiveKind CaptureRegion =
  10626. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  10627. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10628. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  10629. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10630. HelperValStmt = buildPreInits(Context, Captures);
  10631. }
  10632. return new (Context)
  10633. OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
  10634. }
  10635. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  10636. DSAStackTy *Stack, QualType QTy) {
  10637. NamedDecl *ND;
  10638. if (QTy->isIncompleteType(&ND)) {
  10639. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  10640. return false;
  10641. }
  10642. return true;
  10643. }
  10644. /// \brief Return true if it can be proven that the provided array expression
  10645. /// (array section or array subscript) does NOT specify the whole size of the
  10646. /// array whose base type is \a BaseQTy.
  10647. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  10648. const Expr *E,
  10649. QualType BaseQTy) {
  10650. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10651. // If this is an array subscript, it refers to the whole size if the size of
  10652. // the dimension is constant and equals 1. Also, an array section assumes the
  10653. // format of an array subscript if no colon is used.
  10654. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  10655. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10656. return ATy->getSize().getSExtValue() != 1;
  10657. // Size can't be evaluated statically.
  10658. return false;
  10659. }
  10660. assert(OASE && "Expecting array section if not an array subscript.");
  10661. auto *LowerBound = OASE->getLowerBound();
  10662. auto *Length = OASE->getLength();
  10663. // If there is a lower bound that does not evaluates to zero, we are not
  10664. // covering the whole dimension.
  10665. if (LowerBound) {
  10666. llvm::APSInt ConstLowerBound;
  10667. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  10668. return false; // Can't get the integer value as a constant.
  10669. if (ConstLowerBound.getSExtValue())
  10670. return true;
  10671. }
  10672. // If we don't have a length we covering the whole dimension.
  10673. if (!Length)
  10674. return false;
  10675. // If the base is a pointer, we don't have a way to get the size of the
  10676. // pointee.
  10677. if (BaseQTy->isPointerType())
  10678. return false;
  10679. // We can only check if the length is the same as the size of the dimension
  10680. // if we have a constant array.
  10681. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  10682. if (!CATy)
  10683. return false;
  10684. llvm::APSInt ConstLength;
  10685. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10686. return false; // Can't get the integer value as a constant.
  10687. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  10688. }
  10689. // Return true if it can be proven that the provided array expression (array
  10690. // section or array subscript) does NOT specify a single element of the array
  10691. // whose base type is \a BaseQTy.
  10692. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  10693. const Expr *E,
  10694. QualType BaseQTy) {
  10695. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10696. // An array subscript always refer to a single element. Also, an array section
  10697. // assumes the format of an array subscript if no colon is used.
  10698. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  10699. return false;
  10700. assert(OASE && "Expecting array section if not an array subscript.");
  10701. auto *Length = OASE->getLength();
  10702. // If we don't have a length we have to check if the array has unitary size
  10703. // for this dimension. Also, we should always expect a length if the base type
  10704. // is pointer.
  10705. if (!Length) {
  10706. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10707. return ATy->getSize().getSExtValue() != 1;
  10708. // We cannot assume anything.
  10709. return false;
  10710. }
  10711. // Check if the length evaluates to 1.
  10712. llvm::APSInt ConstLength;
  10713. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10714. return false; // Can't get the integer value as a constant.
  10715. return ConstLength.getSExtValue() != 1;
  10716. }
  10717. // Return the expression of the base of the mappable expression or null if it
  10718. // cannot be determined and do all the necessary checks to see if the expression
  10719. // is valid as a standalone mappable expression. In the process, record all the
  10720. // components of the expression.
  10721. static Expr *CheckMapClauseExpressionBase(
  10722. Sema &SemaRef, Expr *E,
  10723. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  10724. OpenMPClauseKind CKind, bool NoDiagnose) {
  10725. SourceLocation ELoc = E->getExprLoc();
  10726. SourceRange ERange = E->getSourceRange();
  10727. // The base of elements of list in a map clause have to be either:
  10728. // - a reference to variable or field.
  10729. // - a member expression.
  10730. // - an array expression.
  10731. //
  10732. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  10733. // reference to 'r'.
  10734. //
  10735. // If we have:
  10736. //
  10737. // struct SS {
  10738. // Bla S;
  10739. // foo() {
  10740. // #pragma omp target map (S.Arr[:12]);
  10741. // }
  10742. // }
  10743. //
  10744. // We want to retrieve the member expression 'this->S';
  10745. Expr *RelevantExpr = nullptr;
  10746. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  10747. // If a list item is an array section, it must specify contiguous storage.
  10748. //
  10749. // For this restriction it is sufficient that we make sure only references
  10750. // to variables or fields and array expressions, and that no array sections
  10751. // exist except in the rightmost expression (unless they cover the whole
  10752. // dimension of the array). E.g. these would be invalid:
  10753. //
  10754. // r.ArrS[3:5].Arr[6:7]
  10755. //
  10756. // r.ArrS[3:5].x
  10757. //
  10758. // but these would be valid:
  10759. // r.ArrS[3].Arr[6:7]
  10760. //
  10761. // r.ArrS[3].x
  10762. bool AllowUnitySizeArraySection = true;
  10763. bool AllowWholeSizeArraySection = true;
  10764. while (!RelevantExpr) {
  10765. E = E->IgnoreParenImpCasts();
  10766. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  10767. if (!isa<VarDecl>(CurE->getDecl()))
  10768. return nullptr;
  10769. RelevantExpr = CurE;
  10770. // If we got a reference to a declaration, we should not expect any array
  10771. // section before that.
  10772. AllowUnitySizeArraySection = false;
  10773. AllowWholeSizeArraySection = false;
  10774. // Record the component.
  10775. CurComponents.emplace_back(CurE, CurE->getDecl());
  10776. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  10777. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  10778. if (isa<CXXThisExpr>(BaseE))
  10779. // We found a base expression: this->Val.
  10780. RelevantExpr = CurE;
  10781. else
  10782. E = BaseE;
  10783. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  10784. if (!NoDiagnose) {
  10785. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  10786. << CurE->getSourceRange();
  10787. return nullptr;
  10788. }
  10789. if (RelevantExpr)
  10790. return nullptr;
  10791. continue;
  10792. }
  10793. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  10794. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  10795. // A bit-field cannot appear in a map clause.
  10796. //
  10797. if (FD->isBitField()) {
  10798. if (!NoDiagnose) {
  10799. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  10800. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  10801. return nullptr;
  10802. }
  10803. if (RelevantExpr)
  10804. return nullptr;
  10805. continue;
  10806. }
  10807. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10808. // If the type of a list item is a reference to a type T then the type
  10809. // will be considered to be T for all purposes of this clause.
  10810. QualType CurType = BaseE->getType().getNonReferenceType();
  10811. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  10812. // A list item cannot be a variable that is a member of a structure with
  10813. // a union type.
  10814. //
  10815. if (auto *RT = CurType->getAs<RecordType>()) {
  10816. if (RT->isUnionType()) {
  10817. if (!NoDiagnose) {
  10818. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  10819. << CurE->getSourceRange();
  10820. return nullptr;
  10821. }
  10822. continue;
  10823. }
  10824. }
  10825. // If we got a member expression, we should not expect any array section
  10826. // before that:
  10827. //
  10828. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  10829. // If a list item is an element of a structure, only the rightmost symbol
  10830. // of the variable reference can be an array section.
  10831. //
  10832. AllowUnitySizeArraySection = false;
  10833. AllowWholeSizeArraySection = false;
  10834. // Record the component.
  10835. CurComponents.emplace_back(CurE, FD);
  10836. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  10837. E = CurE->getBase()->IgnoreParenImpCasts();
  10838. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  10839. if (!NoDiagnose) {
  10840. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10841. << 0 << CurE->getSourceRange();
  10842. return nullptr;
  10843. }
  10844. continue;
  10845. }
  10846. // If we got an array subscript that express the whole dimension we
  10847. // can have any array expressions before. If it only expressing part of
  10848. // the dimension, we can only have unitary-size array expressions.
  10849. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  10850. E->getType()))
  10851. AllowWholeSizeArraySection = false;
  10852. // Record the component - we don't have any declaration associated.
  10853. CurComponents.emplace_back(CurE, nullptr);
  10854. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  10855. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  10856. E = CurE->getBase()->IgnoreParenImpCasts();
  10857. QualType CurType =
  10858. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10859. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10860. // If the type of a list item is a reference to a type T then the type
  10861. // will be considered to be T for all purposes of this clause.
  10862. if (CurType->isReferenceType())
  10863. CurType = CurType->getPointeeType();
  10864. bool IsPointer = CurType->isAnyPointerType();
  10865. if (!IsPointer && !CurType->isArrayType()) {
  10866. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10867. << 0 << CurE->getSourceRange();
  10868. return nullptr;
  10869. }
  10870. bool NotWhole =
  10871. CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  10872. bool NotUnity =
  10873. CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  10874. if (AllowWholeSizeArraySection) {
  10875. // Any array section is currently allowed. Allowing a whole size array
  10876. // section implies allowing a unity array section as well.
  10877. //
  10878. // If this array section refers to the whole dimension we can still
  10879. // accept other array sections before this one, except if the base is a
  10880. // pointer. Otherwise, only unitary sections are accepted.
  10881. if (NotWhole || IsPointer)
  10882. AllowWholeSizeArraySection = false;
  10883. } else if (AllowUnitySizeArraySection && NotUnity) {
  10884. // A unity or whole array section is not allowed and that is not
  10885. // compatible with the properties of the current array section.
  10886. SemaRef.Diag(
  10887. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  10888. << CurE->getSourceRange();
  10889. return nullptr;
  10890. }
  10891. // Record the component - we don't have any declaration associated.
  10892. CurComponents.emplace_back(CurE, nullptr);
  10893. } else {
  10894. if (!NoDiagnose) {
  10895. // If nothing else worked, this is not a valid map clause expression.
  10896. SemaRef.Diag(
  10897. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  10898. << ERange;
  10899. }
  10900. return nullptr;
  10901. }
  10902. }
  10903. return RelevantExpr;
  10904. }
  10905. // Return true if expression E associated with value VD has conflicts with other
  10906. // map information.
  10907. static bool CheckMapConflicts(
  10908. Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
  10909. bool CurrentRegionOnly,
  10910. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  10911. OpenMPClauseKind CKind) {
  10912. assert(VD && E);
  10913. SourceLocation ELoc = E->getExprLoc();
  10914. SourceRange ERange = E->getSourceRange();
  10915. // In order to easily check the conflicts we need to match each component of
  10916. // the expression under test with the components of the expressions that are
  10917. // already in the stack.
  10918. assert(!CurComponents.empty() && "Map clause expression with no components!");
  10919. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  10920. "Map clause expression with unexpected base!");
  10921. // Variables to help detecting enclosing problems in data environment nests.
  10922. bool IsEnclosedByDataEnvironmentExpr = false;
  10923. const Expr *EnclosingExpr = nullptr;
  10924. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  10925. VD, CurrentRegionOnly,
  10926. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  10927. StackComponents,
  10928. OpenMPClauseKind) -> bool {
  10929. assert(!StackComponents.empty() &&
  10930. "Map clause expression with no components!");
  10931. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  10932. "Map clause expression with unexpected base!");
  10933. // The whole expression in the stack.
  10934. auto *RE = StackComponents.front().getAssociatedExpression();
  10935. // Expressions must start from the same base. Here we detect at which
  10936. // point both expressions diverge from each other and see if we can
  10937. // detect if the memory referred to both expressions is contiguous and
  10938. // do not overlap.
  10939. auto CI = CurComponents.rbegin();
  10940. auto CE = CurComponents.rend();
  10941. auto SI = StackComponents.rbegin();
  10942. auto SE = StackComponents.rend();
  10943. for (; CI != CE && SI != SE; ++CI, ++SI) {
  10944. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  10945. // At most one list item can be an array item derived from a given
  10946. // variable in map clauses of the same construct.
  10947. if (CurrentRegionOnly &&
  10948. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  10949. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  10950. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  10951. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  10952. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  10953. diag::err_omp_multiple_array_items_in_map_clause)
  10954. << CI->getAssociatedExpression()->getSourceRange();
  10955. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  10956. diag::note_used_here)
  10957. << SI->getAssociatedExpression()->getSourceRange();
  10958. return true;
  10959. }
  10960. // Do both expressions have the same kind?
  10961. if (CI->getAssociatedExpression()->getStmtClass() !=
  10962. SI->getAssociatedExpression()->getStmtClass())
  10963. break;
  10964. // Are we dealing with different variables/fields?
  10965. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  10966. break;
  10967. }
  10968. // Check if the extra components of the expressions in the enclosing
  10969. // data environment are redundant for the current base declaration.
  10970. // If they are, the maps completely overlap, which is legal.
  10971. for (; SI != SE; ++SI) {
  10972. QualType Type;
  10973. if (auto *ASE =
  10974. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  10975. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  10976. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
  10977. SI->getAssociatedExpression())) {
  10978. auto *E = OASE->getBase()->IgnoreParenImpCasts();
  10979. Type =
  10980. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10981. }
  10982. if (Type.isNull() || Type->isAnyPointerType() ||
  10983. CheckArrayExpressionDoesNotReferToWholeSize(
  10984. SemaRef, SI->getAssociatedExpression(), Type))
  10985. break;
  10986. }
  10987. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10988. // List items of map clauses in the same construct must not share
  10989. // original storage.
  10990. //
  10991. // If the expressions are exactly the same or one is a subset of the
  10992. // other, it means they are sharing storage.
  10993. if (CI == CE && SI == SE) {
  10994. if (CurrentRegionOnly) {
  10995. if (CKind == OMPC_map)
  10996. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10997. else {
  10998. assert(CKind == OMPC_to || CKind == OMPC_from);
  10999. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11000. << ERange;
  11001. }
  11002. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11003. << RE->getSourceRange();
  11004. return true;
  11005. } else {
  11006. // If we find the same expression in the enclosing data environment,
  11007. // that is legal.
  11008. IsEnclosedByDataEnvironmentExpr = true;
  11009. return false;
  11010. }
  11011. }
  11012. QualType DerivedType =
  11013. std::prev(CI)->getAssociatedDeclaration()->getType();
  11014. SourceLocation DerivedLoc =
  11015. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  11016. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11017. // If the type of a list item is a reference to a type T then the type
  11018. // will be considered to be T for all purposes of this clause.
  11019. DerivedType = DerivedType.getNonReferenceType();
  11020. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11021. // A variable for which the type is pointer and an array section
  11022. // derived from that variable must not appear as list items of map
  11023. // clauses of the same construct.
  11024. //
  11025. // Also, cover one of the cases in:
  11026. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11027. // If any part of the original storage of a list item has corresponding
  11028. // storage in the device data environment, all of the original storage
  11029. // must have corresponding storage in the device data environment.
  11030. //
  11031. if (DerivedType->isAnyPointerType()) {
  11032. if (CI == CE || SI == SE) {
  11033. SemaRef.Diag(
  11034. DerivedLoc,
  11035. diag::err_omp_pointer_mapped_along_with_derived_section)
  11036. << DerivedLoc;
  11037. } else {
  11038. assert(CI != CE && SI != SE);
  11039. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  11040. << DerivedLoc;
  11041. }
  11042. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11043. << RE->getSourceRange();
  11044. return true;
  11045. }
  11046. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11047. // List items of map clauses in the same construct must not share
  11048. // original storage.
  11049. //
  11050. // An expression is a subset of the other.
  11051. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11052. if (CKind == OMPC_map)
  11053. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11054. else {
  11055. assert(CKind == OMPC_to || CKind == OMPC_from);
  11056. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11057. << ERange;
  11058. }
  11059. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11060. << RE->getSourceRange();
  11061. return true;
  11062. }
  11063. // The current expression uses the same base as other expression in the
  11064. // data environment but does not contain it completely.
  11065. if (!CurrentRegionOnly && SI != SE)
  11066. EnclosingExpr = RE;
  11067. // The current expression is a subset of the expression in the data
  11068. // environment.
  11069. IsEnclosedByDataEnvironmentExpr |=
  11070. (!CurrentRegionOnly && CI != CE && SI == SE);
  11071. return false;
  11072. });
  11073. if (CurrentRegionOnly)
  11074. return FoundError;
  11075. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11076. // If any part of the original storage of a list item has corresponding
  11077. // storage in the device data environment, all of the original storage must
  11078. // have corresponding storage in the device data environment.
  11079. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11080. // If a list item is an element of a structure, and a different element of
  11081. // the structure has a corresponding list item in the device data environment
  11082. // prior to a task encountering the construct associated with the map clause,
  11083. // then the list item must also have a corresponding list item in the device
  11084. // data environment prior to the task encountering the construct.
  11085. //
  11086. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11087. SemaRef.Diag(ELoc,
  11088. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11089. << ERange;
  11090. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11091. << EnclosingExpr->getSourceRange();
  11092. return true;
  11093. }
  11094. return FoundError;
  11095. }
  11096. namespace {
  11097. // Utility struct that gathers all the related lists associated with a mappable
  11098. // expression.
  11099. struct MappableVarListInfo final {
  11100. // The list of expressions.
  11101. ArrayRef<Expr *> VarList;
  11102. // The list of processed expressions.
  11103. SmallVector<Expr *, 16> ProcessedVarList;
  11104. // The mappble components for each expression.
  11105. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11106. // The base declaration of the variable.
  11107. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11108. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11109. // We have a list of components and base declarations for each entry in the
  11110. // variable list.
  11111. VarComponents.reserve(VarList.size());
  11112. VarBaseDeclarations.reserve(VarList.size());
  11113. }
  11114. };
  11115. }
  11116. // Check the validity of the provided variable list for the provided clause kind
  11117. // \a CKind. In the check process the valid expressions, and mappable expression
  11118. // components and variables are extracted and used to fill \a Vars,
  11119. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11120. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11121. static void
  11122. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11123. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11124. SourceLocation StartLoc,
  11125. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11126. bool IsMapTypeImplicit = false) {
  11127. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11128. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11129. "Unexpected clause kind with mappable expressions!");
  11130. // Keep track of the mappable components and base declarations in this clause.
  11131. // Each entry in the list is going to have a list of components associated. We
  11132. // record each set of the components so that we can build the clause later on.
  11133. // In the end we should have the same amount of declarations and component
  11134. // lists.
  11135. for (auto &RE : MVLI.VarList) {
  11136. assert(RE && "Null expr in omp to/from/map clause");
  11137. SourceLocation ELoc = RE->getExprLoc();
  11138. auto *VE = RE->IgnoreParenLValueCasts();
  11139. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11140. VE->isInstantiationDependent() ||
  11141. VE->containsUnexpandedParameterPack()) {
  11142. // We can only analyze this information once the missing information is
  11143. // resolved.
  11144. MVLI.ProcessedVarList.push_back(RE);
  11145. continue;
  11146. }
  11147. auto *SimpleExpr = RE->IgnoreParenCasts();
  11148. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11149. SemaRef.Diag(ELoc,
  11150. diag::err_omp_expected_named_var_member_or_array_expression)
  11151. << RE->getSourceRange();
  11152. continue;
  11153. }
  11154. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11155. ValueDecl *CurDeclaration = nullptr;
  11156. // Obtain the array or member expression bases if required. Also, fill the
  11157. // components array with all the components identified in the process.
  11158. auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
  11159. CKind, /*NoDiagnose=*/false);
  11160. if (!BE)
  11161. continue;
  11162. assert(!CurComponents.empty() &&
  11163. "Invalid mappable expression information.");
  11164. // For the following checks, we rely on the base declaration which is
  11165. // expected to be associated with the last component. The declaration is
  11166. // expected to be a variable or a field (if 'this' is being mapped).
  11167. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11168. assert(CurDeclaration && "Null decl on map clause.");
  11169. assert(
  11170. CurDeclaration->isCanonicalDecl() &&
  11171. "Expecting components to have associated only canonical declarations.");
  11172. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11173. auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11174. assert((VD || FD) && "Only variables or fields are expected here!");
  11175. (void)FD;
  11176. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11177. // threadprivate variables cannot appear in a map clause.
  11178. // OpenMP 4.5 [2.10.5, target update Construct]
  11179. // threadprivate variables cannot appear in a from clause.
  11180. if (VD && DSAS->isThreadPrivate(VD)) {
  11181. auto DVar = DSAS->getTopDSA(VD, false);
  11182. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11183. << getOpenMPClauseName(CKind);
  11184. ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
  11185. continue;
  11186. }
  11187. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11188. // A list item cannot appear in both a map clause and a data-sharing
  11189. // attribute clause on the same construct.
  11190. // Check conflicts with other map clause expressions. We check the conflicts
  11191. // with the current construct separately from the enclosing data
  11192. // environment, because the restrictions are different. We only have to
  11193. // check conflicts across regions for the map clauses.
  11194. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11195. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  11196. break;
  11197. if (CKind == OMPC_map &&
  11198. CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11199. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  11200. break;
  11201. // OpenMP 4.5 [2.10.5, target update Construct]
  11202. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11203. // If the type of a list item is a reference to a type T then the type will
  11204. // be considered to be T for all purposes of this clause.
  11205. QualType Type = CurDeclaration->getType().getNonReferenceType();
  11206. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  11207. // A list item in a to or from clause must have a mappable type.
  11208. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11209. // A list item must have a mappable type.
  11210. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  11211. DSAS, Type))
  11212. continue;
  11213. if (CKind == OMPC_map) {
  11214. // target enter data
  11215. // OpenMP [2.10.2, Restrictions, p. 99]
  11216. // A map-type must be specified in all map clauses and must be either
  11217. // to or alloc.
  11218. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  11219. if (DKind == OMPD_target_enter_data &&
  11220. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  11221. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11222. << (IsMapTypeImplicit ? 1 : 0)
  11223. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11224. << getOpenMPDirectiveName(DKind);
  11225. continue;
  11226. }
  11227. // target exit_data
  11228. // OpenMP [2.10.3, Restrictions, p. 102]
  11229. // A map-type must be specified in all map clauses and must be either
  11230. // from, release, or delete.
  11231. if (DKind == OMPD_target_exit_data &&
  11232. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  11233. MapType == OMPC_MAP_delete)) {
  11234. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11235. << (IsMapTypeImplicit ? 1 : 0)
  11236. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11237. << getOpenMPDirectiveName(DKind);
  11238. continue;
  11239. }
  11240. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11241. // A list item cannot appear in both a map clause and a data-sharing
  11242. // attribute clause on the same construct
  11243. if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
  11244. DKind == OMPD_target_teams_distribute ||
  11245. DKind == OMPD_target_teams_distribute_parallel_for ||
  11246. DKind == OMPD_target_teams_distribute_parallel_for_simd ||
  11247. DKind == OMPD_target_teams_distribute_simd) && VD) {
  11248. auto DVar = DSAS->getTopDSA(VD, false);
  11249. if (isOpenMPPrivate(DVar.CKind)) {
  11250. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11251. << getOpenMPClauseName(DVar.CKind)
  11252. << getOpenMPClauseName(OMPC_map)
  11253. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  11254. ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
  11255. continue;
  11256. }
  11257. }
  11258. }
  11259. // Save the current expression.
  11260. MVLI.ProcessedVarList.push_back(RE);
  11261. // Store the components in the stack so that they can be used to check
  11262. // against other clauses later on.
  11263. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  11264. /*WhereFoundClauseKind=*/OMPC_map);
  11265. // Save the components and declaration to create the clause. For purposes of
  11266. // the clause creation, any component list that has has base 'this' uses
  11267. // null as base declaration.
  11268. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11269. MVLI.VarComponents.back().append(CurComponents.begin(),
  11270. CurComponents.end());
  11271. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  11272. : CurDeclaration);
  11273. }
  11274. }
  11275. OMPClause *
  11276. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  11277. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  11278. SourceLocation MapLoc, SourceLocation ColonLoc,
  11279. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11280. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11281. MappableVarListInfo MVLI(VarList);
  11282. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  11283. MapType, IsMapTypeImplicit);
  11284. // We need to produce a map clause even if we don't have variables so that
  11285. // other diagnostics related with non-existing map clauses are accurate.
  11286. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11287. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11288. MVLI.VarComponents, MapTypeModifier, MapType,
  11289. IsMapTypeImplicit, MapLoc);
  11290. }
  11291. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  11292. TypeResult ParsedType) {
  11293. assert(ParsedType.isUsable());
  11294. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  11295. if (ReductionType.isNull())
  11296. return QualType();
  11297. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  11298. // A type name in a declare reduction directive cannot be a function type, an
  11299. // array type, a reference type, or a type qualified with const, volatile or
  11300. // restrict.
  11301. if (ReductionType.hasQualifiers()) {
  11302. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  11303. return QualType();
  11304. }
  11305. if (ReductionType->isFunctionType()) {
  11306. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  11307. return QualType();
  11308. }
  11309. if (ReductionType->isReferenceType()) {
  11310. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  11311. return QualType();
  11312. }
  11313. if (ReductionType->isArrayType()) {
  11314. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  11315. return QualType();
  11316. }
  11317. return ReductionType;
  11318. }
  11319. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  11320. Scope *S, DeclContext *DC, DeclarationName Name,
  11321. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  11322. AccessSpecifier AS, Decl *PrevDeclInScope) {
  11323. SmallVector<Decl *, 8> Decls;
  11324. Decls.reserve(ReductionTypes.size());
  11325. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  11326. forRedeclarationInCurContext());
  11327. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  11328. // A reduction-identifier may not be re-declared in the current scope for the
  11329. // same type or for a type that is compatible according to the base language
  11330. // rules.
  11331. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  11332. OMPDeclareReductionDecl *PrevDRD = nullptr;
  11333. bool InCompoundScope = true;
  11334. if (S != nullptr) {
  11335. // Find previous declaration with the same name not referenced in other
  11336. // declarations.
  11337. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  11338. InCompoundScope =
  11339. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  11340. LookupName(Lookup, S);
  11341. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  11342. /*AllowInlineNamespace=*/false);
  11343. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  11344. auto Filter = Lookup.makeFilter();
  11345. while (Filter.hasNext()) {
  11346. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  11347. if (InCompoundScope) {
  11348. auto I = UsedAsPrevious.find(PrevDecl);
  11349. if (I == UsedAsPrevious.end())
  11350. UsedAsPrevious[PrevDecl] = false;
  11351. if (auto *D = PrevDecl->getPrevDeclInScope())
  11352. UsedAsPrevious[D] = true;
  11353. }
  11354. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  11355. PrevDecl->getLocation();
  11356. }
  11357. Filter.done();
  11358. if (InCompoundScope) {
  11359. for (auto &PrevData : UsedAsPrevious) {
  11360. if (!PrevData.second) {
  11361. PrevDRD = PrevData.first;
  11362. break;
  11363. }
  11364. }
  11365. }
  11366. } else if (PrevDeclInScope != nullptr) {
  11367. auto *PrevDRDInScope = PrevDRD =
  11368. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  11369. do {
  11370. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  11371. PrevDRDInScope->getLocation();
  11372. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  11373. } while (PrevDRDInScope != nullptr);
  11374. }
  11375. for (auto &TyData : ReductionTypes) {
  11376. auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  11377. bool Invalid = false;
  11378. if (I != PreviousRedeclTypes.end()) {
  11379. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  11380. << TyData.first;
  11381. Diag(I->second, diag::note_previous_definition);
  11382. Invalid = true;
  11383. }
  11384. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  11385. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  11386. Name, TyData.first, PrevDRD);
  11387. DC->addDecl(DRD);
  11388. DRD->setAccess(AS);
  11389. Decls.push_back(DRD);
  11390. if (Invalid)
  11391. DRD->setInvalidDecl();
  11392. else
  11393. PrevDRD = DRD;
  11394. }
  11395. return DeclGroupPtrTy::make(
  11396. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  11397. }
  11398. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  11399. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11400. // Enter new function scope.
  11401. PushFunctionScope();
  11402. getCurFunction()->setHasBranchProtectedScope();
  11403. getCurFunction()->setHasOMPDeclareReductionCombiner();
  11404. if (S != nullptr)
  11405. PushDeclContext(S, DRD);
  11406. else
  11407. CurContext = DRD;
  11408. PushExpressionEvaluationContext(
  11409. ExpressionEvaluationContext::PotentiallyEvaluated);
  11410. QualType ReductionType = DRD->getType();
  11411. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  11412. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  11413. // uses semantics of argument handles by value, but it should be passed by
  11414. // reference. C lang does not support references, so pass all parameters as
  11415. // pointers.
  11416. // Create 'T omp_in;' variable.
  11417. auto *OmpInParm =
  11418. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  11419. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  11420. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  11421. // uses semantics of argument handles by value, but it should be passed by
  11422. // reference. C lang does not support references, so pass all parameters as
  11423. // pointers.
  11424. // Create 'T omp_out;' variable.
  11425. auto *OmpOutParm =
  11426. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  11427. if (S != nullptr) {
  11428. PushOnScopeChains(OmpInParm, S);
  11429. PushOnScopeChains(OmpOutParm, S);
  11430. } else {
  11431. DRD->addDecl(OmpInParm);
  11432. DRD->addDecl(OmpOutParm);
  11433. }
  11434. }
  11435. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  11436. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11437. DiscardCleanupsInEvaluationContext();
  11438. PopExpressionEvaluationContext();
  11439. PopDeclContext();
  11440. PopFunctionScopeInfo();
  11441. if (Combiner != nullptr)
  11442. DRD->setCombiner(Combiner);
  11443. else
  11444. DRD->setInvalidDecl();
  11445. }
  11446. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  11447. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11448. // Enter new function scope.
  11449. PushFunctionScope();
  11450. getCurFunction()->setHasBranchProtectedScope();
  11451. if (S != nullptr)
  11452. PushDeclContext(S, DRD);
  11453. else
  11454. CurContext = DRD;
  11455. PushExpressionEvaluationContext(
  11456. ExpressionEvaluationContext::PotentiallyEvaluated);
  11457. QualType ReductionType = DRD->getType();
  11458. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  11459. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  11460. // uses semantics of argument handles by value, but it should be passed by
  11461. // reference. C lang does not support references, so pass all parameters as
  11462. // pointers.
  11463. // Create 'T omp_priv;' variable.
  11464. auto *OmpPrivParm =
  11465. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  11466. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  11467. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  11468. // uses semantics of argument handles by value, but it should be passed by
  11469. // reference. C lang does not support references, so pass all parameters as
  11470. // pointers.
  11471. // Create 'T omp_orig;' variable.
  11472. auto *OmpOrigParm =
  11473. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  11474. if (S != nullptr) {
  11475. PushOnScopeChains(OmpPrivParm, S);
  11476. PushOnScopeChains(OmpOrigParm, S);
  11477. } else {
  11478. DRD->addDecl(OmpPrivParm);
  11479. DRD->addDecl(OmpOrigParm);
  11480. }
  11481. return OmpPrivParm;
  11482. }
  11483. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  11484. VarDecl *OmpPrivParm) {
  11485. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11486. DiscardCleanupsInEvaluationContext();
  11487. PopExpressionEvaluationContext();
  11488. PopDeclContext();
  11489. PopFunctionScopeInfo();
  11490. if (Initializer != nullptr) {
  11491. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  11492. } else if (OmpPrivParm->hasInit()) {
  11493. DRD->setInitializer(OmpPrivParm->getInit(),
  11494. OmpPrivParm->isDirectInit()
  11495. ? OMPDeclareReductionDecl::DirectInit
  11496. : OMPDeclareReductionDecl::CopyInit);
  11497. } else {
  11498. DRD->setInvalidDecl();
  11499. }
  11500. }
  11501. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  11502. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  11503. for (auto *D : DeclReductions.get()) {
  11504. if (IsValid) {
  11505. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11506. if (S != nullptr)
  11507. PushOnScopeChains(DRD, S, /*AddToContext=*/false);
  11508. } else
  11509. D->setInvalidDecl();
  11510. }
  11511. return DeclReductions;
  11512. }
  11513. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  11514. SourceLocation StartLoc,
  11515. SourceLocation LParenLoc,
  11516. SourceLocation EndLoc) {
  11517. Expr *ValExpr = NumTeams;
  11518. Stmt *HelperValStmt = nullptr;
  11519. // OpenMP [teams Constrcut, Restrictions]
  11520. // The num_teams expression must evaluate to a positive integer value.
  11521. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  11522. /*StrictlyPositive=*/true))
  11523. return nullptr;
  11524. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11525. OpenMPDirectiveKind CaptureRegion =
  11526. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  11527. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11528. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11529. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11530. HelperValStmt = buildPreInits(Context, Captures);
  11531. }
  11532. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  11533. StartLoc, LParenLoc, EndLoc);
  11534. }
  11535. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  11536. SourceLocation StartLoc,
  11537. SourceLocation LParenLoc,
  11538. SourceLocation EndLoc) {
  11539. Expr *ValExpr = ThreadLimit;
  11540. Stmt *HelperValStmt = nullptr;
  11541. // OpenMP [teams Constrcut, Restrictions]
  11542. // The thread_limit expression must evaluate to a positive integer value.
  11543. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  11544. /*StrictlyPositive=*/true))
  11545. return nullptr;
  11546. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11547. OpenMPDirectiveKind CaptureRegion =
  11548. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  11549. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11550. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11551. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11552. HelperValStmt = buildPreInits(Context, Captures);
  11553. }
  11554. return new (Context) OMPThreadLimitClause(
  11555. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  11556. }
  11557. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  11558. SourceLocation StartLoc,
  11559. SourceLocation LParenLoc,
  11560. SourceLocation EndLoc) {
  11561. Expr *ValExpr = Priority;
  11562. // OpenMP [2.9.1, task Constrcut]
  11563. // The priority-value is a non-negative numerical scalar expression.
  11564. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  11565. /*StrictlyPositive=*/false))
  11566. return nullptr;
  11567. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11568. }
  11569. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  11570. SourceLocation StartLoc,
  11571. SourceLocation LParenLoc,
  11572. SourceLocation EndLoc) {
  11573. Expr *ValExpr = Grainsize;
  11574. // OpenMP [2.9.2, taskloop Constrcut]
  11575. // The parameter of the grainsize clause must be a positive integer
  11576. // expression.
  11577. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  11578. /*StrictlyPositive=*/true))
  11579. return nullptr;
  11580. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11581. }
  11582. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  11583. SourceLocation StartLoc,
  11584. SourceLocation LParenLoc,
  11585. SourceLocation EndLoc) {
  11586. Expr *ValExpr = NumTasks;
  11587. // OpenMP [2.9.2, taskloop Constrcut]
  11588. // The parameter of the num_tasks clause must be a positive integer
  11589. // expression.
  11590. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  11591. /*StrictlyPositive=*/true))
  11592. return nullptr;
  11593. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11594. }
  11595. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  11596. SourceLocation LParenLoc,
  11597. SourceLocation EndLoc) {
  11598. // OpenMP [2.13.2, critical construct, Description]
  11599. // ... where hint-expression is an integer constant expression that evaluates
  11600. // to a valid lock hint.
  11601. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  11602. if (HintExpr.isInvalid())
  11603. return nullptr;
  11604. return new (Context)
  11605. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  11606. }
  11607. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  11608. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  11609. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  11610. SourceLocation EndLoc) {
  11611. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  11612. std::string Values;
  11613. Values += "'";
  11614. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  11615. Values += "'";
  11616. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  11617. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  11618. return nullptr;
  11619. }
  11620. Expr *ValExpr = ChunkSize;
  11621. Stmt *HelperValStmt = nullptr;
  11622. if (ChunkSize) {
  11623. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  11624. !ChunkSize->isInstantiationDependent() &&
  11625. !ChunkSize->containsUnexpandedParameterPack()) {
  11626. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  11627. ExprResult Val =
  11628. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  11629. if (Val.isInvalid())
  11630. return nullptr;
  11631. ValExpr = Val.get();
  11632. // OpenMP [2.7.1, Restrictions]
  11633. // chunk_size must be a loop invariant integer expression with a positive
  11634. // value.
  11635. llvm::APSInt Result;
  11636. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  11637. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  11638. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  11639. << "dist_schedule" << ChunkSize->getSourceRange();
  11640. return nullptr;
  11641. }
  11642. } else if (getOpenMPCaptureRegionForClause(
  11643. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  11644. OMPD_unknown &&
  11645. !CurContext->isDependentContext()) {
  11646. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11647. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11648. HelperValStmt = buildPreInits(Context, Captures);
  11649. }
  11650. }
  11651. }
  11652. return new (Context)
  11653. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  11654. Kind, ValExpr, HelperValStmt);
  11655. }
  11656. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  11657. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  11658. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  11659. SourceLocation KindLoc, SourceLocation EndLoc) {
  11660. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  11661. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  11662. std::string Value;
  11663. SourceLocation Loc;
  11664. Value += "'";
  11665. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  11666. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11667. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  11668. Loc = MLoc;
  11669. } else {
  11670. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11671. OMPC_DEFAULTMAP_scalar);
  11672. Loc = KindLoc;
  11673. }
  11674. Value += "'";
  11675. Diag(Loc, diag::err_omp_unexpected_clause_value)
  11676. << Value << getOpenMPClauseName(OMPC_defaultmap);
  11677. return nullptr;
  11678. }
  11679. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  11680. return new (Context)
  11681. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  11682. }
  11683. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  11684. DeclContext *CurLexicalContext = getCurLexicalContext();
  11685. if (!CurLexicalContext->isFileContext() &&
  11686. !CurLexicalContext->isExternCContext() &&
  11687. !CurLexicalContext->isExternCXXContext() &&
  11688. !isa<CXXRecordDecl>(CurLexicalContext) &&
  11689. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  11690. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  11691. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  11692. Diag(Loc, diag::err_omp_region_not_file_context);
  11693. return false;
  11694. }
  11695. if (IsInOpenMPDeclareTargetContext) {
  11696. Diag(Loc, diag::err_omp_enclosed_declare_target);
  11697. return false;
  11698. }
  11699. IsInOpenMPDeclareTargetContext = true;
  11700. return true;
  11701. }
  11702. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  11703. assert(IsInOpenMPDeclareTargetContext &&
  11704. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  11705. IsInOpenMPDeclareTargetContext = false;
  11706. }
  11707. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  11708. CXXScopeSpec &ScopeSpec,
  11709. const DeclarationNameInfo &Id,
  11710. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  11711. NamedDeclSetType &SameDirectiveDecls) {
  11712. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  11713. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  11714. if (Lookup.isAmbiguous())
  11715. return;
  11716. Lookup.suppressDiagnostics();
  11717. if (!Lookup.isSingleResult()) {
  11718. if (TypoCorrection Corrected =
  11719. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  11720. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  11721. CTK_ErrorRecovery)) {
  11722. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  11723. << Id.getName());
  11724. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  11725. return;
  11726. }
  11727. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  11728. return;
  11729. }
  11730. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  11731. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  11732. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  11733. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  11734. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  11735. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  11736. ND->addAttr(A);
  11737. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11738. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  11739. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  11740. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  11741. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  11742. << Id.getName();
  11743. }
  11744. } else
  11745. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  11746. }
  11747. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  11748. Sema &SemaRef, Decl *D) {
  11749. if (!D)
  11750. return;
  11751. Decl *LD = nullptr;
  11752. if (isa<TagDecl>(D)) {
  11753. LD = cast<TagDecl>(D)->getDefinition();
  11754. } else if (isa<VarDecl>(D)) {
  11755. LD = cast<VarDecl>(D)->getDefinition();
  11756. // If this is an implicit variable that is legal and we do not need to do
  11757. // anything.
  11758. if (cast<VarDecl>(D)->isImplicit()) {
  11759. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11760. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11761. D->addAttr(A);
  11762. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11763. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11764. return;
  11765. }
  11766. } else if (isa<FunctionDecl>(D)) {
  11767. const FunctionDecl *FD = nullptr;
  11768. if (cast<FunctionDecl>(D)->hasBody(FD))
  11769. LD = const_cast<FunctionDecl *>(FD);
  11770. // If the definition is associated with the current declaration in the
  11771. // target region (it can be e.g. a lambda) that is legal and we do not need
  11772. // to do anything else.
  11773. if (LD == D) {
  11774. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11775. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11776. D->addAttr(A);
  11777. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11778. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11779. return;
  11780. }
  11781. }
  11782. if (!LD)
  11783. LD = D;
  11784. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11785. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  11786. // Outlined declaration is not declared target.
  11787. if (LD->isOutOfLine()) {
  11788. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11789. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11790. } else {
  11791. DeclContext *DC = LD->getDeclContext();
  11792. while (DC) {
  11793. if (isa<FunctionDecl>(DC) &&
  11794. cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
  11795. break;
  11796. DC = DC->getParent();
  11797. }
  11798. if (DC)
  11799. return;
  11800. // Is not declared in target context.
  11801. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11802. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11803. }
  11804. // Mark decl as declared target to prevent further diagnostic.
  11805. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11806. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11807. D->addAttr(A);
  11808. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11809. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11810. }
  11811. }
  11812. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  11813. Sema &SemaRef, DSAStackTy *Stack,
  11814. ValueDecl *VD) {
  11815. if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
  11816. return true;
  11817. if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
  11818. return false;
  11819. return true;
  11820. }
  11821. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  11822. SourceLocation IdLoc) {
  11823. if (!D || D->isInvalidDecl())
  11824. return;
  11825. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  11826. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  11827. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  11828. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  11829. if (DSAStack->isThreadPrivate(VD)) {
  11830. Diag(SL, diag::err_omp_threadprivate_in_target);
  11831. ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  11832. return;
  11833. }
  11834. }
  11835. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  11836. // Problem if any with var declared with incomplete type will be reported
  11837. // as normal, so no need to check it here.
  11838. if ((E || !VD->getType()->isIncompleteType()) &&
  11839. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  11840. // Mark decl as declared target to prevent further diagnostic.
  11841. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
  11842. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11843. Context, OMPDeclareTargetDeclAttr::MT_To);
  11844. VD->addAttr(A);
  11845. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11846. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  11847. }
  11848. return;
  11849. }
  11850. }
  11851. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  11852. if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11853. (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
  11854. OMPDeclareTargetDeclAttr::MT_Link)) {
  11855. assert(IdLoc.isValid() && "Source location is expected");
  11856. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  11857. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  11858. return;
  11859. }
  11860. }
  11861. if (!E) {
  11862. // Checking declaration inside declare target region.
  11863. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11864. (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
  11865. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11866. Context, OMPDeclareTargetDeclAttr::MT_To);
  11867. D->addAttr(A);
  11868. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11869. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11870. }
  11871. return;
  11872. }
  11873. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  11874. }
  11875. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  11876. SourceLocation StartLoc,
  11877. SourceLocation LParenLoc,
  11878. SourceLocation EndLoc) {
  11879. MappableVarListInfo MVLI(VarList);
  11880. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  11881. if (MVLI.ProcessedVarList.empty())
  11882. return nullptr;
  11883. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11884. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11885. MVLI.VarComponents);
  11886. }
  11887. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  11888. SourceLocation StartLoc,
  11889. SourceLocation LParenLoc,
  11890. SourceLocation EndLoc) {
  11891. MappableVarListInfo MVLI(VarList);
  11892. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  11893. if (MVLI.ProcessedVarList.empty())
  11894. return nullptr;
  11895. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11896. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11897. MVLI.VarComponents);
  11898. }
  11899. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  11900. SourceLocation StartLoc,
  11901. SourceLocation LParenLoc,
  11902. SourceLocation EndLoc) {
  11903. MappableVarListInfo MVLI(VarList);
  11904. SmallVector<Expr *, 8> PrivateCopies;
  11905. SmallVector<Expr *, 8> Inits;
  11906. for (auto &RefExpr : VarList) {
  11907. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  11908. SourceLocation ELoc;
  11909. SourceRange ERange;
  11910. Expr *SimpleRefExpr = RefExpr;
  11911. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11912. if (Res.second) {
  11913. // It will be analyzed later.
  11914. MVLI.ProcessedVarList.push_back(RefExpr);
  11915. PrivateCopies.push_back(nullptr);
  11916. Inits.push_back(nullptr);
  11917. }
  11918. ValueDecl *D = Res.first;
  11919. if (!D)
  11920. continue;
  11921. QualType Type = D->getType();
  11922. Type = Type.getNonReferenceType().getUnqualifiedType();
  11923. auto *VD = dyn_cast<VarDecl>(D);
  11924. // Item should be a pointer or reference to pointer.
  11925. if (!Type->isPointerType()) {
  11926. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  11927. << 0 << RefExpr->getSourceRange();
  11928. continue;
  11929. }
  11930. // Build the private variable and the expression that refers to it.
  11931. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  11932. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11933. if (VDPrivate->isInvalidDecl())
  11934. continue;
  11935. CurContext->addDecl(VDPrivate);
  11936. auto VDPrivateRefExpr = buildDeclRefExpr(
  11937. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11938. // Add temporary variable to initialize the private copy of the pointer.
  11939. auto *VDInit =
  11940. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  11941. auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11942. RefExpr->getExprLoc());
  11943. AddInitializerToDecl(VDPrivate,
  11944. DefaultLvalueConversion(VDInitRefExpr).get(),
  11945. /*DirectInit=*/false);
  11946. // If required, build a capture to implement the privatization initialized
  11947. // with the current list item value.
  11948. DeclRefExpr *Ref = nullptr;
  11949. if (!VD)
  11950. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11951. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  11952. PrivateCopies.push_back(VDPrivateRefExpr);
  11953. Inits.push_back(VDInitRefExpr);
  11954. // We need to add a data sharing attribute for this variable to make sure it
  11955. // is correctly captured. A variable that shows up in a use_device_ptr has
  11956. // similar properties of a first private variable.
  11957. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11958. // Create a mappable component for the list item. List items in this clause
  11959. // only need a component.
  11960. MVLI.VarBaseDeclarations.push_back(D);
  11961. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11962. MVLI.VarComponents.back().push_back(
  11963. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  11964. }
  11965. if (MVLI.ProcessedVarList.empty())
  11966. return nullptr;
  11967. return OMPUseDevicePtrClause::Create(
  11968. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11969. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11970. }
  11971. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  11972. SourceLocation StartLoc,
  11973. SourceLocation LParenLoc,
  11974. SourceLocation EndLoc) {
  11975. MappableVarListInfo MVLI(VarList);
  11976. for (auto &RefExpr : VarList) {
  11977. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  11978. SourceLocation ELoc;
  11979. SourceRange ERange;
  11980. Expr *SimpleRefExpr = RefExpr;
  11981. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11982. if (Res.second) {
  11983. // It will be analyzed later.
  11984. MVLI.ProcessedVarList.push_back(RefExpr);
  11985. }
  11986. ValueDecl *D = Res.first;
  11987. if (!D)
  11988. continue;
  11989. QualType Type = D->getType();
  11990. // item should be a pointer or array or reference to pointer or array
  11991. if (!Type.getNonReferenceType()->isPointerType() &&
  11992. !Type.getNonReferenceType()->isArrayType()) {
  11993. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  11994. << 0 << RefExpr->getSourceRange();
  11995. continue;
  11996. }
  11997. // Check if the declaration in the clause does not show up in any data
  11998. // sharing attribute.
  11999. auto DVar = DSAStack->getTopDSA(D, false);
  12000. if (isOpenMPPrivate(DVar.CKind)) {
  12001. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12002. << getOpenMPClauseName(DVar.CKind)
  12003. << getOpenMPClauseName(OMPC_is_device_ptr)
  12004. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12005. ReportOriginalDSA(*this, DSAStack, D, DVar);
  12006. continue;
  12007. }
  12008. Expr *ConflictExpr;
  12009. if (DSAStack->checkMappableExprComponentListsForDecl(
  12010. D, /*CurrentRegionOnly=*/true,
  12011. [&ConflictExpr](
  12012. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  12013. OpenMPClauseKind) -> bool {
  12014. ConflictExpr = R.front().getAssociatedExpression();
  12015. return true;
  12016. })) {
  12017. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  12018. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  12019. << ConflictExpr->getSourceRange();
  12020. continue;
  12021. }
  12022. // Store the components in the stack so that they can be used to check
  12023. // against other clauses later on.
  12024. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  12025. DSAStack->addMappableExpressionComponents(
  12026. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  12027. // Record the expression we've just processed.
  12028. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  12029. // Create a mappable component for the list item. List items in this clause
  12030. // only need a component. We use a null declaration to signal fields in
  12031. // 'this'.
  12032. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12033. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12034. "Unexpected device pointer expression!");
  12035. MVLI.VarBaseDeclarations.push_back(
  12036. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12037. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12038. MVLI.VarComponents.back().push_back(MC);
  12039. }
  12040. if (MVLI.ProcessedVarList.empty())
  12041. return nullptr;
  12042. return OMPIsDevicePtrClause::Create(
  12043. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12044. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12045. }