SemaOpenMP.cpp 544 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703
  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. /// 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 const Expr *checkMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// 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. /// Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy {
  54. public:
  55. struct DSAVarData {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. const Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  63. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  64. SourceLocation ImplicitDSALoc)
  65. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  66. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  67. };
  68. using OperatorOffsetTy =
  69. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  70. using DoacrossDependMapTy =
  71. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  72. private:
  73. struct DSAInfo {
  74. OpenMPClauseKind Attributes = OMPC_unknown;
  75. /// Pointer to a reference expression and a flag which shows that the
  76. /// variable is marked as lastprivate(true) or not (false).
  77. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  78. DeclRefExpr *PrivateCopy = nullptr;
  79. };
  80. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  81. using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  82. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  83. using LoopControlVariablesMapTy =
  84. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  85. /// Struct that associates a component with the clause kind where they are
  86. /// found.
  87. struct MappedExprComponentTy {
  88. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  89. OpenMPClauseKind Kind = OMPC_unknown;
  90. };
  91. using MappedExprComponentsTy =
  92. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  93. using CriticalsWithHintsTy =
  94. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  95. struct ReductionData {
  96. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  97. SourceRange ReductionRange;
  98. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  99. ReductionData() = default;
  100. void set(BinaryOperatorKind BO, SourceRange RR) {
  101. ReductionRange = RR;
  102. ReductionOp = BO;
  103. }
  104. void set(const Expr *RefExpr, SourceRange RR) {
  105. ReductionRange = RR;
  106. ReductionOp = RefExpr;
  107. }
  108. };
  109. using DeclReductionMapTy =
  110. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  111. struct SharingMapTy {
  112. DeclSAMapTy SharingMap;
  113. DeclReductionMapTy ReductionMap;
  114. AlignedMapTy AlignedMap;
  115. MappedExprComponentsTy MappedExprComponents;
  116. LoopControlVariablesMapTy LCVMap;
  117. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  118. SourceLocation DefaultAttrLoc;
  119. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  120. SourceLocation DefaultMapAttrLoc;
  121. OpenMPDirectiveKind Directive = OMPD_unknown;
  122. DeclarationNameInfo DirectiveName;
  123. Scope *CurScope = nullptr;
  124. SourceLocation ConstructLoc;
  125. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  126. /// get the data (loop counters etc.) about enclosing loop-based construct.
  127. /// This data is required during codegen.
  128. DoacrossDependMapTy DoacrossDepends;
  129. /// first argument (Expr *) contains optional argument of the
  130. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  131. /// clause, false otherwise.
  132. llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  133. unsigned AssociatedLoops = 1;
  134. const Decl *PossiblyLoopCounter = nullptr;
  135. bool NowaitRegion = false;
  136. bool CancelRegion = false;
  137. bool LoopStart = false;
  138. SourceLocation InnerTeamsRegionLoc;
  139. /// Reference to the taskgroup task_reduction reference expression.
  140. Expr *TaskgroupReductionRef = nullptr;
  141. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  142. Scope *CurScope, SourceLocation Loc)
  143. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  144. ConstructLoc(Loc) {}
  145. SharingMapTy() = default;
  146. };
  147. using StackTy = SmallVector<SharingMapTy, 4>;
  148. /// Stack of used declaration and their data-sharing attributes.
  149. DeclSAMapTy Threadprivates;
  150. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  151. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  152. /// true, if check for DSA must be from parent directive, false, if
  153. /// from current directive.
  154. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  155. Sema &SemaRef;
  156. bool ForceCapturing = false;
  157. /// true if all the vaiables in the target executable directives must be
  158. /// captured by reference.
  159. bool ForceCaptureByReferenceInTargetExecutable = false;
  160. CriticalsWithHintsTy Criticals;
  161. using iterator = StackTy::const_reverse_iterator;
  162. DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
  163. /// Checks if the variable is a local for OpenMP region.
  164. bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
  165. bool isStackEmpty() const {
  166. return Stack.empty() ||
  167. Stack.back().second != CurrentNonCapturingFunctionScope ||
  168. Stack.back().first.empty();
  169. }
  170. /// Vector of previously declared requires directives
  171. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  172. public:
  173. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  174. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  175. OpenMPClauseKind getClauseParsingMode() const {
  176. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  177. return ClauseKindMode;
  178. }
  179. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  180. bool isForceVarCapturing() const { return ForceCapturing; }
  181. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  182. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  183. ForceCaptureByReferenceInTargetExecutable = V;
  184. }
  185. bool isForceCaptureByReferenceInTargetExecutable() const {
  186. return ForceCaptureByReferenceInTargetExecutable;
  187. }
  188. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  189. Scope *CurScope, SourceLocation Loc) {
  190. if (Stack.empty() ||
  191. Stack.back().second != CurrentNonCapturingFunctionScope)
  192. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  193. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  194. Stack.back().first.back().DefaultAttrLoc = Loc;
  195. }
  196. void pop() {
  197. assert(!Stack.back().first.empty() &&
  198. "Data-sharing attributes stack is empty!");
  199. Stack.back().first.pop_back();
  200. }
  201. /// Marks that we're started loop parsing.
  202. void loopInit() {
  203. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  204. "Expected loop-based directive.");
  205. Stack.back().first.back().LoopStart = true;
  206. }
  207. /// Start capturing of the variables in the loop context.
  208. void loopStart() {
  209. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  210. "Expected loop-based directive.");
  211. Stack.back().first.back().LoopStart = false;
  212. }
  213. /// true, if variables are captured, false otherwise.
  214. bool isLoopStarted() const {
  215. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  216. "Expected loop-based directive.");
  217. return !Stack.back().first.back().LoopStart;
  218. }
  219. /// Marks (or clears) declaration as possibly loop counter.
  220. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  221. Stack.back().first.back().PossiblyLoopCounter =
  222. D ? D->getCanonicalDecl() : D;
  223. }
  224. /// Gets the possible loop counter decl.
  225. const Decl *getPossiblyLoopCunter() const {
  226. return Stack.back().first.back().PossiblyLoopCounter;
  227. }
  228. /// Start new OpenMP region stack in new non-capturing function.
  229. void pushFunction() {
  230. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  231. assert(!isa<CapturingScopeInfo>(CurFnScope));
  232. CurrentNonCapturingFunctionScope = CurFnScope;
  233. }
  234. /// Pop region stack for non-capturing function.
  235. void popFunction(const FunctionScopeInfo *OldFSI) {
  236. if (!Stack.empty() && Stack.back().second == OldFSI) {
  237. assert(Stack.back().first.empty());
  238. Stack.pop_back();
  239. }
  240. CurrentNonCapturingFunctionScope = nullptr;
  241. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  242. if (!isa<CapturingScopeInfo>(FSI)) {
  243. CurrentNonCapturingFunctionScope = FSI;
  244. break;
  245. }
  246. }
  247. }
  248. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  249. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  250. }
  251. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  252. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  253. auto I = Criticals.find(Name.getAsString());
  254. if (I != Criticals.end())
  255. return I->second;
  256. return std::make_pair(nullptr, llvm::APSInt());
  257. }
  258. /// If 'aligned' declaration for given variable \a D was not seen yet,
  259. /// add it and return NULL; otherwise return previous occurrence's expression
  260. /// for diagnostics.
  261. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  262. /// Register specified variable as loop control variable.
  263. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  264. /// Check if the specified variable is a loop control variable for
  265. /// current region.
  266. /// \return The index of the loop control variable in the list of associated
  267. /// for-loops (from outer to inner).
  268. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  269. /// Check if the specified variable is a loop control variable for
  270. /// parent region.
  271. /// \return The index of the loop control variable in the list of associated
  272. /// for-loops (from outer to inner).
  273. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  274. /// Get the loop control variable for the I-th loop (or nullptr) in
  275. /// parent directive.
  276. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  277. /// Adds explicit data sharing attribute to the specified declaration.
  278. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  279. DeclRefExpr *PrivateCopy = nullptr);
  280. /// Adds additional information for the reduction items with the reduction id
  281. /// represented as an operator.
  282. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  283. BinaryOperatorKind BOK);
  284. /// Adds additional information for the reduction items with the reduction id
  285. /// represented as reduction identifier.
  286. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  287. const Expr *ReductionRef);
  288. /// Returns the location and reduction operation from the innermost parent
  289. /// region for the given \p D.
  290. const DSAVarData
  291. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  292. BinaryOperatorKind &BOK,
  293. Expr *&TaskgroupDescriptor) const;
  294. /// Returns the location and reduction operation from the innermost parent
  295. /// region for the given \p D.
  296. const DSAVarData
  297. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  298. const Expr *&ReductionRef,
  299. Expr *&TaskgroupDescriptor) const;
  300. /// Return reduction reference expression for the current taskgroup.
  301. Expr *getTaskgroupReductionRef() const {
  302. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  303. "taskgroup reference expression requested for non taskgroup "
  304. "directive.");
  305. return Stack.back().first.back().TaskgroupReductionRef;
  306. }
  307. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  308. /// descriptor variable at the \p Level of OpenMP regions.
  309. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  310. return Stack.back().first[Level].TaskgroupReductionRef &&
  311. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  312. ->getDecl() == VD;
  313. }
  314. /// Returns data sharing attributes from top of the stack for the
  315. /// specified declaration.
  316. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  317. /// Returns data-sharing attributes for the specified declaration.
  318. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  319. /// Checks if the specified variables has data-sharing attributes which
  320. /// match specified \a CPred predicate in any directive which matches \a DPred
  321. /// predicate.
  322. const DSAVarData
  323. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  324. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  325. bool FromParent) const;
  326. /// Checks if the specified variables has data-sharing attributes which
  327. /// match specified \a CPred predicate in any innermost directive which
  328. /// matches \a DPred predicate.
  329. const DSAVarData
  330. hasInnermostDSA(ValueDecl *D,
  331. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  332. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  333. bool FromParent) const;
  334. /// Checks if the specified variables has explicit data-sharing
  335. /// attributes which match specified \a CPred predicate at the specified
  336. /// OpenMP region.
  337. bool hasExplicitDSA(const ValueDecl *D,
  338. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  339. unsigned Level, bool NotLastprivate = false) const;
  340. /// Returns true if the directive at level \Level matches in the
  341. /// specified \a DPred predicate.
  342. bool hasExplicitDirective(
  343. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  344. unsigned Level) const;
  345. /// Finds a directive which matches specified \a DPred predicate.
  346. bool hasDirective(
  347. const llvm::function_ref<bool(
  348. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  349. DPred,
  350. bool FromParent) const;
  351. /// Returns currently analyzed directive.
  352. OpenMPDirectiveKind getCurrentDirective() const {
  353. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  354. }
  355. /// Returns directive kind at specified level.
  356. OpenMPDirectiveKind getDirective(unsigned Level) const {
  357. assert(!isStackEmpty() && "No directive at specified level.");
  358. return Stack.back().first[Level].Directive;
  359. }
  360. /// Returns parent directive.
  361. OpenMPDirectiveKind getParentDirective() const {
  362. if (isStackEmpty() || Stack.back().first.size() == 1)
  363. return OMPD_unknown;
  364. return std::next(Stack.back().first.rbegin())->Directive;
  365. }
  366. /// Add requires decl to internal vector
  367. void addRequiresDecl(OMPRequiresDecl *RD) {
  368. RequiresDecls.push_back(RD);
  369. }
  370. /// Checks for a duplicate clause amongst previously declared requires
  371. /// directives
  372. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  373. bool IsDuplicate = false;
  374. for (OMPClause *CNew : ClauseList) {
  375. for (const OMPRequiresDecl *D : RequiresDecls) {
  376. for (const OMPClause *CPrev : D->clauselists()) {
  377. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  378. SemaRef.Diag(CNew->getBeginLoc(),
  379. diag::err_omp_requires_clause_redeclaration)
  380. << getOpenMPClauseName(CNew->getClauseKind());
  381. SemaRef.Diag(CPrev->getBeginLoc(),
  382. diag::note_omp_requires_previous_clause)
  383. << getOpenMPClauseName(CPrev->getClauseKind());
  384. IsDuplicate = true;
  385. }
  386. }
  387. }
  388. }
  389. return IsDuplicate;
  390. }
  391. /// Set default data sharing attribute to none.
  392. void setDefaultDSANone(SourceLocation Loc) {
  393. assert(!isStackEmpty());
  394. Stack.back().first.back().DefaultAttr = DSA_none;
  395. Stack.back().first.back().DefaultAttrLoc = Loc;
  396. }
  397. /// Set default data sharing attribute to shared.
  398. void setDefaultDSAShared(SourceLocation Loc) {
  399. assert(!isStackEmpty());
  400. Stack.back().first.back().DefaultAttr = DSA_shared;
  401. Stack.back().first.back().DefaultAttrLoc = Loc;
  402. }
  403. /// Set default data mapping attribute to 'tofrom:scalar'.
  404. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  405. assert(!isStackEmpty());
  406. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  407. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  408. }
  409. DefaultDataSharingAttributes getDefaultDSA() const {
  410. return isStackEmpty() ? DSA_unspecified
  411. : Stack.back().first.back().DefaultAttr;
  412. }
  413. SourceLocation getDefaultDSALocation() const {
  414. return isStackEmpty() ? SourceLocation()
  415. : Stack.back().first.back().DefaultAttrLoc;
  416. }
  417. DefaultMapAttributes getDefaultDMA() const {
  418. return isStackEmpty() ? DMA_unspecified
  419. : Stack.back().first.back().DefaultMapAttr;
  420. }
  421. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  422. return Stack.back().first[Level].DefaultMapAttr;
  423. }
  424. SourceLocation getDefaultDMALocation() const {
  425. return isStackEmpty() ? SourceLocation()
  426. : Stack.back().first.back().DefaultMapAttrLoc;
  427. }
  428. /// Checks if the specified variable is a threadprivate.
  429. bool isThreadPrivate(VarDecl *D) {
  430. const DSAVarData DVar = getTopDSA(D, false);
  431. return isOpenMPThreadPrivate(DVar.CKind);
  432. }
  433. /// Marks current region as ordered (it has an 'ordered' clause).
  434. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  435. OMPOrderedClause *Clause) {
  436. assert(!isStackEmpty());
  437. if (IsOrdered)
  438. Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
  439. else
  440. Stack.back().first.back().OrderedRegion.reset();
  441. }
  442. /// Returns true, if region is ordered (has associated 'ordered' clause),
  443. /// false - otherwise.
  444. bool isOrderedRegion() const {
  445. if (isStackEmpty())
  446. return false;
  447. return Stack.back().first.rbegin()->OrderedRegion.hasValue();
  448. }
  449. /// Returns optional parameter for the ordered region.
  450. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  451. if (isStackEmpty() ||
  452. !Stack.back().first.rbegin()->OrderedRegion.hasValue())
  453. return std::make_pair(nullptr, nullptr);
  454. return Stack.back().first.rbegin()->OrderedRegion.getValue();
  455. }
  456. /// Returns true, if parent region is ordered (has associated
  457. /// 'ordered' clause), false - otherwise.
  458. bool isParentOrderedRegion() const {
  459. if (isStackEmpty() || Stack.back().first.size() == 1)
  460. return false;
  461. return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
  462. }
  463. /// Returns optional parameter for the ordered region.
  464. std::pair<const Expr *, OMPOrderedClause *>
  465. getParentOrderedRegionParam() const {
  466. if (isStackEmpty() || Stack.back().first.size() == 1 ||
  467. !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
  468. return std::make_pair(nullptr, nullptr);
  469. return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
  470. }
  471. /// Marks current region as nowait (it has a 'nowait' clause).
  472. void setNowaitRegion(bool IsNowait = true) {
  473. assert(!isStackEmpty());
  474. Stack.back().first.back().NowaitRegion = IsNowait;
  475. }
  476. /// Returns true, if parent region is nowait (has associated
  477. /// 'nowait' clause), false - otherwise.
  478. bool isParentNowaitRegion() const {
  479. if (isStackEmpty() || Stack.back().first.size() == 1)
  480. return false;
  481. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  482. }
  483. /// Marks parent region as cancel region.
  484. void setParentCancelRegion(bool Cancel = true) {
  485. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  486. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  487. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  488. }
  489. }
  490. /// Return true if current region has inner cancel construct.
  491. bool isCancelRegion() const {
  492. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  493. }
  494. /// Set collapse value for the region.
  495. void setAssociatedLoops(unsigned Val) {
  496. assert(!isStackEmpty());
  497. Stack.back().first.back().AssociatedLoops = Val;
  498. }
  499. /// Return collapse value for region.
  500. unsigned getAssociatedLoops() const {
  501. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  502. }
  503. /// Marks current target region as one with closely nested teams
  504. /// region.
  505. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  506. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  507. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  508. TeamsRegionLoc;
  509. }
  510. }
  511. /// Returns true, if current region has closely nested teams region.
  512. bool hasInnerTeamsRegion() const {
  513. return getInnerTeamsRegionLoc().isValid();
  514. }
  515. /// Returns location of the nested teams region (if any).
  516. SourceLocation getInnerTeamsRegionLoc() const {
  517. return isStackEmpty() ? SourceLocation()
  518. : Stack.back().first.back().InnerTeamsRegionLoc;
  519. }
  520. Scope *getCurScope() const {
  521. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  522. }
  523. SourceLocation getConstructLoc() const {
  524. return isStackEmpty() ? SourceLocation()
  525. : Stack.back().first.back().ConstructLoc;
  526. }
  527. /// Do the check specified in \a Check to all component lists and return true
  528. /// if any issue is found.
  529. bool checkMappableExprComponentListsForDecl(
  530. const ValueDecl *VD, bool CurrentRegionOnly,
  531. const llvm::function_ref<
  532. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  533. OpenMPClauseKind)>
  534. Check) const {
  535. if (isStackEmpty())
  536. return false;
  537. auto SI = Stack.back().first.rbegin();
  538. auto SE = Stack.back().first.rend();
  539. if (SI == SE)
  540. return false;
  541. if (CurrentRegionOnly)
  542. SE = std::next(SI);
  543. else
  544. std::advance(SI, 1);
  545. for (; SI != SE; ++SI) {
  546. auto MI = SI->MappedExprComponents.find(VD);
  547. if (MI != SI->MappedExprComponents.end())
  548. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  549. MI->second.Components)
  550. if (Check(L, MI->second.Kind))
  551. return true;
  552. }
  553. return false;
  554. }
  555. /// Do the check specified in \a Check to all component lists at a given level
  556. /// and return true if any issue is found.
  557. bool checkMappableExprComponentListsForDeclAtLevel(
  558. const ValueDecl *VD, unsigned Level,
  559. const llvm::function_ref<
  560. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  561. OpenMPClauseKind)>
  562. Check) const {
  563. if (isStackEmpty())
  564. return false;
  565. auto StartI = Stack.back().first.begin();
  566. auto EndI = Stack.back().first.end();
  567. if (std::distance(StartI, EndI) <= (int)Level)
  568. return false;
  569. std::advance(StartI, Level);
  570. auto MI = StartI->MappedExprComponents.find(VD);
  571. if (MI != StartI->MappedExprComponents.end())
  572. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  573. MI->second.Components)
  574. if (Check(L, MI->second.Kind))
  575. return true;
  576. return false;
  577. }
  578. /// Create a new mappable expression component list associated with a given
  579. /// declaration and initialize it with the provided list of components.
  580. void addMappableExpressionComponents(
  581. const ValueDecl *VD,
  582. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  583. OpenMPClauseKind WhereFoundClauseKind) {
  584. assert(!isStackEmpty() &&
  585. "Not expecting to retrieve components from a empty stack!");
  586. MappedExprComponentTy &MEC =
  587. Stack.back().first.back().MappedExprComponents[VD];
  588. // Create new entry and append the new components there.
  589. MEC.Components.resize(MEC.Components.size() + 1);
  590. MEC.Components.back().append(Components.begin(), Components.end());
  591. MEC.Kind = WhereFoundClauseKind;
  592. }
  593. unsigned getNestingLevel() const {
  594. assert(!isStackEmpty());
  595. return Stack.back().first.size() - 1;
  596. }
  597. void addDoacrossDependClause(OMPDependClause *C,
  598. const OperatorOffsetTy &OpsOffs) {
  599. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  600. SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  601. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  602. StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
  603. }
  604. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  605. getDoacrossDependClauses() const {
  606. assert(!isStackEmpty());
  607. const SharingMapTy &StackElem = Stack.back().first.back();
  608. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  609. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  610. return llvm::make_range(Ref.begin(), Ref.end());
  611. }
  612. return llvm::make_range(StackElem.DoacrossDepends.end(),
  613. StackElem.DoacrossDepends.end());
  614. }
  615. };
  616. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  617. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  618. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  619. }
  620. } // namespace
  621. static const Expr *getExprAsWritten(const Expr *E) {
  622. if (const auto *FE = dyn_cast<FullExpr>(E))
  623. E = FE->getSubExpr();
  624. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  625. E = MTE->GetTemporaryExpr();
  626. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  627. E = Binder->getSubExpr();
  628. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  629. E = ICE->getSubExprAsWritten();
  630. return E->IgnoreParens();
  631. }
  632. static Expr *getExprAsWritten(Expr *E) {
  633. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  634. }
  635. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  636. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  637. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  638. D = ME->getMemberDecl();
  639. const auto *VD = dyn_cast<VarDecl>(D);
  640. const auto *FD = dyn_cast<FieldDecl>(D);
  641. if (VD != nullptr) {
  642. VD = VD->getCanonicalDecl();
  643. D = VD;
  644. } else {
  645. assert(FD);
  646. FD = FD->getCanonicalDecl();
  647. D = FD;
  648. }
  649. return D;
  650. }
  651. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  652. return const_cast<ValueDecl *>(
  653. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  654. }
  655. DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
  656. ValueDecl *D) const {
  657. D = getCanonicalDecl(D);
  658. auto *VD = dyn_cast<VarDecl>(D);
  659. const auto *FD = dyn_cast<FieldDecl>(D);
  660. DSAVarData DVar;
  661. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  662. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  663. // in a region but not in construct]
  664. // File-scope or namespace-scope variables referenced in called routines
  665. // in the region are shared unless they appear in a threadprivate
  666. // directive.
  667. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  668. DVar.CKind = OMPC_shared;
  669. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  670. // in a region but not in construct]
  671. // Variables with static storage duration that are declared in called
  672. // routines in the region are shared.
  673. if (VD && VD->hasGlobalStorage())
  674. DVar.CKind = OMPC_shared;
  675. // Non-static data members are shared by default.
  676. if (FD)
  677. DVar.CKind = OMPC_shared;
  678. return DVar;
  679. }
  680. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  681. // in a Construct, C/C++, predetermined, p.1]
  682. // Variables with automatic storage duration that are declared in a scope
  683. // inside the construct are private.
  684. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  685. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  686. DVar.CKind = OMPC_private;
  687. return DVar;
  688. }
  689. DVar.DKind = Iter->Directive;
  690. // Explicitly specified attributes and local variables with predetermined
  691. // attributes.
  692. if (Iter->SharingMap.count(D)) {
  693. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  694. DVar.RefExpr = Data.RefExpr.getPointer();
  695. DVar.PrivateCopy = Data.PrivateCopy;
  696. DVar.CKind = Data.Attributes;
  697. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  698. return DVar;
  699. }
  700. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  701. // in a Construct, C/C++, implicitly determined, p.1]
  702. // In a parallel or task construct, the data-sharing attributes of these
  703. // variables are determined by the default clause, if present.
  704. switch (Iter->DefaultAttr) {
  705. case DSA_shared:
  706. DVar.CKind = OMPC_shared;
  707. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  708. return DVar;
  709. case DSA_none:
  710. return DVar;
  711. case DSA_unspecified:
  712. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  713. // in a Construct, implicitly determined, p.2]
  714. // In a parallel construct, if no default clause is present, these
  715. // variables are shared.
  716. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  717. if (isOpenMPParallelDirective(DVar.DKind) ||
  718. isOpenMPTeamsDirective(DVar.DKind)) {
  719. DVar.CKind = OMPC_shared;
  720. return DVar;
  721. }
  722. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  723. // in a Construct, implicitly determined, p.4]
  724. // In a task construct, if no default clause is present, a variable that in
  725. // the enclosing context is determined to be shared by all implicit tasks
  726. // bound to the current team is shared.
  727. if (isOpenMPTaskingDirective(DVar.DKind)) {
  728. DSAVarData DVarTemp;
  729. iterator I = Iter, E = Stack.back().first.rend();
  730. do {
  731. ++I;
  732. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  733. // Referenced in a Construct, implicitly determined, p.6]
  734. // In a task construct, if no default clause is present, a variable
  735. // whose data-sharing attribute is not determined by the rules above is
  736. // firstprivate.
  737. DVarTemp = getDSA(I, D);
  738. if (DVarTemp.CKind != OMPC_shared) {
  739. DVar.RefExpr = nullptr;
  740. DVar.CKind = OMPC_firstprivate;
  741. return DVar;
  742. }
  743. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  744. DVar.CKind =
  745. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  746. return DVar;
  747. }
  748. }
  749. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  750. // in a Construct, implicitly determined, p.3]
  751. // For constructs other than task, if no default clause is present, these
  752. // variables inherit their data-sharing attributes from the enclosing
  753. // context.
  754. return getDSA(++Iter, D);
  755. }
  756. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  757. const Expr *NewDE) {
  758. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  759. D = getCanonicalDecl(D);
  760. SharingMapTy &StackElem = Stack.back().first.back();
  761. auto It = StackElem.AlignedMap.find(D);
  762. if (It == StackElem.AlignedMap.end()) {
  763. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  764. StackElem.AlignedMap[D] = NewDE;
  765. return nullptr;
  766. }
  767. assert(It->second && "Unexpected nullptr expr in the aligned map");
  768. return It->second;
  769. }
  770. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  771. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  772. D = getCanonicalDecl(D);
  773. SharingMapTy &StackElem = Stack.back().first.back();
  774. StackElem.LCVMap.try_emplace(
  775. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  776. }
  777. const DSAStackTy::LCDeclInfo
  778. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  779. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  780. D = getCanonicalDecl(D);
  781. const SharingMapTy &StackElem = Stack.back().first.back();
  782. auto It = StackElem.LCVMap.find(D);
  783. if (It != StackElem.LCVMap.end())
  784. return It->second;
  785. return {0, nullptr};
  786. }
  787. const DSAStackTy::LCDeclInfo
  788. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  789. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  790. "Data-sharing attributes stack is empty");
  791. D = getCanonicalDecl(D);
  792. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  793. auto It = StackElem.LCVMap.find(D);
  794. if (It != StackElem.LCVMap.end())
  795. return It->second;
  796. return {0, nullptr};
  797. }
  798. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  799. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  800. "Data-sharing attributes stack is empty");
  801. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  802. if (StackElem.LCVMap.size() < I)
  803. return nullptr;
  804. for (const auto &Pair : StackElem.LCVMap)
  805. if (Pair.second.first == I)
  806. return Pair.first;
  807. return nullptr;
  808. }
  809. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  810. DeclRefExpr *PrivateCopy) {
  811. D = getCanonicalDecl(D);
  812. if (A == OMPC_threadprivate) {
  813. DSAInfo &Data = Threadprivates[D];
  814. Data.Attributes = A;
  815. Data.RefExpr.setPointer(E);
  816. Data.PrivateCopy = nullptr;
  817. } else {
  818. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  819. DSAInfo &Data = Stack.back().first.back().SharingMap[D];
  820. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  821. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  822. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  823. (isLoopControlVariable(D).first && A == OMPC_private));
  824. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  825. Data.RefExpr.setInt(/*IntVal=*/true);
  826. return;
  827. }
  828. const bool IsLastprivate =
  829. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  830. Data.Attributes = A;
  831. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  832. Data.PrivateCopy = PrivateCopy;
  833. if (PrivateCopy) {
  834. DSAInfo &Data =
  835. Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  836. Data.Attributes = A;
  837. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  838. Data.PrivateCopy = nullptr;
  839. }
  840. }
  841. }
  842. /// Build a variable declaration for OpenMP loop iteration variable.
  843. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  844. StringRef Name, const AttrVec *Attrs = nullptr,
  845. DeclRefExpr *OrigRef = nullptr) {
  846. DeclContext *DC = SemaRef.CurContext;
  847. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  848. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  849. auto *Decl =
  850. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  851. if (Attrs) {
  852. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  853. I != E; ++I)
  854. Decl->addAttr(*I);
  855. }
  856. Decl->setImplicit();
  857. if (OrigRef) {
  858. Decl->addAttr(
  859. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  860. }
  861. return Decl;
  862. }
  863. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  864. SourceLocation Loc,
  865. bool RefersToCapture = false) {
  866. D->setReferenced();
  867. D->markUsed(S.Context);
  868. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  869. SourceLocation(), D, RefersToCapture, Loc, Ty,
  870. VK_LValue);
  871. }
  872. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  873. BinaryOperatorKind BOK) {
  874. D = getCanonicalDecl(D);
  875. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  876. assert(
  877. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  878. "Additional reduction info may be specified only for reduction items.");
  879. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  880. assert(ReductionData.ReductionRange.isInvalid() &&
  881. Stack.back().first.back().Directive == OMPD_taskgroup &&
  882. "Additional reduction info may be specified only once for reduction "
  883. "items.");
  884. ReductionData.set(BOK, SR);
  885. Expr *&TaskgroupReductionRef =
  886. Stack.back().first.back().TaskgroupReductionRef;
  887. if (!TaskgroupReductionRef) {
  888. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  889. SemaRef.Context.VoidPtrTy, ".task_red.");
  890. TaskgroupReductionRef =
  891. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  892. }
  893. }
  894. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  895. const Expr *ReductionRef) {
  896. D = getCanonicalDecl(D);
  897. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  898. assert(
  899. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  900. "Additional reduction info may be specified only for reduction items.");
  901. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  902. assert(ReductionData.ReductionRange.isInvalid() &&
  903. Stack.back().first.back().Directive == OMPD_taskgroup &&
  904. "Additional reduction info may be specified only once for reduction "
  905. "items.");
  906. ReductionData.set(ReductionRef, SR);
  907. Expr *&TaskgroupReductionRef =
  908. Stack.back().first.back().TaskgroupReductionRef;
  909. if (!TaskgroupReductionRef) {
  910. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  911. SemaRef.Context.VoidPtrTy, ".task_red.");
  912. TaskgroupReductionRef =
  913. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  914. }
  915. }
  916. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  917. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  918. Expr *&TaskgroupDescriptor) const {
  919. D = getCanonicalDecl(D);
  920. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  921. if (Stack.back().first.empty())
  922. return DSAVarData();
  923. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  924. E = Stack.back().first.rend();
  925. I != E; std::advance(I, 1)) {
  926. const DSAInfo &Data = I->SharingMap.lookup(D);
  927. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  928. continue;
  929. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  930. if (!ReductionData.ReductionOp ||
  931. ReductionData.ReductionOp.is<const Expr *>())
  932. return DSAVarData();
  933. SR = ReductionData.ReductionRange;
  934. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  935. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  936. "expression for the descriptor is not "
  937. "set.");
  938. TaskgroupDescriptor = I->TaskgroupReductionRef;
  939. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  940. Data.PrivateCopy, I->DefaultAttrLoc);
  941. }
  942. return DSAVarData();
  943. }
  944. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  945. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  946. Expr *&TaskgroupDescriptor) const {
  947. D = getCanonicalDecl(D);
  948. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  949. if (Stack.back().first.empty())
  950. return DSAVarData();
  951. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  952. E = Stack.back().first.rend();
  953. I != E; std::advance(I, 1)) {
  954. const DSAInfo &Data = I->SharingMap.lookup(D);
  955. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  956. continue;
  957. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  958. if (!ReductionData.ReductionOp ||
  959. !ReductionData.ReductionOp.is<const Expr *>())
  960. return DSAVarData();
  961. SR = ReductionData.ReductionRange;
  962. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  963. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  964. "expression for the descriptor is not "
  965. "set.");
  966. TaskgroupDescriptor = I->TaskgroupReductionRef;
  967. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  968. Data.PrivateCopy, I->DefaultAttrLoc);
  969. }
  970. return DSAVarData();
  971. }
  972. bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
  973. D = D->getCanonicalDecl();
  974. if (!isStackEmpty()) {
  975. iterator I = Iter, E = Stack.back().first.rend();
  976. Scope *TopScope = nullptr;
  977. while (I != E && !isParallelOrTaskRegion(I->Directive) &&
  978. !isOpenMPTargetExecutionDirective(I->Directive))
  979. ++I;
  980. if (I == E)
  981. return false;
  982. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  983. Scope *CurScope = getCurScope();
  984. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  985. CurScope = CurScope->getParent();
  986. return CurScope != TopScope;
  987. }
  988. return false;
  989. }
  990. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  991. bool FromParent) {
  992. D = getCanonicalDecl(D);
  993. DSAVarData DVar;
  994. auto *VD = dyn_cast<VarDecl>(D);
  995. auto TI = Threadprivates.find(D);
  996. if (TI != Threadprivates.end()) {
  997. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  998. DVar.CKind = OMPC_threadprivate;
  999. return DVar;
  1000. }
  1001. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1002. DVar.RefExpr = buildDeclRefExpr(
  1003. SemaRef, VD, D->getType().getNonReferenceType(),
  1004. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1005. DVar.CKind = OMPC_threadprivate;
  1006. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1007. return DVar;
  1008. }
  1009. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1010. // in a Construct, C/C++, predetermined, p.1]
  1011. // Variables appearing in threadprivate directives are threadprivate.
  1012. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1013. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1014. SemaRef.getLangOpts().OpenMPUseTLS &&
  1015. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1016. (VD && VD->getStorageClass() == SC_Register &&
  1017. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1018. DVar.RefExpr = buildDeclRefExpr(
  1019. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1020. DVar.CKind = OMPC_threadprivate;
  1021. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1022. return DVar;
  1023. }
  1024. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1025. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1026. !isLoopControlVariable(D).first) {
  1027. iterator IterTarget =
  1028. std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
  1029. [](const SharingMapTy &Data) {
  1030. return isOpenMPTargetExecutionDirective(Data.Directive);
  1031. });
  1032. if (IterTarget != Stack.back().first.rend()) {
  1033. iterator ParentIterTarget = std::next(IterTarget, 1);
  1034. for (iterator Iter = Stack.back().first.rbegin();
  1035. Iter != ParentIterTarget; std::advance(Iter, 1)) {
  1036. if (isOpenMPLocal(VD, Iter)) {
  1037. DVar.RefExpr =
  1038. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1039. D->getLocation());
  1040. DVar.CKind = OMPC_threadprivate;
  1041. return DVar;
  1042. }
  1043. }
  1044. if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
  1045. auto DSAIter = IterTarget->SharingMap.find(D);
  1046. if (DSAIter != IterTarget->SharingMap.end() &&
  1047. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1048. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1049. DVar.CKind = OMPC_threadprivate;
  1050. return DVar;
  1051. }
  1052. iterator End = Stack.back().first.rend();
  1053. if (!SemaRef.isOpenMPCapturedByRef(
  1054. D, std::distance(ParentIterTarget, End))) {
  1055. DVar.RefExpr =
  1056. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1057. IterTarget->ConstructLoc);
  1058. DVar.CKind = OMPC_threadprivate;
  1059. return DVar;
  1060. }
  1061. }
  1062. }
  1063. }
  1064. if (isStackEmpty())
  1065. // Not in OpenMP execution region and top scope was already checked.
  1066. return DVar;
  1067. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1068. // in a Construct, C/C++, predetermined, p.4]
  1069. // Static data members are shared.
  1070. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1071. // in a Construct, C/C++, predetermined, p.7]
  1072. // Variables with static storage duration that are declared in a scope
  1073. // inside the construct are shared.
  1074. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1075. if (VD && VD->isStaticDataMember()) {
  1076. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  1077. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1078. return DVar;
  1079. DVar.CKind = OMPC_shared;
  1080. return DVar;
  1081. }
  1082. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  1083. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  1084. Type = SemaRef.getASTContext().getBaseElementType(Type);
  1085. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1086. // in a Construct, C/C++, predetermined, p.6]
  1087. // Variables with const qualified type having no mutable member are
  1088. // shared.
  1089. const CXXRecordDecl *RD =
  1090. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  1091. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1092. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1093. RD = CTD->getTemplatedDecl();
  1094. if (IsConstant &&
  1095. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  1096. RD->hasMutableFields())) {
  1097. // Variables with const-qualified type having no mutable member may be
  1098. // listed in a firstprivate clause, even if they are static data members.
  1099. DSAVarData DVarTemp =
  1100. hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
  1101. MatchesAlways, FromParent);
  1102. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  1103. return DVarTemp;
  1104. DVar.CKind = OMPC_shared;
  1105. return DVar;
  1106. }
  1107. // Explicitly specified attributes and local variables with predetermined
  1108. // attributes.
  1109. iterator I = Stack.back().first.rbegin();
  1110. iterator EndI = Stack.back().first.rend();
  1111. if (FromParent && I != EndI)
  1112. std::advance(I, 1);
  1113. auto It = I->SharingMap.find(D);
  1114. if (It != I->SharingMap.end()) {
  1115. const DSAInfo &Data = It->getSecond();
  1116. DVar.RefExpr = Data.RefExpr.getPointer();
  1117. DVar.PrivateCopy = Data.PrivateCopy;
  1118. DVar.CKind = Data.Attributes;
  1119. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1120. DVar.DKind = I->Directive;
  1121. }
  1122. return DVar;
  1123. }
  1124. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1125. bool FromParent) const {
  1126. if (isStackEmpty()) {
  1127. iterator I;
  1128. return getDSA(I, D);
  1129. }
  1130. D = getCanonicalDecl(D);
  1131. iterator StartI = Stack.back().first.rbegin();
  1132. iterator EndI = Stack.back().first.rend();
  1133. if (FromParent && StartI != EndI)
  1134. std::advance(StartI, 1);
  1135. return getDSA(StartI, D);
  1136. }
  1137. const DSAStackTy::DSAVarData
  1138. DSAStackTy::hasDSA(ValueDecl *D,
  1139. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1140. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1141. bool FromParent) const {
  1142. if (isStackEmpty())
  1143. return {};
  1144. D = getCanonicalDecl(D);
  1145. iterator I = Stack.back().first.rbegin();
  1146. iterator EndI = Stack.back().first.rend();
  1147. if (FromParent && I != EndI)
  1148. std::advance(I, 1);
  1149. for (; I != EndI; std::advance(I, 1)) {
  1150. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  1151. continue;
  1152. iterator NewI = I;
  1153. DSAVarData DVar = getDSA(NewI, D);
  1154. if (I == NewI && CPred(DVar.CKind))
  1155. return DVar;
  1156. }
  1157. return {};
  1158. }
  1159. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1160. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1161. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1162. bool FromParent) const {
  1163. if (isStackEmpty())
  1164. return {};
  1165. D = getCanonicalDecl(D);
  1166. iterator StartI = Stack.back().first.rbegin();
  1167. iterator EndI = Stack.back().first.rend();
  1168. if (FromParent && StartI != EndI)
  1169. std::advance(StartI, 1);
  1170. if (StartI == EndI || !DPred(StartI->Directive))
  1171. return {};
  1172. iterator NewI = StartI;
  1173. DSAVarData DVar = getDSA(NewI, D);
  1174. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1175. }
  1176. bool DSAStackTy::hasExplicitDSA(
  1177. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1178. unsigned Level, bool NotLastprivate) const {
  1179. if (isStackEmpty())
  1180. return false;
  1181. D = getCanonicalDecl(D);
  1182. auto StartI = Stack.back().first.begin();
  1183. auto EndI = Stack.back().first.end();
  1184. if (std::distance(StartI, EndI) <= (int)Level)
  1185. return false;
  1186. std::advance(StartI, Level);
  1187. auto I = StartI->SharingMap.find(D);
  1188. return (I != StartI->SharingMap.end()) &&
  1189. I->getSecond().RefExpr.getPointer() &&
  1190. CPred(I->getSecond().Attributes) &&
  1191. (!NotLastprivate || !I->getSecond().RefExpr.getInt());
  1192. }
  1193. bool DSAStackTy::hasExplicitDirective(
  1194. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1195. unsigned Level) const {
  1196. if (isStackEmpty())
  1197. return false;
  1198. auto StartI = Stack.back().first.begin();
  1199. auto EndI = Stack.back().first.end();
  1200. if (std::distance(StartI, EndI) <= (int)Level)
  1201. return false;
  1202. std::advance(StartI, Level);
  1203. return DPred(StartI->Directive);
  1204. }
  1205. bool DSAStackTy::hasDirective(
  1206. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1207. const DeclarationNameInfo &, SourceLocation)>
  1208. DPred,
  1209. bool FromParent) const {
  1210. // We look only in the enclosing region.
  1211. if (isStackEmpty())
  1212. return false;
  1213. auto StartI = std::next(Stack.back().first.rbegin());
  1214. auto EndI = Stack.back().first.rend();
  1215. if (FromParent && StartI != EndI)
  1216. StartI = std::next(StartI);
  1217. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1218. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1219. return true;
  1220. }
  1221. return false;
  1222. }
  1223. void Sema::InitDataSharingAttributesStack() {
  1224. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1225. }
  1226. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1227. void Sema::pushOpenMPFunctionRegion() {
  1228. DSAStack->pushFunction();
  1229. }
  1230. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1231. DSAStack->popFunction(OldFSI);
  1232. }
  1233. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1234. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1235. ASTContext &Ctx = getASTContext();
  1236. bool IsByRef = true;
  1237. // Find the directive that is associated with the provided scope.
  1238. D = cast<ValueDecl>(D->getCanonicalDecl());
  1239. QualType Ty = D->getType();
  1240. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1241. // This table summarizes how a given variable should be passed to the device
  1242. // given its type and the clauses where it appears. This table is based on
  1243. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1244. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1245. //
  1246. // =========================================================================
  1247. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1248. // | |(tofrom:scalar)| | pvt | | | |
  1249. // =========================================================================
  1250. // | scl | | | | - | | bycopy|
  1251. // | scl | | - | x | - | - | bycopy|
  1252. // | scl | | x | - | - | - | null |
  1253. // | scl | x | | | - | | byref |
  1254. // | scl | x | - | x | - | - | bycopy|
  1255. // | scl | x | x | - | - | - | null |
  1256. // | scl | | - | - | - | x | byref |
  1257. // | scl | x | - | - | - | x | byref |
  1258. //
  1259. // | agg | n.a. | | | - | | byref |
  1260. // | agg | n.a. | - | x | - | - | byref |
  1261. // | agg | n.a. | x | - | - | - | null |
  1262. // | agg | n.a. | - | - | - | x | byref |
  1263. // | agg | n.a. | - | - | - | x[] | byref |
  1264. //
  1265. // | ptr | n.a. | | | - | | bycopy|
  1266. // | ptr | n.a. | - | x | - | - | bycopy|
  1267. // | ptr | n.a. | x | - | - | - | null |
  1268. // | ptr | n.a. | - | - | - | x | byref |
  1269. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1270. // | ptr | n.a. | - | - | x | | bycopy|
  1271. // | ptr | n.a. | - | - | x | x | bycopy|
  1272. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1273. // =========================================================================
  1274. // Legend:
  1275. // scl - scalar
  1276. // ptr - pointer
  1277. // agg - aggregate
  1278. // x - applies
  1279. // - - invalid in this combination
  1280. // [] - mapped with an array section
  1281. // byref - should be mapped by reference
  1282. // byval - should be mapped by value
  1283. // null - initialize a local variable to null on the device
  1284. //
  1285. // Observations:
  1286. // - All scalar declarations that show up in a map clause have to be passed
  1287. // by reference, because they may have been mapped in the enclosing data
  1288. // environment.
  1289. // - If the scalar value does not fit the size of uintptr, it has to be
  1290. // passed by reference, regardless the result in the table above.
  1291. // - For pointers mapped by value that have either an implicit map or an
  1292. // array section, the runtime library may pass the NULL value to the
  1293. // device instead of the value passed to it by the compiler.
  1294. if (Ty->isReferenceType())
  1295. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1296. // Locate map clauses and see if the variable being captured is referred to
  1297. // in any of those clauses. Here we only care about variables, not fields,
  1298. // because fields are part of aggregates.
  1299. bool IsVariableUsedInMapClause = false;
  1300. bool IsVariableAssociatedWithSection = false;
  1301. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1302. D, Level,
  1303. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1304. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1305. MapExprComponents,
  1306. OpenMPClauseKind WhereFoundClauseKind) {
  1307. // Only the map clause information influences how a variable is
  1308. // captured. E.g. is_device_ptr does not require changing the default
  1309. // behavior.
  1310. if (WhereFoundClauseKind != OMPC_map)
  1311. return false;
  1312. auto EI = MapExprComponents.rbegin();
  1313. auto EE = MapExprComponents.rend();
  1314. assert(EI != EE && "Invalid map expression!");
  1315. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1316. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1317. ++EI;
  1318. if (EI == EE)
  1319. return false;
  1320. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1321. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1322. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1323. IsVariableAssociatedWithSection = true;
  1324. // There is nothing more we need to know about this variable.
  1325. return true;
  1326. }
  1327. // Keep looking for more map info.
  1328. return false;
  1329. });
  1330. if (IsVariableUsedInMapClause) {
  1331. // If variable is identified in a map clause it is always captured by
  1332. // reference except if it is a pointer that is dereferenced somehow.
  1333. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1334. } else {
  1335. // By default, all the data that has a scalar type is mapped by copy
  1336. // (except for reduction variables).
  1337. IsByRef =
  1338. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1339. !Ty->isAnyPointerType()) ||
  1340. !Ty->isScalarType() ||
  1341. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1342. DSAStack->hasExplicitDSA(
  1343. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1344. }
  1345. }
  1346. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1347. IsByRef =
  1348. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1349. !Ty->isAnyPointerType()) ||
  1350. !DSAStack->hasExplicitDSA(
  1351. D,
  1352. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1353. Level, /*NotLastprivate=*/true)) &&
  1354. // If the variable is artificial and must be captured by value - try to
  1355. // capture by value.
  1356. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1357. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1358. }
  1359. // When passing data by copy, we need to make sure it fits the uintptr size
  1360. // and alignment, because the runtime library only deals with uintptr types.
  1361. // If it does not fit the uintptr size, we need to pass the data by reference
  1362. // instead.
  1363. if (!IsByRef &&
  1364. (Ctx.getTypeSizeInChars(Ty) >
  1365. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1366. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1367. IsByRef = true;
  1368. }
  1369. return IsByRef;
  1370. }
  1371. unsigned Sema::getOpenMPNestingLevel() const {
  1372. assert(getLangOpts().OpenMP);
  1373. return DSAStack->getNestingLevel();
  1374. }
  1375. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1376. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1377. !DSAStack->isClauseParsingMode()) ||
  1378. DSAStack->hasDirective(
  1379. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1380. SourceLocation) -> bool {
  1381. return isOpenMPTargetExecutionDirective(K);
  1382. },
  1383. false);
  1384. }
  1385. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
  1386. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1387. D = getCanonicalDecl(D);
  1388. // If we are attempting to capture a global variable in a directive with
  1389. // 'target' we return true so that this global is also mapped to the device.
  1390. //
  1391. auto *VD = dyn_cast<VarDecl>(D);
  1392. if (VD && !VD->hasLocalStorage()) {
  1393. if (isInOpenMPDeclareTargetContext() &&
  1394. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1395. // Try to mark variable as declare target if it is used in capturing
  1396. // regions.
  1397. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1398. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1399. return nullptr;
  1400. } else if (isInOpenMPTargetExecutionDirective()) {
  1401. // If the declaration is enclosed in a 'declare target' directive,
  1402. // then it should not be captured.
  1403. //
  1404. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1405. return nullptr;
  1406. return VD;
  1407. }
  1408. }
  1409. // Capture variables captured by reference in lambdas for target-based
  1410. // directives.
  1411. if (VD && !DSAStack->isClauseParsingMode()) {
  1412. if (const auto *RD = VD->getType()
  1413. .getCanonicalType()
  1414. .getNonReferenceType()
  1415. ->getAsCXXRecordDecl()) {
  1416. bool SavedForceCaptureByReferenceInTargetExecutable =
  1417. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1418. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1419. if (RD->isLambda())
  1420. for (const LambdaCapture &LC : RD->captures()) {
  1421. if (LC.getCaptureKind() == LCK_ByRef) {
  1422. VarDecl *VD = LC.getCapturedVar();
  1423. DeclContext *VDC = VD->getDeclContext();
  1424. if (!VDC->Encloses(CurContext))
  1425. continue;
  1426. DSAStackTy::DSAVarData DVarPrivate =
  1427. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1428. // Do not capture already captured variables.
  1429. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1430. DVarPrivate.CKind == OMPC_unknown &&
  1431. !DSAStack->checkMappableExprComponentListsForDecl(
  1432. D, /*CurrentRegionOnly=*/true,
  1433. [](OMPClauseMappableExprCommon::
  1434. MappableExprComponentListRef,
  1435. OpenMPClauseKind) { return true; }))
  1436. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1437. } else if (LC.getCaptureKind() == LCK_This) {
  1438. CheckCXXThisCapture(LC.getLocation());
  1439. }
  1440. }
  1441. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1442. SavedForceCaptureByReferenceInTargetExecutable);
  1443. }
  1444. }
  1445. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1446. (!DSAStack->isClauseParsingMode() ||
  1447. DSAStack->getParentDirective() != OMPD_unknown)) {
  1448. auto &&Info = DSAStack->isLoopControlVariable(D);
  1449. if (Info.first ||
  1450. (VD && VD->hasLocalStorage() &&
  1451. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1452. (VD && DSAStack->isForceVarCapturing()))
  1453. return VD ? VD : Info.second;
  1454. DSAStackTy::DSAVarData DVarPrivate =
  1455. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1456. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1457. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1458. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1459. [](OpenMPDirectiveKind) { return true; },
  1460. DSAStack->isClauseParsingMode());
  1461. if (DVarPrivate.CKind != OMPC_unknown)
  1462. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1463. }
  1464. return nullptr;
  1465. }
  1466. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1467. unsigned Level) const {
  1468. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1469. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1470. FunctionScopesIndex -= Regions.size();
  1471. }
  1472. void Sema::startOpenMPLoop() {
  1473. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1474. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1475. DSAStack->loopInit();
  1476. }
  1477. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1478. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1479. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1480. if (DSAStack->getAssociatedLoops() > 0 &&
  1481. !DSAStack->isLoopStarted()) {
  1482. DSAStack->resetPossibleLoopCounter(D);
  1483. DSAStack->loopStart();
  1484. return true;
  1485. }
  1486. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1487. DSAStack->isLoopControlVariable(D).first) &&
  1488. !DSAStack->hasExplicitDSA(
  1489. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1490. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1491. return true;
  1492. }
  1493. return DSAStack->hasExplicitDSA(
  1494. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1495. (DSAStack->isClauseParsingMode() &&
  1496. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1497. // Consider taskgroup reduction descriptor variable a private to avoid
  1498. // possible capture in the region.
  1499. (DSAStack->hasExplicitDirective(
  1500. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1501. Level) &&
  1502. DSAStack->isTaskgroupReductionRef(D, Level));
  1503. }
  1504. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1505. unsigned Level) {
  1506. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1507. D = getCanonicalDecl(D);
  1508. OpenMPClauseKind OMPC = OMPC_unknown;
  1509. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1510. const unsigned NewLevel = I - 1;
  1511. if (DSAStack->hasExplicitDSA(D,
  1512. [&OMPC](const OpenMPClauseKind K) {
  1513. if (isOpenMPPrivate(K)) {
  1514. OMPC = K;
  1515. return true;
  1516. }
  1517. return false;
  1518. },
  1519. NewLevel))
  1520. break;
  1521. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1522. D, NewLevel,
  1523. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1524. OpenMPClauseKind) { return true; })) {
  1525. OMPC = OMPC_map;
  1526. break;
  1527. }
  1528. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1529. NewLevel)) {
  1530. OMPC = OMPC_map;
  1531. if (D->getType()->isScalarType() &&
  1532. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1533. DefaultMapAttributes::DMA_tofrom_scalar)
  1534. OMPC = OMPC_firstprivate;
  1535. break;
  1536. }
  1537. }
  1538. if (OMPC != OMPC_unknown)
  1539. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1540. }
  1541. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1542. unsigned Level) const {
  1543. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1544. // Return true if the current level is no longer enclosed in a target region.
  1545. const auto *VD = dyn_cast<VarDecl>(D);
  1546. return VD && !VD->hasLocalStorage() &&
  1547. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1548. Level);
  1549. }
  1550. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1551. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1552. const DeclarationNameInfo &DirName,
  1553. Scope *CurScope, SourceLocation Loc) {
  1554. DSAStack->push(DKind, DirName, CurScope, Loc);
  1555. PushExpressionEvaluationContext(
  1556. ExpressionEvaluationContext::PotentiallyEvaluated);
  1557. }
  1558. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1559. DSAStack->setClauseParsingMode(K);
  1560. }
  1561. void Sema::EndOpenMPClause() {
  1562. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1563. }
  1564. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1565. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1566. // A variable of class type (or array thereof) that appears in a lastprivate
  1567. // clause requires an accessible, unambiguous default constructor for the
  1568. // class type, unless the list item is also specified in a firstprivate
  1569. // clause.
  1570. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1571. for (OMPClause *C : D->clauses()) {
  1572. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1573. SmallVector<Expr *, 8> PrivateCopies;
  1574. for (Expr *DE : Clause->varlists()) {
  1575. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1576. PrivateCopies.push_back(nullptr);
  1577. continue;
  1578. }
  1579. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1580. auto *VD = cast<VarDecl>(DRE->getDecl());
  1581. QualType Type = VD->getType().getNonReferenceType();
  1582. const DSAStackTy::DSAVarData DVar =
  1583. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1584. if (DVar.CKind == OMPC_lastprivate) {
  1585. // Generate helper private variable and initialize it with the
  1586. // default value. The address of the original variable is replaced
  1587. // by the address of the new private variable in CodeGen. This new
  1588. // variable is not added to IdResolver, so the code in the OpenMP
  1589. // region uses original variable for proper diagnostics.
  1590. VarDecl *VDPrivate = buildVarDecl(
  1591. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1592. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1593. ActOnUninitializedDecl(VDPrivate);
  1594. if (VDPrivate->isInvalidDecl())
  1595. continue;
  1596. PrivateCopies.push_back(buildDeclRefExpr(
  1597. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1598. } else {
  1599. // The variable is also a firstprivate, so initialization sequence
  1600. // for private copy is generated already.
  1601. PrivateCopies.push_back(nullptr);
  1602. }
  1603. }
  1604. // Set initializers to private copies if no errors were found.
  1605. if (PrivateCopies.size() == Clause->varlist_size())
  1606. Clause->setPrivateCopies(PrivateCopies);
  1607. }
  1608. }
  1609. }
  1610. DSAStack->pop();
  1611. DiscardCleanupsInEvaluationContext();
  1612. PopExpressionEvaluationContext();
  1613. }
  1614. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1615. Expr *NumIterations, Sema &SemaRef,
  1616. Scope *S, DSAStackTy *Stack);
  1617. namespace {
  1618. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1619. private:
  1620. Sema &SemaRef;
  1621. public:
  1622. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1623. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1624. NamedDecl *ND = Candidate.getCorrectionDecl();
  1625. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1626. return VD->hasGlobalStorage() &&
  1627. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1628. SemaRef.getCurScope());
  1629. }
  1630. return false;
  1631. }
  1632. };
  1633. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1634. private:
  1635. Sema &SemaRef;
  1636. public:
  1637. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1638. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1639. NamedDecl *ND = Candidate.getCorrectionDecl();
  1640. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1641. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1642. SemaRef.getCurScope());
  1643. }
  1644. return false;
  1645. }
  1646. };
  1647. } // namespace
  1648. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1649. CXXScopeSpec &ScopeSpec,
  1650. const DeclarationNameInfo &Id) {
  1651. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1652. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1653. if (Lookup.isAmbiguous())
  1654. return ExprError();
  1655. VarDecl *VD;
  1656. if (!Lookup.isSingleResult()) {
  1657. if (TypoCorrection Corrected = CorrectTypo(
  1658. Id, LookupOrdinaryName, CurScope, nullptr,
  1659. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1660. diagnoseTypo(Corrected,
  1661. PDiag(Lookup.empty()
  1662. ? diag::err_undeclared_var_use_suggest
  1663. : diag::err_omp_expected_var_arg_suggest)
  1664. << Id.getName());
  1665. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1666. } else {
  1667. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1668. : diag::err_omp_expected_var_arg)
  1669. << Id.getName();
  1670. return ExprError();
  1671. }
  1672. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1673. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1674. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1675. return ExprError();
  1676. }
  1677. Lookup.suppressDiagnostics();
  1678. // OpenMP [2.9.2, Syntax, C/C++]
  1679. // Variables must be file-scope, namespace-scope, or static block-scope.
  1680. if (!VD->hasGlobalStorage()) {
  1681. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1682. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1683. bool IsDecl =
  1684. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1685. Diag(VD->getLocation(),
  1686. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1687. << VD;
  1688. return ExprError();
  1689. }
  1690. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1691. NamedDecl *ND = CanonicalVD;
  1692. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1693. // A threadprivate directive for file-scope variables must appear outside
  1694. // any definition or declaration.
  1695. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1696. !getCurLexicalContext()->isTranslationUnit()) {
  1697. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1698. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1699. bool IsDecl =
  1700. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1701. Diag(VD->getLocation(),
  1702. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1703. << VD;
  1704. return ExprError();
  1705. }
  1706. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1707. // A threadprivate directive for static class member variables must appear
  1708. // in the class definition, in the same scope in which the member
  1709. // variables are declared.
  1710. if (CanonicalVD->isStaticDataMember() &&
  1711. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1712. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1713. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1714. bool IsDecl =
  1715. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1716. Diag(VD->getLocation(),
  1717. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1718. << VD;
  1719. return ExprError();
  1720. }
  1721. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1722. // A threadprivate directive for namespace-scope variables must appear
  1723. // outside any definition or declaration other than the namespace
  1724. // definition itself.
  1725. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1726. (!getCurLexicalContext()->isFileContext() ||
  1727. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1728. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1729. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1730. bool IsDecl =
  1731. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1732. Diag(VD->getLocation(),
  1733. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1734. << VD;
  1735. return ExprError();
  1736. }
  1737. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1738. // A threadprivate directive for static block-scope variables must appear
  1739. // in the scope of the variable and not in a nested scope.
  1740. if (CanonicalVD->isStaticLocal() && CurScope &&
  1741. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1742. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1743. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1744. bool IsDecl =
  1745. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1746. Diag(VD->getLocation(),
  1747. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1748. << VD;
  1749. return ExprError();
  1750. }
  1751. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1752. // A threadprivate directive must lexically precede all references to any
  1753. // of the variables in its list.
  1754. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1755. Diag(Id.getLoc(), diag::err_omp_var_used)
  1756. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1757. return ExprError();
  1758. }
  1759. QualType ExprType = VD->getType().getNonReferenceType();
  1760. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1761. SourceLocation(), VD,
  1762. /*RefersToEnclosingVariableOrCapture=*/false,
  1763. Id.getLoc(), ExprType, VK_LValue);
  1764. }
  1765. Sema::DeclGroupPtrTy
  1766. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1767. ArrayRef<Expr *> VarList) {
  1768. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1769. CurContext->addDecl(D);
  1770. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1771. }
  1772. return nullptr;
  1773. }
  1774. namespace {
  1775. class LocalVarRefChecker final
  1776. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1777. Sema &SemaRef;
  1778. public:
  1779. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1780. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1781. if (VD->hasLocalStorage()) {
  1782. SemaRef.Diag(E->getBeginLoc(),
  1783. diag::err_omp_local_var_in_threadprivate_init)
  1784. << E->getSourceRange();
  1785. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1786. << VD << VD->getSourceRange();
  1787. return true;
  1788. }
  1789. }
  1790. return false;
  1791. }
  1792. bool VisitStmt(const Stmt *S) {
  1793. for (const Stmt *Child : S->children()) {
  1794. if (Child && Visit(Child))
  1795. return true;
  1796. }
  1797. return false;
  1798. }
  1799. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1800. };
  1801. } // namespace
  1802. OMPThreadPrivateDecl *
  1803. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1804. SmallVector<Expr *, 8> Vars;
  1805. for (Expr *RefExpr : VarList) {
  1806. auto *DE = cast<DeclRefExpr>(RefExpr);
  1807. auto *VD = cast<VarDecl>(DE->getDecl());
  1808. SourceLocation ILoc = DE->getExprLoc();
  1809. // Mark variable as used.
  1810. VD->setReferenced();
  1811. VD->markUsed(Context);
  1812. QualType QType = VD->getType();
  1813. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1814. // It will be analyzed later.
  1815. Vars.push_back(DE);
  1816. continue;
  1817. }
  1818. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1819. // A threadprivate variable must not have an incomplete type.
  1820. if (RequireCompleteType(ILoc, VD->getType(),
  1821. diag::err_omp_threadprivate_incomplete_type)) {
  1822. continue;
  1823. }
  1824. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1825. // A threadprivate variable must not have a reference type.
  1826. if (VD->getType()->isReferenceType()) {
  1827. Diag(ILoc, diag::err_omp_ref_type_arg)
  1828. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1829. bool IsDecl =
  1830. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1831. Diag(VD->getLocation(),
  1832. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1833. << VD;
  1834. continue;
  1835. }
  1836. // Check if this is a TLS variable. If TLS is not being supported, produce
  1837. // the corresponding diagnostic.
  1838. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1839. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1840. getLangOpts().OpenMPUseTLS &&
  1841. getASTContext().getTargetInfo().isTLSSupported())) ||
  1842. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1843. !VD->isLocalVarDecl())) {
  1844. Diag(ILoc, diag::err_omp_var_thread_local)
  1845. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1846. bool IsDecl =
  1847. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1848. Diag(VD->getLocation(),
  1849. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1850. << VD;
  1851. continue;
  1852. }
  1853. // Check if initial value of threadprivate variable reference variable with
  1854. // local storage (it is not supported by runtime).
  1855. if (const Expr *Init = VD->getAnyInitializer()) {
  1856. LocalVarRefChecker Checker(*this);
  1857. if (Checker.Visit(Init))
  1858. continue;
  1859. }
  1860. Vars.push_back(RefExpr);
  1861. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1862. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1863. Context, SourceRange(Loc, Loc)));
  1864. if (ASTMutationListener *ML = Context.getASTMutationListener())
  1865. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1866. }
  1867. OMPThreadPrivateDecl *D = nullptr;
  1868. if (!Vars.empty()) {
  1869. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1870. Vars);
  1871. D->setAccess(AS_public);
  1872. }
  1873. return D;
  1874. }
  1875. Sema::DeclGroupPtrTy
  1876. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  1877. ArrayRef<OMPClause *> ClauseList) {
  1878. OMPRequiresDecl *D = nullptr;
  1879. if (!CurContext->isFileContext()) {
  1880. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  1881. } else {
  1882. D = CheckOMPRequiresDecl(Loc, ClauseList);
  1883. if (D) {
  1884. CurContext->addDecl(D);
  1885. DSAStack->addRequiresDecl(D);
  1886. }
  1887. }
  1888. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1889. }
  1890. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  1891. ArrayRef<OMPClause *> ClauseList) {
  1892. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  1893. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  1894. ClauseList);
  1895. return nullptr;
  1896. }
  1897. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  1898. const ValueDecl *D,
  1899. const DSAStackTy::DSAVarData &DVar,
  1900. bool IsLoopIterVar = false) {
  1901. if (DVar.RefExpr) {
  1902. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1903. << getOpenMPClauseName(DVar.CKind);
  1904. return;
  1905. }
  1906. enum {
  1907. PDSA_StaticMemberShared,
  1908. PDSA_StaticLocalVarShared,
  1909. PDSA_LoopIterVarPrivate,
  1910. PDSA_LoopIterVarLinear,
  1911. PDSA_LoopIterVarLastprivate,
  1912. PDSA_ConstVarShared,
  1913. PDSA_GlobalVarShared,
  1914. PDSA_TaskVarFirstprivate,
  1915. PDSA_LocalVarPrivate,
  1916. PDSA_Implicit
  1917. } Reason = PDSA_Implicit;
  1918. bool ReportHint = false;
  1919. auto ReportLoc = D->getLocation();
  1920. auto *VD = dyn_cast<VarDecl>(D);
  1921. if (IsLoopIterVar) {
  1922. if (DVar.CKind == OMPC_private)
  1923. Reason = PDSA_LoopIterVarPrivate;
  1924. else if (DVar.CKind == OMPC_lastprivate)
  1925. Reason = PDSA_LoopIterVarLastprivate;
  1926. else
  1927. Reason = PDSA_LoopIterVarLinear;
  1928. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1929. DVar.CKind == OMPC_firstprivate) {
  1930. Reason = PDSA_TaskVarFirstprivate;
  1931. ReportLoc = DVar.ImplicitDSALoc;
  1932. } else if (VD && VD->isStaticLocal())
  1933. Reason = PDSA_StaticLocalVarShared;
  1934. else if (VD && VD->isStaticDataMember())
  1935. Reason = PDSA_StaticMemberShared;
  1936. else if (VD && VD->isFileVarDecl())
  1937. Reason = PDSA_GlobalVarShared;
  1938. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1939. Reason = PDSA_ConstVarShared;
  1940. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1941. ReportHint = true;
  1942. Reason = PDSA_LocalVarPrivate;
  1943. }
  1944. if (Reason != PDSA_Implicit) {
  1945. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1946. << Reason << ReportHint
  1947. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1948. } else if (DVar.ImplicitDSALoc.isValid()) {
  1949. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1950. << getOpenMPClauseName(DVar.CKind);
  1951. }
  1952. }
  1953. namespace {
  1954. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  1955. DSAStackTy *Stack;
  1956. Sema &SemaRef;
  1957. bool ErrorFound = false;
  1958. CapturedStmt *CS = nullptr;
  1959. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  1960. llvm::SmallVector<Expr *, 4> ImplicitMap;
  1961. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  1962. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  1963. void VisitSubCaptures(OMPExecutableDirective *S) {
  1964. // Check implicitly captured variables.
  1965. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  1966. return;
  1967. for (const CapturedStmt::Capture &Cap :
  1968. S->getInnermostCapturedStmt()->captures()) {
  1969. if (!Cap.capturesVariable())
  1970. continue;
  1971. VarDecl *VD = Cap.getCapturedVar();
  1972. // Do not try to map the variable if it or its sub-component was mapped
  1973. // already.
  1974. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  1975. Stack->checkMappableExprComponentListsForDecl(
  1976. VD, /*CurrentRegionOnly=*/true,
  1977. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1978. OpenMPClauseKind) { return true; }))
  1979. continue;
  1980. DeclRefExpr *DRE = buildDeclRefExpr(
  1981. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  1982. Cap.getLocation(), /*RefersToCapture=*/true);
  1983. Visit(DRE);
  1984. }
  1985. }
  1986. public:
  1987. void VisitDeclRefExpr(DeclRefExpr *E) {
  1988. if (E->isTypeDependent() || E->isValueDependent() ||
  1989. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1990. return;
  1991. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1992. VD = VD->getCanonicalDecl();
  1993. // Skip internally declared variables.
  1994. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1995. return;
  1996. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  1997. // Check if the variable has explicit DSA set and stop analysis if it so.
  1998. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1999. return;
  2000. // Skip internally declared static variables.
  2001. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2002. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2003. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  2004. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2005. return;
  2006. SourceLocation ELoc = E->getExprLoc();
  2007. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2008. // The default(none) clause requires that each variable that is referenced
  2009. // in the construct, and does not have a predetermined data-sharing
  2010. // attribute, must have its data-sharing attribute explicitly determined
  2011. // by being listed in a data-sharing attribute clause.
  2012. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2013. isParallelOrTaskRegion(DKind) &&
  2014. VarsWithInheritedDSA.count(VD) == 0) {
  2015. VarsWithInheritedDSA[VD] = E;
  2016. return;
  2017. }
  2018. if (isOpenMPTargetExecutionDirective(DKind) &&
  2019. !Stack->isLoopControlVariable(VD).first) {
  2020. if (!Stack->checkMappableExprComponentListsForDecl(
  2021. VD, /*CurrentRegionOnly=*/true,
  2022. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2023. StackComponents,
  2024. OpenMPClauseKind) {
  2025. // Variable is used if it has been marked as an array, array
  2026. // section or the variable iself.
  2027. return StackComponents.size() == 1 ||
  2028. std::all_of(
  2029. std::next(StackComponents.rbegin()),
  2030. StackComponents.rend(),
  2031. [](const OMPClauseMappableExprCommon::
  2032. MappableComponent &MC) {
  2033. return MC.getAssociatedDeclaration() ==
  2034. nullptr &&
  2035. (isa<OMPArraySectionExpr>(
  2036. MC.getAssociatedExpression()) ||
  2037. isa<ArraySubscriptExpr>(
  2038. MC.getAssociatedExpression()));
  2039. });
  2040. })) {
  2041. bool IsFirstprivate = false;
  2042. // By default lambdas are captured as firstprivates.
  2043. if (const auto *RD =
  2044. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2045. IsFirstprivate = RD->isLambda();
  2046. IsFirstprivate =
  2047. IsFirstprivate ||
  2048. (VD->getType().getNonReferenceType()->isScalarType() &&
  2049. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2050. if (IsFirstprivate)
  2051. ImplicitFirstprivate.emplace_back(E);
  2052. else
  2053. ImplicitMap.emplace_back(E);
  2054. return;
  2055. }
  2056. }
  2057. // OpenMP [2.9.3.6, Restrictions, p.2]
  2058. // A list item that appears in a reduction clause of the innermost
  2059. // enclosing worksharing or parallel construct may not be accessed in an
  2060. // explicit task.
  2061. DVar = Stack->hasInnermostDSA(
  2062. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2063. [](OpenMPDirectiveKind K) {
  2064. return isOpenMPParallelDirective(K) ||
  2065. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2066. },
  2067. /*FromParent=*/true);
  2068. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2069. ErrorFound = true;
  2070. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2071. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2072. return;
  2073. }
  2074. // Define implicit data-sharing attributes for task.
  2075. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2076. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2077. !Stack->isLoopControlVariable(VD).first)
  2078. ImplicitFirstprivate.push_back(E);
  2079. }
  2080. }
  2081. void VisitMemberExpr(MemberExpr *E) {
  2082. if (E->isTypeDependent() || E->isValueDependent() ||
  2083. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2084. return;
  2085. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2086. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2087. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2088. if (!FD)
  2089. return;
  2090. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2091. // Check if the variable has explicit DSA set and stop analysis if it
  2092. // so.
  2093. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2094. return;
  2095. if (isOpenMPTargetExecutionDirective(DKind) &&
  2096. !Stack->isLoopControlVariable(FD).first &&
  2097. !Stack->checkMappableExprComponentListsForDecl(
  2098. FD, /*CurrentRegionOnly=*/true,
  2099. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2100. StackComponents,
  2101. OpenMPClauseKind) {
  2102. return isa<CXXThisExpr>(
  2103. cast<MemberExpr>(
  2104. StackComponents.back().getAssociatedExpression())
  2105. ->getBase()
  2106. ->IgnoreParens());
  2107. })) {
  2108. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2109. // A bit-field cannot appear in a map clause.
  2110. //
  2111. if (FD->isBitField())
  2112. return;
  2113. ImplicitMap.emplace_back(E);
  2114. return;
  2115. }
  2116. SourceLocation ELoc = E->getExprLoc();
  2117. // OpenMP [2.9.3.6, Restrictions, p.2]
  2118. // A list item that appears in a reduction clause of the innermost
  2119. // enclosing worksharing or parallel construct may not be accessed in
  2120. // an explicit task.
  2121. DVar = Stack->hasInnermostDSA(
  2122. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2123. [](OpenMPDirectiveKind K) {
  2124. return isOpenMPParallelDirective(K) ||
  2125. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2126. },
  2127. /*FromParent=*/true);
  2128. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2129. ErrorFound = true;
  2130. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2131. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2132. return;
  2133. }
  2134. // Define implicit data-sharing attributes for task.
  2135. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2136. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2137. !Stack->isLoopControlVariable(FD).first) {
  2138. // Check if there is a captured expression for the current field in the
  2139. // region. Do not mark it as firstprivate unless there is no captured
  2140. // expression.
  2141. // TODO: try to make it firstprivate.
  2142. if (DVar.CKind != OMPC_unknown)
  2143. ImplicitFirstprivate.push_back(E);
  2144. }
  2145. return;
  2146. }
  2147. if (isOpenMPTargetExecutionDirective(DKind)) {
  2148. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2149. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2150. /*NoDiagnose=*/true))
  2151. return;
  2152. const auto *VD = cast<ValueDecl>(
  2153. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2154. if (!Stack->checkMappableExprComponentListsForDecl(
  2155. VD, /*CurrentRegionOnly=*/true,
  2156. [&CurComponents](
  2157. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2158. StackComponents,
  2159. OpenMPClauseKind) {
  2160. auto CCI = CurComponents.rbegin();
  2161. auto CCE = CurComponents.rend();
  2162. for (const auto &SC : llvm::reverse(StackComponents)) {
  2163. // Do both expressions have the same kind?
  2164. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2165. SC.getAssociatedExpression()->getStmtClass())
  2166. if (!(isa<OMPArraySectionExpr>(
  2167. SC.getAssociatedExpression()) &&
  2168. isa<ArraySubscriptExpr>(
  2169. CCI->getAssociatedExpression())))
  2170. return false;
  2171. const Decl *CCD = CCI->getAssociatedDeclaration();
  2172. const Decl *SCD = SC.getAssociatedDeclaration();
  2173. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2174. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2175. if (SCD != CCD)
  2176. return false;
  2177. std::advance(CCI, 1);
  2178. if (CCI == CCE)
  2179. break;
  2180. }
  2181. return true;
  2182. })) {
  2183. Visit(E->getBase());
  2184. }
  2185. } else {
  2186. Visit(E->getBase());
  2187. }
  2188. }
  2189. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2190. for (OMPClause *C : S->clauses()) {
  2191. // Skip analysis of arguments of implicitly defined firstprivate clause
  2192. // for task|target directives.
  2193. // Skip analysis of arguments of implicitly defined map clause for target
  2194. // directives.
  2195. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2196. C->isImplicit())) {
  2197. for (Stmt *CC : C->children()) {
  2198. if (CC)
  2199. Visit(CC);
  2200. }
  2201. }
  2202. }
  2203. // Check implicitly captured variables.
  2204. VisitSubCaptures(S);
  2205. }
  2206. void VisitStmt(Stmt *S) {
  2207. for (Stmt *C : S->children()) {
  2208. if (C) {
  2209. if (auto *OED = dyn_cast<OMPExecutableDirective>(C)) {
  2210. // Check implicitly captured variables in the task-based directives to
  2211. // check if they must be firstprivatized.
  2212. VisitSubCaptures(OED);
  2213. } else {
  2214. Visit(C);
  2215. }
  2216. }
  2217. }
  2218. }
  2219. bool isErrorFound() const { return ErrorFound; }
  2220. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2221. return ImplicitFirstprivate;
  2222. }
  2223. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2224. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2225. return VarsWithInheritedDSA;
  2226. }
  2227. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2228. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  2229. };
  2230. } // namespace
  2231. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2232. switch (DKind) {
  2233. case OMPD_parallel:
  2234. case OMPD_parallel_for:
  2235. case OMPD_parallel_for_simd:
  2236. case OMPD_parallel_sections:
  2237. case OMPD_teams:
  2238. case OMPD_teams_distribute:
  2239. case OMPD_teams_distribute_simd: {
  2240. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2241. QualType KmpInt32PtrTy =
  2242. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2243. Sema::CapturedParamNameType Params[] = {
  2244. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2245. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2246. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2247. };
  2248. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2249. Params);
  2250. break;
  2251. }
  2252. case OMPD_target_teams:
  2253. case OMPD_target_parallel:
  2254. case OMPD_target_parallel_for:
  2255. case OMPD_target_parallel_for_simd:
  2256. case OMPD_target_teams_distribute:
  2257. case OMPD_target_teams_distribute_simd: {
  2258. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2259. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2260. QualType KmpInt32PtrTy =
  2261. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2262. QualType Args[] = {VoidPtrTy};
  2263. FunctionProtoType::ExtProtoInfo EPI;
  2264. EPI.Variadic = true;
  2265. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2266. Sema::CapturedParamNameType Params[] = {
  2267. std::make_pair(".global_tid.", KmpInt32Ty),
  2268. std::make_pair(".part_id.", KmpInt32PtrTy),
  2269. std::make_pair(".privates.", VoidPtrTy),
  2270. std::make_pair(
  2271. ".copy_fn.",
  2272. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2273. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2274. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2275. };
  2276. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2277. Params);
  2278. // Mark this captured region as inlined, because we don't use outlined
  2279. // function directly.
  2280. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2281. AlwaysInlineAttr::CreateImplicit(
  2282. Context, AlwaysInlineAttr::Keyword_forceinline));
  2283. Sema::CapturedParamNameType ParamsTarget[] = {
  2284. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2285. };
  2286. // Start a captured region for 'target' with no implicit parameters.
  2287. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2288. ParamsTarget);
  2289. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2290. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2291. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2292. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2293. };
  2294. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2295. // the same implicit parameters.
  2296. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2297. ParamsTeamsOrParallel);
  2298. break;
  2299. }
  2300. case OMPD_target:
  2301. case OMPD_target_simd: {
  2302. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2303. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2304. QualType KmpInt32PtrTy =
  2305. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2306. QualType Args[] = {VoidPtrTy};
  2307. FunctionProtoType::ExtProtoInfo EPI;
  2308. EPI.Variadic = true;
  2309. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2310. Sema::CapturedParamNameType Params[] = {
  2311. std::make_pair(".global_tid.", KmpInt32Ty),
  2312. std::make_pair(".part_id.", KmpInt32PtrTy),
  2313. std::make_pair(".privates.", VoidPtrTy),
  2314. std::make_pair(
  2315. ".copy_fn.",
  2316. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2317. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2318. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2319. };
  2320. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2321. Params);
  2322. // Mark this captured region as inlined, because we don't use outlined
  2323. // function directly.
  2324. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2325. AlwaysInlineAttr::CreateImplicit(
  2326. Context, AlwaysInlineAttr::Keyword_forceinline));
  2327. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2328. std::make_pair(StringRef(), QualType()));
  2329. break;
  2330. }
  2331. case OMPD_simd:
  2332. case OMPD_for:
  2333. case OMPD_for_simd:
  2334. case OMPD_sections:
  2335. case OMPD_section:
  2336. case OMPD_single:
  2337. case OMPD_master:
  2338. case OMPD_critical:
  2339. case OMPD_taskgroup:
  2340. case OMPD_distribute:
  2341. case OMPD_distribute_simd:
  2342. case OMPD_ordered:
  2343. case OMPD_atomic:
  2344. case OMPD_target_data: {
  2345. Sema::CapturedParamNameType Params[] = {
  2346. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2347. };
  2348. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2349. Params);
  2350. break;
  2351. }
  2352. case OMPD_task: {
  2353. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2354. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2355. QualType KmpInt32PtrTy =
  2356. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2357. QualType Args[] = {VoidPtrTy};
  2358. FunctionProtoType::ExtProtoInfo EPI;
  2359. EPI.Variadic = true;
  2360. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2361. Sema::CapturedParamNameType Params[] = {
  2362. std::make_pair(".global_tid.", KmpInt32Ty),
  2363. std::make_pair(".part_id.", KmpInt32PtrTy),
  2364. std::make_pair(".privates.", VoidPtrTy),
  2365. std::make_pair(
  2366. ".copy_fn.",
  2367. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2368. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2369. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2370. };
  2371. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2372. Params);
  2373. // Mark this captured region as inlined, because we don't use outlined
  2374. // function directly.
  2375. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2376. AlwaysInlineAttr::CreateImplicit(
  2377. Context, AlwaysInlineAttr::Keyword_forceinline));
  2378. break;
  2379. }
  2380. case OMPD_taskloop:
  2381. case OMPD_taskloop_simd: {
  2382. QualType KmpInt32Ty =
  2383. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2384. .withConst();
  2385. QualType KmpUInt64Ty =
  2386. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2387. .withConst();
  2388. QualType KmpInt64Ty =
  2389. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2390. .withConst();
  2391. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2392. QualType KmpInt32PtrTy =
  2393. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2394. QualType Args[] = {VoidPtrTy};
  2395. FunctionProtoType::ExtProtoInfo EPI;
  2396. EPI.Variadic = true;
  2397. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2398. Sema::CapturedParamNameType Params[] = {
  2399. std::make_pair(".global_tid.", KmpInt32Ty),
  2400. std::make_pair(".part_id.", KmpInt32PtrTy),
  2401. std::make_pair(".privates.", VoidPtrTy),
  2402. std::make_pair(
  2403. ".copy_fn.",
  2404. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2405. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2406. std::make_pair(".lb.", KmpUInt64Ty),
  2407. std::make_pair(".ub.", KmpUInt64Ty),
  2408. std::make_pair(".st.", KmpInt64Ty),
  2409. std::make_pair(".liter.", KmpInt32Ty),
  2410. std::make_pair(".reductions.", VoidPtrTy),
  2411. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2412. };
  2413. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2414. Params);
  2415. // Mark this captured region as inlined, because we don't use outlined
  2416. // function directly.
  2417. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2418. AlwaysInlineAttr::CreateImplicit(
  2419. Context, AlwaysInlineAttr::Keyword_forceinline));
  2420. break;
  2421. }
  2422. case OMPD_distribute_parallel_for_simd:
  2423. case OMPD_distribute_parallel_for: {
  2424. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2425. QualType KmpInt32PtrTy =
  2426. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2427. Sema::CapturedParamNameType Params[] = {
  2428. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2429. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2430. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2431. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2432. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2433. };
  2434. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2435. Params);
  2436. break;
  2437. }
  2438. case OMPD_target_teams_distribute_parallel_for:
  2439. case OMPD_target_teams_distribute_parallel_for_simd: {
  2440. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2441. QualType KmpInt32PtrTy =
  2442. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2443. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2444. QualType Args[] = {VoidPtrTy};
  2445. FunctionProtoType::ExtProtoInfo EPI;
  2446. EPI.Variadic = true;
  2447. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2448. Sema::CapturedParamNameType Params[] = {
  2449. std::make_pair(".global_tid.", KmpInt32Ty),
  2450. std::make_pair(".part_id.", KmpInt32PtrTy),
  2451. std::make_pair(".privates.", VoidPtrTy),
  2452. std::make_pair(
  2453. ".copy_fn.",
  2454. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2455. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2456. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2457. };
  2458. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2459. Params);
  2460. // Mark this captured region as inlined, because we don't use outlined
  2461. // function directly.
  2462. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2463. AlwaysInlineAttr::CreateImplicit(
  2464. Context, AlwaysInlineAttr::Keyword_forceinline));
  2465. Sema::CapturedParamNameType ParamsTarget[] = {
  2466. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2467. };
  2468. // Start a captured region for 'target' with no implicit parameters.
  2469. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2470. ParamsTarget);
  2471. Sema::CapturedParamNameType ParamsTeams[] = {
  2472. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2473. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2474. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2475. };
  2476. // Start a captured region for 'target' with no implicit parameters.
  2477. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2478. ParamsTeams);
  2479. Sema::CapturedParamNameType ParamsParallel[] = {
  2480. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2481. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2482. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2483. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2484. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2485. };
  2486. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2487. // the same implicit parameters.
  2488. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2489. ParamsParallel);
  2490. break;
  2491. }
  2492. case OMPD_teams_distribute_parallel_for:
  2493. case OMPD_teams_distribute_parallel_for_simd: {
  2494. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2495. QualType KmpInt32PtrTy =
  2496. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2497. Sema::CapturedParamNameType ParamsTeams[] = {
  2498. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2499. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2500. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2501. };
  2502. // Start a captured region for 'target' with no implicit parameters.
  2503. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2504. ParamsTeams);
  2505. Sema::CapturedParamNameType ParamsParallel[] = {
  2506. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2507. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2508. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2509. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2510. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2511. };
  2512. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2513. // the same implicit parameters.
  2514. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2515. ParamsParallel);
  2516. break;
  2517. }
  2518. case OMPD_target_update:
  2519. case OMPD_target_enter_data:
  2520. case OMPD_target_exit_data: {
  2521. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2522. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2523. QualType KmpInt32PtrTy =
  2524. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2525. QualType Args[] = {VoidPtrTy};
  2526. FunctionProtoType::ExtProtoInfo EPI;
  2527. EPI.Variadic = true;
  2528. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2529. Sema::CapturedParamNameType Params[] = {
  2530. std::make_pair(".global_tid.", KmpInt32Ty),
  2531. std::make_pair(".part_id.", KmpInt32PtrTy),
  2532. std::make_pair(".privates.", VoidPtrTy),
  2533. std::make_pair(
  2534. ".copy_fn.",
  2535. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2536. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2537. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2538. };
  2539. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2540. Params);
  2541. // Mark this captured region as inlined, because we don't use outlined
  2542. // function directly.
  2543. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2544. AlwaysInlineAttr::CreateImplicit(
  2545. Context, AlwaysInlineAttr::Keyword_forceinline));
  2546. break;
  2547. }
  2548. case OMPD_threadprivate:
  2549. case OMPD_taskyield:
  2550. case OMPD_barrier:
  2551. case OMPD_taskwait:
  2552. case OMPD_cancellation_point:
  2553. case OMPD_cancel:
  2554. case OMPD_flush:
  2555. case OMPD_declare_reduction:
  2556. case OMPD_declare_simd:
  2557. case OMPD_declare_target:
  2558. case OMPD_end_declare_target:
  2559. case OMPD_requires:
  2560. llvm_unreachable("OpenMP Directive is not allowed");
  2561. case OMPD_unknown:
  2562. llvm_unreachable("Unknown OpenMP directive");
  2563. }
  2564. }
  2565. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2566. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2567. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2568. return CaptureRegions.size();
  2569. }
  2570. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2571. Expr *CaptureExpr, bool WithInit,
  2572. bool AsExpression) {
  2573. assert(CaptureExpr);
  2574. ASTContext &C = S.getASTContext();
  2575. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2576. QualType Ty = Init->getType();
  2577. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2578. if (S.getLangOpts().CPlusPlus) {
  2579. Ty = C.getLValueReferenceType(Ty);
  2580. } else {
  2581. Ty = C.getPointerType(Ty);
  2582. ExprResult Res =
  2583. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2584. if (!Res.isUsable())
  2585. return nullptr;
  2586. Init = Res.get();
  2587. }
  2588. WithInit = true;
  2589. }
  2590. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2591. CaptureExpr->getBeginLoc());
  2592. if (!WithInit)
  2593. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2594. S.CurContext->addHiddenDecl(CED);
  2595. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2596. return CED;
  2597. }
  2598. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2599. bool WithInit) {
  2600. OMPCapturedExprDecl *CD;
  2601. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2602. CD = cast<OMPCapturedExprDecl>(VD);
  2603. else
  2604. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2605. /*AsExpression=*/false);
  2606. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2607. CaptureExpr->getExprLoc());
  2608. }
  2609. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2610. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2611. if (!Ref) {
  2612. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2613. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2614. /*WithInit=*/true, /*AsExpression=*/true);
  2615. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2616. CaptureExpr->getExprLoc());
  2617. }
  2618. ExprResult Res = Ref;
  2619. if (!S.getLangOpts().CPlusPlus &&
  2620. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2621. Ref->getType()->isPointerType()) {
  2622. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2623. if (!Res.isUsable())
  2624. return ExprError();
  2625. }
  2626. return S.DefaultLvalueConversion(Res.get());
  2627. }
  2628. namespace {
  2629. // OpenMP directives parsed in this section are represented as a
  2630. // CapturedStatement with an associated statement. If a syntax error
  2631. // is detected during the parsing of the associated statement, the
  2632. // compiler must abort processing and close the CapturedStatement.
  2633. //
  2634. // Combined directives such as 'target parallel' have more than one
  2635. // nested CapturedStatements. This RAII ensures that we unwind out
  2636. // of all the nested CapturedStatements when an error is found.
  2637. class CaptureRegionUnwinderRAII {
  2638. private:
  2639. Sema &S;
  2640. bool &ErrorFound;
  2641. OpenMPDirectiveKind DKind = OMPD_unknown;
  2642. public:
  2643. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2644. OpenMPDirectiveKind DKind)
  2645. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2646. ~CaptureRegionUnwinderRAII() {
  2647. if (ErrorFound) {
  2648. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2649. while (--ThisCaptureLevel >= 0)
  2650. S.ActOnCapturedRegionError();
  2651. }
  2652. }
  2653. };
  2654. } // namespace
  2655. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2656. ArrayRef<OMPClause *> Clauses) {
  2657. bool ErrorFound = false;
  2658. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2659. *this, ErrorFound, DSAStack->getCurrentDirective());
  2660. if (!S.isUsable()) {
  2661. ErrorFound = true;
  2662. return StmtError();
  2663. }
  2664. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2665. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2666. OMPOrderedClause *OC = nullptr;
  2667. OMPScheduleClause *SC = nullptr;
  2668. SmallVector<const OMPLinearClause *, 4> LCs;
  2669. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  2670. // This is required for proper codegen.
  2671. for (OMPClause *Clause : Clauses) {
  2672. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2673. Clause->getClauseKind() == OMPC_in_reduction) {
  2674. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2675. // with the corresponding in_reduction items.
  2676. auto *IRC = cast<OMPInReductionClause>(Clause);
  2677. for (Expr *E : IRC->taskgroup_descriptors())
  2678. if (E)
  2679. MarkDeclarationsReferencedInExpr(E);
  2680. }
  2681. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2682. Clause->getClauseKind() == OMPC_copyprivate ||
  2683. (getLangOpts().OpenMPUseTLS &&
  2684. getASTContext().getTargetInfo().isTLSSupported() &&
  2685. Clause->getClauseKind() == OMPC_copyin)) {
  2686. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2687. // Mark all variables in private list clauses as used in inner region.
  2688. for (Stmt *VarRef : Clause->children()) {
  2689. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2690. MarkDeclarationsReferencedInExpr(E);
  2691. }
  2692. }
  2693. DSAStack->setForceVarCapturing(/*V=*/false);
  2694. } else if (CaptureRegions.size() > 1 ||
  2695. CaptureRegions.back() != OMPD_unknown) {
  2696. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2697. PICs.push_back(C);
  2698. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2699. if (Expr *E = C->getPostUpdateExpr())
  2700. MarkDeclarationsReferencedInExpr(E);
  2701. }
  2702. }
  2703. if (Clause->getClauseKind() == OMPC_schedule)
  2704. SC = cast<OMPScheduleClause>(Clause);
  2705. else if (Clause->getClauseKind() == OMPC_ordered)
  2706. OC = cast<OMPOrderedClause>(Clause);
  2707. else if (Clause->getClauseKind() == OMPC_linear)
  2708. LCs.push_back(cast<OMPLinearClause>(Clause));
  2709. }
  2710. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2711. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2712. // specified.
  2713. if (SC &&
  2714. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2715. SC->getSecondScheduleModifier() ==
  2716. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2717. OC) {
  2718. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2719. ? SC->getFirstScheduleModifierLoc()
  2720. : SC->getSecondScheduleModifierLoc(),
  2721. diag::err_omp_schedule_nonmonotonic_ordered)
  2722. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2723. ErrorFound = true;
  2724. }
  2725. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2726. for (const OMPLinearClause *C : LCs) {
  2727. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  2728. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2729. }
  2730. ErrorFound = true;
  2731. }
  2732. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2733. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2734. OC->getNumForLoops()) {
  2735. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  2736. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2737. ErrorFound = true;
  2738. }
  2739. if (ErrorFound) {
  2740. return StmtError();
  2741. }
  2742. StmtResult SR = S;
  2743. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2744. // Mark all variables in private list clauses as used in inner region.
  2745. // Required for proper codegen of combined directives.
  2746. // TODO: add processing for other clauses.
  2747. if (ThisCaptureRegion != OMPD_unknown) {
  2748. for (const clang::OMPClauseWithPreInit *C : PICs) {
  2749. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2750. // Find the particular capture region for the clause if the
  2751. // directive is a combined one with multiple capture regions.
  2752. // If the directive is not a combined one, the capture region
  2753. // associated with the clause is OMPD_unknown and is generated
  2754. // only once.
  2755. if (CaptureRegion == ThisCaptureRegion ||
  2756. CaptureRegion == OMPD_unknown) {
  2757. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2758. for (Decl *D : DS->decls())
  2759. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2760. }
  2761. }
  2762. }
  2763. }
  2764. SR = ActOnCapturedRegionEnd(SR.get());
  2765. }
  2766. return SR;
  2767. }
  2768. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2769. OpenMPDirectiveKind CancelRegion,
  2770. SourceLocation StartLoc) {
  2771. // CancelRegion is only needed for cancel and cancellation_point.
  2772. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2773. return false;
  2774. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2775. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2776. return false;
  2777. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2778. << getOpenMPDirectiveName(CancelRegion);
  2779. return true;
  2780. }
  2781. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  2782. OpenMPDirectiveKind CurrentRegion,
  2783. const DeclarationNameInfo &CurrentName,
  2784. OpenMPDirectiveKind CancelRegion,
  2785. SourceLocation StartLoc) {
  2786. if (Stack->getCurScope()) {
  2787. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  2788. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  2789. bool NestingProhibited = false;
  2790. bool CloseNesting = true;
  2791. bool OrphanSeen = false;
  2792. enum {
  2793. NoRecommend,
  2794. ShouldBeInParallelRegion,
  2795. ShouldBeInOrderedRegion,
  2796. ShouldBeInTargetRegion,
  2797. ShouldBeInTeamsRegion
  2798. } Recommend = NoRecommend;
  2799. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2800. // OpenMP [2.16, Nesting of Regions]
  2801. // OpenMP constructs may not be nested inside a simd region.
  2802. // OpenMP [2.8.1,simd Construct, Restrictions]
  2803. // An ordered construct with the simd clause is the only OpenMP
  2804. // construct that can appear in the simd region.
  2805. // Allowing a SIMD construct nested in another SIMD construct is an
  2806. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2807. // message.
  2808. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2809. ? diag::err_omp_prohibited_region_simd
  2810. : diag::warn_omp_nesting_simd);
  2811. return CurrentRegion != OMPD_simd;
  2812. }
  2813. if (ParentRegion == OMPD_atomic) {
  2814. // OpenMP [2.16, Nesting of Regions]
  2815. // OpenMP constructs may not be nested inside an atomic region.
  2816. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2817. return true;
  2818. }
  2819. if (CurrentRegion == OMPD_section) {
  2820. // OpenMP [2.7.2, sections Construct, Restrictions]
  2821. // Orphaned section directives are prohibited. That is, the section
  2822. // directives must appear within the sections construct and must not be
  2823. // encountered elsewhere in the sections region.
  2824. if (ParentRegion != OMPD_sections &&
  2825. ParentRegion != OMPD_parallel_sections) {
  2826. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2827. << (ParentRegion != OMPD_unknown)
  2828. << getOpenMPDirectiveName(ParentRegion);
  2829. return true;
  2830. }
  2831. return false;
  2832. }
  2833. // Allow some constructs (except teams) to be orphaned (they could be
  2834. // used in functions, called from OpenMP regions with the required
  2835. // preconditions).
  2836. if (ParentRegion == OMPD_unknown &&
  2837. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2838. return false;
  2839. if (CurrentRegion == OMPD_cancellation_point ||
  2840. CurrentRegion == OMPD_cancel) {
  2841. // OpenMP [2.16, Nesting of Regions]
  2842. // A cancellation point construct for which construct-type-clause is
  2843. // taskgroup must be nested inside a task construct. A cancellation
  2844. // point construct for which construct-type-clause is not taskgroup must
  2845. // be closely nested inside an OpenMP construct that matches the type
  2846. // specified in construct-type-clause.
  2847. // A cancel construct for which construct-type-clause is taskgroup must be
  2848. // nested inside a task construct. A cancel construct for which
  2849. // construct-type-clause is not taskgroup must be closely nested inside an
  2850. // OpenMP construct that matches the type specified in
  2851. // construct-type-clause.
  2852. NestingProhibited =
  2853. !((CancelRegion == OMPD_parallel &&
  2854. (ParentRegion == OMPD_parallel ||
  2855. ParentRegion == OMPD_target_parallel)) ||
  2856. (CancelRegion == OMPD_for &&
  2857. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2858. ParentRegion == OMPD_target_parallel_for ||
  2859. ParentRegion == OMPD_distribute_parallel_for ||
  2860. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2861. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2862. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2863. (CancelRegion == OMPD_sections &&
  2864. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2865. ParentRegion == OMPD_parallel_sections)));
  2866. } else if (CurrentRegion == OMPD_master) {
  2867. // OpenMP [2.16, Nesting of Regions]
  2868. // A master region may not be closely nested inside a worksharing,
  2869. // atomic, or explicit task region.
  2870. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2871. isOpenMPTaskingDirective(ParentRegion);
  2872. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2873. // OpenMP [2.16, Nesting of Regions]
  2874. // A critical region may not be nested (closely or otherwise) inside a
  2875. // critical region with the same name. Note that this restriction is not
  2876. // sufficient to prevent deadlock.
  2877. SourceLocation PreviousCriticalLoc;
  2878. bool DeadLock = Stack->hasDirective(
  2879. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2880. const DeclarationNameInfo &DNI,
  2881. SourceLocation Loc) {
  2882. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2883. PreviousCriticalLoc = Loc;
  2884. return true;
  2885. }
  2886. return false;
  2887. },
  2888. false /* skip top directive */);
  2889. if (DeadLock) {
  2890. SemaRef.Diag(StartLoc,
  2891. diag::err_omp_prohibited_region_critical_same_name)
  2892. << CurrentName.getName();
  2893. if (PreviousCriticalLoc.isValid())
  2894. SemaRef.Diag(PreviousCriticalLoc,
  2895. diag::note_omp_previous_critical_region);
  2896. return true;
  2897. }
  2898. } else if (CurrentRegion == OMPD_barrier) {
  2899. // OpenMP [2.16, Nesting of Regions]
  2900. // A barrier region may not be closely nested inside a worksharing,
  2901. // explicit task, critical, ordered, atomic, or master region.
  2902. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2903. isOpenMPTaskingDirective(ParentRegion) ||
  2904. ParentRegion == OMPD_master ||
  2905. ParentRegion == OMPD_critical ||
  2906. ParentRegion == OMPD_ordered;
  2907. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2908. !isOpenMPParallelDirective(CurrentRegion) &&
  2909. !isOpenMPTeamsDirective(CurrentRegion)) {
  2910. // OpenMP [2.16, Nesting of Regions]
  2911. // A worksharing region may not be closely nested inside a worksharing,
  2912. // explicit task, critical, ordered, atomic, or master region.
  2913. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2914. isOpenMPTaskingDirective(ParentRegion) ||
  2915. ParentRegion == OMPD_master ||
  2916. ParentRegion == OMPD_critical ||
  2917. ParentRegion == OMPD_ordered;
  2918. Recommend = ShouldBeInParallelRegion;
  2919. } else if (CurrentRegion == OMPD_ordered) {
  2920. // OpenMP [2.16, Nesting of Regions]
  2921. // An ordered region may not be closely nested inside a critical,
  2922. // atomic, or explicit task region.
  2923. // An ordered region must be closely nested inside a loop region (or
  2924. // parallel loop region) with an ordered clause.
  2925. // OpenMP [2.8.1,simd Construct, Restrictions]
  2926. // An ordered construct with the simd clause is the only OpenMP construct
  2927. // that can appear in the simd region.
  2928. NestingProhibited = ParentRegion == OMPD_critical ||
  2929. isOpenMPTaskingDirective(ParentRegion) ||
  2930. !(isOpenMPSimdDirective(ParentRegion) ||
  2931. Stack->isParentOrderedRegion());
  2932. Recommend = ShouldBeInOrderedRegion;
  2933. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2934. // OpenMP [2.16, Nesting of Regions]
  2935. // If specified, a teams construct must be contained within a target
  2936. // construct.
  2937. NestingProhibited = ParentRegion != OMPD_target;
  2938. OrphanSeen = ParentRegion == OMPD_unknown;
  2939. Recommend = ShouldBeInTargetRegion;
  2940. }
  2941. if (!NestingProhibited &&
  2942. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2943. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2944. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2945. // OpenMP [2.16, Nesting of Regions]
  2946. // distribute, parallel, parallel sections, parallel workshare, and the
  2947. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2948. // constructs that can be closely nested in the teams region.
  2949. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2950. !isOpenMPDistributeDirective(CurrentRegion);
  2951. Recommend = ShouldBeInParallelRegion;
  2952. }
  2953. if (!NestingProhibited &&
  2954. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2955. // OpenMP 4.5 [2.17 Nesting of Regions]
  2956. // The region associated with the distribute construct must be strictly
  2957. // nested inside a teams region
  2958. NestingProhibited =
  2959. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2960. Recommend = ShouldBeInTeamsRegion;
  2961. }
  2962. if (!NestingProhibited &&
  2963. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2964. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2965. // OpenMP 4.5 [2.17 Nesting of Regions]
  2966. // If a target, target update, target data, target enter data, or
  2967. // target exit data construct is encountered during execution of a
  2968. // target region, the behavior is unspecified.
  2969. NestingProhibited = Stack->hasDirective(
  2970. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2971. SourceLocation) {
  2972. if (isOpenMPTargetExecutionDirective(K)) {
  2973. OffendingRegion = K;
  2974. return true;
  2975. }
  2976. return false;
  2977. },
  2978. false /* don't skip top directive */);
  2979. CloseNesting = false;
  2980. }
  2981. if (NestingProhibited) {
  2982. if (OrphanSeen) {
  2983. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2984. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2985. } else {
  2986. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2987. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2988. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2989. }
  2990. return true;
  2991. }
  2992. }
  2993. return false;
  2994. }
  2995. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2996. ArrayRef<OMPClause *> Clauses,
  2997. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2998. bool ErrorFound = false;
  2999. unsigned NamedModifiersNumber = 0;
  3000. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3001. OMPD_unknown + 1);
  3002. SmallVector<SourceLocation, 4> NameModifierLoc;
  3003. for (const OMPClause *C : Clauses) {
  3004. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3005. // At most one if clause without a directive-name-modifier can appear on
  3006. // the directive.
  3007. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3008. if (FoundNameModifiers[CurNM]) {
  3009. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3010. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3011. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3012. ErrorFound = true;
  3013. } else if (CurNM != OMPD_unknown) {
  3014. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3015. ++NamedModifiersNumber;
  3016. }
  3017. FoundNameModifiers[CurNM] = IC;
  3018. if (CurNM == OMPD_unknown)
  3019. continue;
  3020. // Check if the specified name modifier is allowed for the current
  3021. // directive.
  3022. // At most one if clause with the particular directive-name-modifier can
  3023. // appear on the directive.
  3024. bool MatchFound = false;
  3025. for (auto NM : AllowedNameModifiers) {
  3026. if (CurNM == NM) {
  3027. MatchFound = true;
  3028. break;
  3029. }
  3030. }
  3031. if (!MatchFound) {
  3032. S.Diag(IC->getNameModifierLoc(),
  3033. diag::err_omp_wrong_if_directive_name_modifier)
  3034. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3035. ErrorFound = true;
  3036. }
  3037. }
  3038. }
  3039. // If any if clause on the directive includes a directive-name-modifier then
  3040. // all if clauses on the directive must include a directive-name-modifier.
  3041. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3042. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3043. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3044. diag::err_omp_no_more_if_clause);
  3045. } else {
  3046. std::string Values;
  3047. std::string Sep(", ");
  3048. unsigned AllowedCnt = 0;
  3049. unsigned TotalAllowedNum =
  3050. AllowedNameModifiers.size() - NamedModifiersNumber;
  3051. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3052. ++Cnt) {
  3053. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3054. if (!FoundNameModifiers[NM]) {
  3055. Values += "'";
  3056. Values += getOpenMPDirectiveName(NM);
  3057. Values += "'";
  3058. if (AllowedCnt + 2 == TotalAllowedNum)
  3059. Values += " or ";
  3060. else if (AllowedCnt + 1 != TotalAllowedNum)
  3061. Values += Sep;
  3062. ++AllowedCnt;
  3063. }
  3064. }
  3065. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3066. diag::err_omp_unnamed_if_clause)
  3067. << (TotalAllowedNum > 1) << Values;
  3068. }
  3069. for (SourceLocation Loc : NameModifierLoc) {
  3070. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3071. }
  3072. ErrorFound = true;
  3073. }
  3074. return ErrorFound;
  3075. }
  3076. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3077. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3078. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3079. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3080. StmtResult Res = StmtError();
  3081. // First check CancelRegion which is then used in checkNestingOfRegions.
  3082. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3083. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3084. StartLoc))
  3085. return StmtError();
  3086. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3087. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3088. bool ErrorFound = false;
  3089. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3090. if (AStmt && !CurContext->isDependentContext()) {
  3091. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3092. // Check default data sharing attributes for referenced variables.
  3093. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3094. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3095. Stmt *S = AStmt;
  3096. while (--ThisCaptureLevel >= 0)
  3097. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3098. DSAChecker.Visit(S);
  3099. if (DSAChecker.isErrorFound())
  3100. return StmtError();
  3101. // Generate list of implicitly defined firstprivate variables.
  3102. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3103. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3104. DSAChecker.getImplicitFirstprivate().begin(),
  3105. DSAChecker.getImplicitFirstprivate().end());
  3106. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3107. DSAChecker.getImplicitMap().end());
  3108. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3109. for (OMPClause *C : Clauses) {
  3110. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3111. for (Expr *E : IRC->taskgroup_descriptors())
  3112. if (E)
  3113. ImplicitFirstprivates.emplace_back(E);
  3114. }
  3115. }
  3116. if (!ImplicitFirstprivates.empty()) {
  3117. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3118. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3119. SourceLocation())) {
  3120. ClausesWithImplicit.push_back(Implicit);
  3121. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3122. ImplicitFirstprivates.size();
  3123. } else {
  3124. ErrorFound = true;
  3125. }
  3126. }
  3127. if (!ImplicitMaps.empty()) {
  3128. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3129. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  3130. SourceLocation(), SourceLocation(), ImplicitMaps,
  3131. SourceLocation(), SourceLocation(), SourceLocation())) {
  3132. ClausesWithImplicit.emplace_back(Implicit);
  3133. ErrorFound |=
  3134. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3135. } else {
  3136. ErrorFound = true;
  3137. }
  3138. }
  3139. }
  3140. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3141. switch (Kind) {
  3142. case OMPD_parallel:
  3143. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3144. EndLoc);
  3145. AllowedNameModifiers.push_back(OMPD_parallel);
  3146. break;
  3147. case OMPD_simd:
  3148. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3149. VarsWithInheritedDSA);
  3150. break;
  3151. case OMPD_for:
  3152. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3153. VarsWithInheritedDSA);
  3154. break;
  3155. case OMPD_for_simd:
  3156. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3157. EndLoc, VarsWithInheritedDSA);
  3158. break;
  3159. case OMPD_sections:
  3160. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3161. EndLoc);
  3162. break;
  3163. case OMPD_section:
  3164. assert(ClausesWithImplicit.empty() &&
  3165. "No clauses are allowed for 'omp section' directive");
  3166. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3167. break;
  3168. case OMPD_single:
  3169. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3170. EndLoc);
  3171. break;
  3172. case OMPD_master:
  3173. assert(ClausesWithImplicit.empty() &&
  3174. "No clauses are allowed for 'omp master' directive");
  3175. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3176. break;
  3177. case OMPD_critical:
  3178. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3179. StartLoc, EndLoc);
  3180. break;
  3181. case OMPD_parallel_for:
  3182. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3183. EndLoc, VarsWithInheritedDSA);
  3184. AllowedNameModifiers.push_back(OMPD_parallel);
  3185. break;
  3186. case OMPD_parallel_for_simd:
  3187. Res = ActOnOpenMPParallelForSimdDirective(
  3188. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3189. AllowedNameModifiers.push_back(OMPD_parallel);
  3190. break;
  3191. case OMPD_parallel_sections:
  3192. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3193. StartLoc, EndLoc);
  3194. AllowedNameModifiers.push_back(OMPD_parallel);
  3195. break;
  3196. case OMPD_task:
  3197. Res =
  3198. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3199. AllowedNameModifiers.push_back(OMPD_task);
  3200. break;
  3201. case OMPD_taskyield:
  3202. assert(ClausesWithImplicit.empty() &&
  3203. "No clauses are allowed for 'omp taskyield' directive");
  3204. assert(AStmt == nullptr &&
  3205. "No associated statement allowed for 'omp taskyield' directive");
  3206. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3207. break;
  3208. case OMPD_barrier:
  3209. assert(ClausesWithImplicit.empty() &&
  3210. "No clauses are allowed for 'omp barrier' directive");
  3211. assert(AStmt == nullptr &&
  3212. "No associated statement allowed for 'omp barrier' directive");
  3213. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3214. break;
  3215. case OMPD_taskwait:
  3216. assert(ClausesWithImplicit.empty() &&
  3217. "No clauses are allowed for 'omp taskwait' directive");
  3218. assert(AStmt == nullptr &&
  3219. "No associated statement allowed for 'omp taskwait' directive");
  3220. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3221. break;
  3222. case OMPD_taskgroup:
  3223. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3224. EndLoc);
  3225. break;
  3226. case OMPD_flush:
  3227. assert(AStmt == nullptr &&
  3228. "No associated statement allowed for 'omp flush' directive");
  3229. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3230. break;
  3231. case OMPD_ordered:
  3232. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3233. EndLoc);
  3234. break;
  3235. case OMPD_atomic:
  3236. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3237. EndLoc);
  3238. break;
  3239. case OMPD_teams:
  3240. Res =
  3241. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3242. break;
  3243. case OMPD_target:
  3244. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3245. EndLoc);
  3246. AllowedNameModifiers.push_back(OMPD_target);
  3247. break;
  3248. case OMPD_target_parallel:
  3249. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3250. StartLoc, EndLoc);
  3251. AllowedNameModifiers.push_back(OMPD_target);
  3252. AllowedNameModifiers.push_back(OMPD_parallel);
  3253. break;
  3254. case OMPD_target_parallel_for:
  3255. Res = ActOnOpenMPTargetParallelForDirective(
  3256. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3257. AllowedNameModifiers.push_back(OMPD_target);
  3258. AllowedNameModifiers.push_back(OMPD_parallel);
  3259. break;
  3260. case OMPD_cancellation_point:
  3261. assert(ClausesWithImplicit.empty() &&
  3262. "No clauses are allowed for 'omp cancellation point' directive");
  3263. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3264. "cancellation point' directive");
  3265. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3266. break;
  3267. case OMPD_cancel:
  3268. assert(AStmt == nullptr &&
  3269. "No associated statement allowed for 'omp cancel' directive");
  3270. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3271. CancelRegion);
  3272. AllowedNameModifiers.push_back(OMPD_cancel);
  3273. break;
  3274. case OMPD_target_data:
  3275. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3276. EndLoc);
  3277. AllowedNameModifiers.push_back(OMPD_target_data);
  3278. break;
  3279. case OMPD_target_enter_data:
  3280. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3281. EndLoc, AStmt);
  3282. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3283. break;
  3284. case OMPD_target_exit_data:
  3285. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3286. EndLoc, AStmt);
  3287. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3288. break;
  3289. case OMPD_taskloop:
  3290. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3291. EndLoc, VarsWithInheritedDSA);
  3292. AllowedNameModifiers.push_back(OMPD_taskloop);
  3293. break;
  3294. case OMPD_taskloop_simd:
  3295. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3296. EndLoc, VarsWithInheritedDSA);
  3297. AllowedNameModifiers.push_back(OMPD_taskloop);
  3298. break;
  3299. case OMPD_distribute:
  3300. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3301. EndLoc, VarsWithInheritedDSA);
  3302. break;
  3303. case OMPD_target_update:
  3304. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3305. EndLoc, AStmt);
  3306. AllowedNameModifiers.push_back(OMPD_target_update);
  3307. break;
  3308. case OMPD_distribute_parallel_for:
  3309. Res = ActOnOpenMPDistributeParallelForDirective(
  3310. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3311. AllowedNameModifiers.push_back(OMPD_parallel);
  3312. break;
  3313. case OMPD_distribute_parallel_for_simd:
  3314. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3315. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3316. AllowedNameModifiers.push_back(OMPD_parallel);
  3317. break;
  3318. case OMPD_distribute_simd:
  3319. Res = ActOnOpenMPDistributeSimdDirective(
  3320. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3321. break;
  3322. case OMPD_target_parallel_for_simd:
  3323. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3324. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3325. AllowedNameModifiers.push_back(OMPD_target);
  3326. AllowedNameModifiers.push_back(OMPD_parallel);
  3327. break;
  3328. case OMPD_target_simd:
  3329. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3330. EndLoc, VarsWithInheritedDSA);
  3331. AllowedNameModifiers.push_back(OMPD_target);
  3332. break;
  3333. case OMPD_teams_distribute:
  3334. Res = ActOnOpenMPTeamsDistributeDirective(
  3335. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3336. break;
  3337. case OMPD_teams_distribute_simd:
  3338. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3339. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3340. break;
  3341. case OMPD_teams_distribute_parallel_for_simd:
  3342. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3343. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3344. AllowedNameModifiers.push_back(OMPD_parallel);
  3345. break;
  3346. case OMPD_teams_distribute_parallel_for:
  3347. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3348. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3349. AllowedNameModifiers.push_back(OMPD_parallel);
  3350. break;
  3351. case OMPD_target_teams:
  3352. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3353. EndLoc);
  3354. AllowedNameModifiers.push_back(OMPD_target);
  3355. break;
  3356. case OMPD_target_teams_distribute:
  3357. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3358. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3359. AllowedNameModifiers.push_back(OMPD_target);
  3360. break;
  3361. case OMPD_target_teams_distribute_parallel_for:
  3362. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3363. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3364. AllowedNameModifiers.push_back(OMPD_target);
  3365. AllowedNameModifiers.push_back(OMPD_parallel);
  3366. break;
  3367. case OMPD_target_teams_distribute_parallel_for_simd:
  3368. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3369. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3370. AllowedNameModifiers.push_back(OMPD_target);
  3371. AllowedNameModifiers.push_back(OMPD_parallel);
  3372. break;
  3373. case OMPD_target_teams_distribute_simd:
  3374. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3375. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3376. AllowedNameModifiers.push_back(OMPD_target);
  3377. break;
  3378. case OMPD_declare_target:
  3379. case OMPD_end_declare_target:
  3380. case OMPD_threadprivate:
  3381. case OMPD_declare_reduction:
  3382. case OMPD_declare_simd:
  3383. case OMPD_requires:
  3384. llvm_unreachable("OpenMP Directive is not allowed");
  3385. case OMPD_unknown:
  3386. llvm_unreachable("Unknown OpenMP directive");
  3387. }
  3388. for (const auto &P : VarsWithInheritedDSA) {
  3389. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3390. << P.first << P.second->getSourceRange();
  3391. }
  3392. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3393. if (!AllowedNameModifiers.empty())
  3394. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3395. ErrorFound;
  3396. if (ErrorFound)
  3397. return StmtError();
  3398. return Res;
  3399. }
  3400. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3401. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3402. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3403. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3404. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3405. assert(Aligneds.size() == Alignments.size());
  3406. assert(Linears.size() == LinModifiers.size());
  3407. assert(Linears.size() == Steps.size());
  3408. if (!DG || DG.get().isNull())
  3409. return DeclGroupPtrTy();
  3410. if (!DG.get().isSingleDecl()) {
  3411. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3412. return DG;
  3413. }
  3414. Decl *ADecl = DG.get().getSingleDecl();
  3415. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3416. ADecl = FTD->getTemplatedDecl();
  3417. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3418. if (!FD) {
  3419. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3420. return DeclGroupPtrTy();
  3421. }
  3422. // OpenMP [2.8.2, declare simd construct, Description]
  3423. // The parameter of the simdlen clause must be a constant positive integer
  3424. // expression.
  3425. ExprResult SL;
  3426. if (Simdlen)
  3427. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3428. // OpenMP [2.8.2, declare simd construct, Description]
  3429. // The special this pointer can be used as if was one of the arguments to the
  3430. // function in any of the linear, aligned, or uniform clauses.
  3431. // The uniform clause declares one or more arguments to have an invariant
  3432. // value for all concurrent invocations of the function in the execution of a
  3433. // single SIMD loop.
  3434. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3435. const Expr *UniformedLinearThis = nullptr;
  3436. for (const Expr *E : Uniforms) {
  3437. E = E->IgnoreParenImpCasts();
  3438. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3439. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3440. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3441. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3442. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3443. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3444. continue;
  3445. }
  3446. if (isa<CXXThisExpr>(E)) {
  3447. UniformedLinearThis = E;
  3448. continue;
  3449. }
  3450. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3451. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3452. }
  3453. // OpenMP [2.8.2, declare simd construct, Description]
  3454. // The aligned clause declares that the object to which each list item points
  3455. // is aligned to the number of bytes expressed in the optional parameter of
  3456. // the aligned clause.
  3457. // The special this pointer can be used as if was one of the arguments to the
  3458. // function in any of the linear, aligned, or uniform clauses.
  3459. // The type of list items appearing in the aligned clause must be array,
  3460. // pointer, reference to array, or reference to pointer.
  3461. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3462. const Expr *AlignedThis = nullptr;
  3463. for (const Expr *E : Aligneds) {
  3464. E = E->IgnoreParenImpCasts();
  3465. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3466. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3467. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3468. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3469. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3470. ->getCanonicalDecl() == CanonPVD) {
  3471. // OpenMP [2.8.1, simd construct, Restrictions]
  3472. // A list-item cannot appear in more than one aligned clause.
  3473. if (AlignedArgs.count(CanonPVD) > 0) {
  3474. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3475. << 1 << E->getSourceRange();
  3476. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3477. diag::note_omp_explicit_dsa)
  3478. << getOpenMPClauseName(OMPC_aligned);
  3479. continue;
  3480. }
  3481. AlignedArgs[CanonPVD] = E;
  3482. QualType QTy = PVD->getType()
  3483. .getNonReferenceType()
  3484. .getUnqualifiedType()
  3485. .getCanonicalType();
  3486. const Type *Ty = QTy.getTypePtrOrNull();
  3487. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3488. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3489. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3490. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3491. }
  3492. continue;
  3493. }
  3494. }
  3495. if (isa<CXXThisExpr>(E)) {
  3496. if (AlignedThis) {
  3497. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3498. << 2 << E->getSourceRange();
  3499. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3500. << getOpenMPClauseName(OMPC_aligned);
  3501. }
  3502. AlignedThis = E;
  3503. continue;
  3504. }
  3505. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3506. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3507. }
  3508. // The optional parameter of the aligned clause, alignment, must be a constant
  3509. // positive integer expression. If no optional parameter is specified,
  3510. // implementation-defined default alignments for SIMD instructions on the
  3511. // target platforms are assumed.
  3512. SmallVector<const Expr *, 4> NewAligns;
  3513. for (Expr *E : Alignments) {
  3514. ExprResult Align;
  3515. if (E)
  3516. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3517. NewAligns.push_back(Align.get());
  3518. }
  3519. // OpenMP [2.8.2, declare simd construct, Description]
  3520. // The linear clause declares one or more list items to be private to a SIMD
  3521. // lane and to have a linear relationship with respect to the iteration space
  3522. // of a loop.
  3523. // The special this pointer can be used as if was one of the arguments to the
  3524. // function in any of the linear, aligned, or uniform clauses.
  3525. // When a linear-step expression is specified in a linear clause it must be
  3526. // either a constant integer expression or an integer-typed parameter that is
  3527. // specified in a uniform clause on the directive.
  3528. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  3529. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3530. auto MI = LinModifiers.begin();
  3531. for (const Expr *E : Linears) {
  3532. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3533. ++MI;
  3534. E = E->IgnoreParenImpCasts();
  3535. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3536. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3537. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3538. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3539. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3540. ->getCanonicalDecl() == CanonPVD) {
  3541. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3542. // A list-item cannot appear in more than one linear clause.
  3543. if (LinearArgs.count(CanonPVD) > 0) {
  3544. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3545. << getOpenMPClauseName(OMPC_linear)
  3546. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3547. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3548. diag::note_omp_explicit_dsa)
  3549. << getOpenMPClauseName(OMPC_linear);
  3550. continue;
  3551. }
  3552. // Each argument can appear in at most one uniform or linear clause.
  3553. if (UniformedArgs.count(CanonPVD) > 0) {
  3554. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3555. << getOpenMPClauseName(OMPC_linear)
  3556. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3557. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3558. diag::note_omp_explicit_dsa)
  3559. << getOpenMPClauseName(OMPC_uniform);
  3560. continue;
  3561. }
  3562. LinearArgs[CanonPVD] = E;
  3563. if (E->isValueDependent() || E->isTypeDependent() ||
  3564. E->isInstantiationDependent() ||
  3565. E->containsUnexpandedParameterPack())
  3566. continue;
  3567. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3568. PVD->getOriginalType());
  3569. continue;
  3570. }
  3571. }
  3572. if (isa<CXXThisExpr>(E)) {
  3573. if (UniformedLinearThis) {
  3574. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3575. << getOpenMPClauseName(OMPC_linear)
  3576. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3577. << E->getSourceRange();
  3578. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3579. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3580. : OMPC_linear);
  3581. continue;
  3582. }
  3583. UniformedLinearThis = E;
  3584. if (E->isValueDependent() || E->isTypeDependent() ||
  3585. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3586. continue;
  3587. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3588. E->getType());
  3589. continue;
  3590. }
  3591. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3592. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3593. }
  3594. Expr *Step = nullptr;
  3595. Expr *NewStep = nullptr;
  3596. SmallVector<Expr *, 4> NewSteps;
  3597. for (Expr *E : Steps) {
  3598. // Skip the same step expression, it was checked already.
  3599. if (Step == E || !E) {
  3600. NewSteps.push_back(E ? NewStep : nullptr);
  3601. continue;
  3602. }
  3603. Step = E;
  3604. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3605. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3606. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3607. if (UniformedArgs.count(CanonPVD) == 0) {
  3608. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3609. << Step->getSourceRange();
  3610. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3611. E->isInstantiationDependent() ||
  3612. E->containsUnexpandedParameterPack() ||
  3613. CanonPVD->getType()->hasIntegerRepresentation()) {
  3614. NewSteps.push_back(Step);
  3615. } else {
  3616. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3617. << Step->getSourceRange();
  3618. }
  3619. continue;
  3620. }
  3621. NewStep = Step;
  3622. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3623. !Step->isInstantiationDependent() &&
  3624. !Step->containsUnexpandedParameterPack()) {
  3625. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3626. .get();
  3627. if (NewStep)
  3628. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3629. }
  3630. NewSteps.push_back(NewStep);
  3631. }
  3632. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3633. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3634. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3635. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3636. const_cast<Expr **>(Linears.data()), Linears.size(),
  3637. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3638. NewSteps.data(), NewSteps.size(), SR);
  3639. ADecl->addAttr(NewAttr);
  3640. return ConvertDeclToDeclGroup(ADecl);
  3641. }
  3642. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3643. Stmt *AStmt,
  3644. SourceLocation StartLoc,
  3645. SourceLocation EndLoc) {
  3646. if (!AStmt)
  3647. return StmtError();
  3648. auto *CS = cast<CapturedStmt>(AStmt);
  3649. // 1.2.2 OpenMP Language Terminology
  3650. // Structured block - An executable statement with a single entry at the
  3651. // top and a single exit at the bottom.
  3652. // The point of exit cannot be a branch out of the structured block.
  3653. // longjmp() and throw() must not violate the entry/exit criteria.
  3654. CS->getCapturedDecl()->setNothrow();
  3655. setFunctionHasBranchProtectedScope();
  3656. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3657. DSAStack->isCancelRegion());
  3658. }
  3659. namespace {
  3660. /// Helper class for checking canonical form of the OpenMP loops and
  3661. /// extracting iteration space of each loop in the loop nest, that will be used
  3662. /// for IR generation.
  3663. class OpenMPIterationSpaceChecker {
  3664. /// Reference to Sema.
  3665. Sema &SemaRef;
  3666. /// A location for diagnostics (when there is no some better location).
  3667. SourceLocation DefaultLoc;
  3668. /// A location for diagnostics (when increment is not compatible).
  3669. SourceLocation ConditionLoc;
  3670. /// A source location for referring to loop init later.
  3671. SourceRange InitSrcRange;
  3672. /// A source location for referring to condition later.
  3673. SourceRange ConditionSrcRange;
  3674. /// A source location for referring to increment later.
  3675. SourceRange IncrementSrcRange;
  3676. /// Loop variable.
  3677. ValueDecl *LCDecl = nullptr;
  3678. /// Reference to loop variable.
  3679. Expr *LCRef = nullptr;
  3680. /// Lower bound (initializer for the var).
  3681. Expr *LB = nullptr;
  3682. /// Upper bound.
  3683. Expr *UB = nullptr;
  3684. /// Loop step (increment).
  3685. Expr *Step = nullptr;
  3686. /// This flag is true when condition is one of:
  3687. /// Var < UB
  3688. /// Var <= UB
  3689. /// UB > Var
  3690. /// UB >= Var
  3691. bool TestIsLessOp = false;
  3692. /// This flag is true when condition is strict ( < or > ).
  3693. bool TestIsStrictOp = false;
  3694. /// This flag is true when step is subtracted on each iteration.
  3695. bool SubtractStep = false;
  3696. public:
  3697. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3698. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3699. /// Check init-expr for canonical loop form and save loop counter
  3700. /// variable - #Var and its initialization value - #LB.
  3701. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  3702. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  3703. /// for less/greater and for strict/non-strict comparison.
  3704. bool checkAndSetCond(Expr *S);
  3705. /// Check incr-expr for canonical loop form and return true if it
  3706. /// does not conform, otherwise save loop step (#Step).
  3707. bool checkAndSetInc(Expr *S);
  3708. /// Return the loop counter variable.
  3709. ValueDecl *getLoopDecl() const { return LCDecl; }
  3710. /// Return the reference expression to loop counter variable.
  3711. Expr *getLoopDeclRefExpr() const { return LCRef; }
  3712. /// Source range of the loop init.
  3713. SourceRange getInitSrcRange() const { return InitSrcRange; }
  3714. /// Source range of the loop condition.
  3715. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  3716. /// Source range of the loop increment.
  3717. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  3718. /// True if the step should be subtracted.
  3719. bool shouldSubtractStep() const { return SubtractStep; }
  3720. /// Build the expression to calculate the number of iterations.
  3721. Expr *buildNumIterations(
  3722. Scope *S, const bool LimitedType,
  3723. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3724. /// Build the precondition expression for the loops.
  3725. Expr *
  3726. buildPreCond(Scope *S, Expr *Cond,
  3727. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3728. /// Build reference expression to the counter be used for codegen.
  3729. DeclRefExpr *
  3730. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3731. DSAStackTy &DSA) const;
  3732. /// Build reference expression to the private counter be used for
  3733. /// codegen.
  3734. Expr *buildPrivateCounterVar() const;
  3735. /// Build initialization of the counter be used for codegen.
  3736. Expr *buildCounterInit() const;
  3737. /// Build step of the counter be used for codegen.
  3738. Expr *buildCounterStep() const;
  3739. /// Build loop data with counter value for depend clauses in ordered
  3740. /// directives.
  3741. Expr *
  3742. buildOrderedLoopData(Scope *S, Expr *Counter,
  3743. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3744. SourceLocation Loc, Expr *Inc = nullptr,
  3745. OverloadedOperatorKind OOK = OO_Amp);
  3746. /// Return true if any expression is dependent.
  3747. bool dependent() const;
  3748. private:
  3749. /// Check the right-hand side of an assignment in the increment
  3750. /// expression.
  3751. bool checkAndSetIncRHS(Expr *RHS);
  3752. /// Helper to set loop counter variable and its initializer.
  3753. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3754. /// Helper to set upper bound.
  3755. bool setUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3756. SourceLocation SL);
  3757. /// Helper to set loop increment.
  3758. bool setStep(Expr *NewStep, bool Subtract);
  3759. };
  3760. bool OpenMPIterationSpaceChecker::dependent() const {
  3761. if (!LCDecl) {
  3762. assert(!LB && !UB && !Step);
  3763. return false;
  3764. }
  3765. return LCDecl->getType()->isDependentType() ||
  3766. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3767. (Step && Step->isValueDependent());
  3768. }
  3769. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  3770. Expr *NewLCRefExpr,
  3771. Expr *NewLB) {
  3772. // State consistency checking to ensure correct usage.
  3773. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3774. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3775. if (!NewLCDecl || !NewLB)
  3776. return true;
  3777. LCDecl = getCanonicalDecl(NewLCDecl);
  3778. LCRef = NewLCRefExpr;
  3779. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3780. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3781. if ((Ctor->isCopyOrMoveConstructor() ||
  3782. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3783. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3784. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3785. LB = NewLB;
  3786. return false;
  3787. }
  3788. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3789. SourceRange SR, SourceLocation SL) {
  3790. // State consistency checking to ensure correct usage.
  3791. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3792. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3793. if (!NewUB)
  3794. return true;
  3795. UB = NewUB;
  3796. TestIsLessOp = LessOp;
  3797. TestIsStrictOp = StrictOp;
  3798. ConditionSrcRange = SR;
  3799. ConditionLoc = SL;
  3800. return false;
  3801. }
  3802. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  3803. // State consistency checking to ensure correct usage.
  3804. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3805. if (!NewStep)
  3806. return true;
  3807. if (!NewStep->isValueDependent()) {
  3808. // Check that the step is integer expression.
  3809. SourceLocation StepLoc = NewStep->getBeginLoc();
  3810. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3811. StepLoc, getExprAsWritten(NewStep));
  3812. if (Val.isInvalid())
  3813. return true;
  3814. NewStep = Val.get();
  3815. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3816. // If test-expr is of form var relational-op b and relational-op is < or
  3817. // <= then incr-expr must cause var to increase on each iteration of the
  3818. // loop. If test-expr is of form var relational-op b and relational-op is
  3819. // > or >= then incr-expr must cause var to decrease on each iteration of
  3820. // the loop.
  3821. // If test-expr is of form b relational-op var and relational-op is < or
  3822. // <= then incr-expr must cause var to decrease on each iteration of the
  3823. // loop. If test-expr is of form b relational-op var and relational-op is
  3824. // > or >= then incr-expr must cause var to increase on each iteration of
  3825. // the loop.
  3826. llvm::APSInt Result;
  3827. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3828. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3829. bool IsConstNeg =
  3830. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3831. bool IsConstPos =
  3832. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3833. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3834. if (UB && (IsConstZero ||
  3835. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3836. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3837. SemaRef.Diag(NewStep->getExprLoc(),
  3838. diag::err_omp_loop_incr_not_compatible)
  3839. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3840. SemaRef.Diag(ConditionLoc,
  3841. diag::note_omp_loop_cond_requres_compatible_incr)
  3842. << TestIsLessOp << ConditionSrcRange;
  3843. return true;
  3844. }
  3845. if (TestIsLessOp == Subtract) {
  3846. NewStep =
  3847. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3848. .get();
  3849. Subtract = !Subtract;
  3850. }
  3851. }
  3852. Step = NewStep;
  3853. SubtractStep = Subtract;
  3854. return false;
  3855. }
  3856. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  3857. // Check init-expr for canonical loop form and save loop counter
  3858. // variable - #Var and its initialization value - #LB.
  3859. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3860. // var = lb
  3861. // integer-type var = lb
  3862. // random-access-iterator-type var = lb
  3863. // pointer-type var = lb
  3864. //
  3865. if (!S) {
  3866. if (EmitDiags) {
  3867. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3868. }
  3869. return true;
  3870. }
  3871. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3872. if (!ExprTemp->cleanupsHaveSideEffects())
  3873. S = ExprTemp->getSubExpr();
  3874. InitSrcRange = S->getSourceRange();
  3875. if (Expr *E = dyn_cast<Expr>(S))
  3876. S = E->IgnoreParens();
  3877. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3878. if (BO->getOpcode() == BO_Assign) {
  3879. Expr *LHS = BO->getLHS()->IgnoreParens();
  3880. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3881. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3882. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3883. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3884. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3885. }
  3886. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3887. if (ME->isArrow() &&
  3888. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3889. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3890. }
  3891. }
  3892. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3893. if (DS->isSingleDecl()) {
  3894. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3895. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3896. // Accept non-canonical init form here but emit ext. warning.
  3897. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3898. SemaRef.Diag(S->getBeginLoc(),
  3899. diag::ext_omp_loop_not_canonical_init)
  3900. << S->getSourceRange();
  3901. return setLCDeclAndLB(
  3902. Var,
  3903. buildDeclRefExpr(SemaRef, Var,
  3904. Var->getType().getNonReferenceType(),
  3905. DS->getBeginLoc()),
  3906. Var->getInit());
  3907. }
  3908. }
  3909. }
  3910. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3911. if (CE->getOperator() == OO_Equal) {
  3912. Expr *LHS = CE->getArg(0);
  3913. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3914. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3915. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3916. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3917. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3918. }
  3919. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3920. if (ME->isArrow() &&
  3921. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3922. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3923. }
  3924. }
  3925. }
  3926. if (dependent() || SemaRef.CurContext->isDependentContext())
  3927. return false;
  3928. if (EmitDiags) {
  3929. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  3930. << S->getSourceRange();
  3931. }
  3932. return true;
  3933. }
  3934. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  3935. /// variable (which may be the loop variable) if possible.
  3936. static const ValueDecl *getInitLCDecl(const Expr *E) {
  3937. if (!E)
  3938. return nullptr;
  3939. E = getExprAsWritten(E);
  3940. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3941. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3942. if ((Ctor->isCopyOrMoveConstructor() ||
  3943. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3944. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3945. E = CE->getArg(0)->IgnoreParenImpCasts();
  3946. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3947. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3948. return getCanonicalDecl(VD);
  3949. }
  3950. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3951. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3952. return getCanonicalDecl(ME->getMemberDecl());
  3953. return nullptr;
  3954. }
  3955. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  3956. // Check test-expr for canonical form, save upper-bound UB, flags for
  3957. // less/greater and for strict/non-strict comparison.
  3958. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3959. // var relational-op b
  3960. // b relational-op var
  3961. //
  3962. if (!S) {
  3963. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3964. return true;
  3965. }
  3966. S = getExprAsWritten(S);
  3967. SourceLocation CondLoc = S->getBeginLoc();
  3968. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3969. if (BO->isRelationalOp()) {
  3970. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3971. return setUB(BO->getRHS(),
  3972. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3973. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3974. BO->getSourceRange(), BO->getOperatorLoc());
  3975. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  3976. return setUB(BO->getLHS(),
  3977. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3978. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3979. BO->getSourceRange(), BO->getOperatorLoc());
  3980. }
  3981. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3982. if (CE->getNumArgs() == 2) {
  3983. auto Op = CE->getOperator();
  3984. switch (Op) {
  3985. case OO_Greater:
  3986. case OO_GreaterEqual:
  3987. case OO_Less:
  3988. case OO_LessEqual:
  3989. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  3990. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3991. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3992. CE->getOperatorLoc());
  3993. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  3994. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3995. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3996. CE->getOperatorLoc());
  3997. break;
  3998. default:
  3999. break;
  4000. }
  4001. }
  4002. }
  4003. if (dependent() || SemaRef.CurContext->isDependentContext())
  4004. return false;
  4005. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4006. << S->getSourceRange() << LCDecl;
  4007. return true;
  4008. }
  4009. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4010. // RHS of canonical loop form increment can be:
  4011. // var + incr
  4012. // incr + var
  4013. // var - incr
  4014. //
  4015. RHS = RHS->IgnoreParenImpCasts();
  4016. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4017. if (BO->isAdditiveOp()) {
  4018. bool IsAdd = BO->getOpcode() == BO_Add;
  4019. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4020. return setStep(BO->getRHS(), !IsAdd);
  4021. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4022. return setStep(BO->getLHS(), /*Subtract=*/false);
  4023. }
  4024. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4025. bool IsAdd = CE->getOperator() == OO_Plus;
  4026. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4027. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4028. return setStep(CE->getArg(1), !IsAdd);
  4029. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4030. return setStep(CE->getArg(0), /*Subtract=*/false);
  4031. }
  4032. }
  4033. if (dependent() || SemaRef.CurContext->isDependentContext())
  4034. return false;
  4035. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4036. << RHS->getSourceRange() << LCDecl;
  4037. return true;
  4038. }
  4039. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4040. // Check incr-expr for canonical loop form and return true if it
  4041. // does not conform.
  4042. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4043. // ++var
  4044. // var++
  4045. // --var
  4046. // var--
  4047. // var += incr
  4048. // var -= incr
  4049. // var = var + incr
  4050. // var = incr + var
  4051. // var = var - incr
  4052. //
  4053. if (!S) {
  4054. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4055. return true;
  4056. }
  4057. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4058. if (!ExprTemp->cleanupsHaveSideEffects())
  4059. S = ExprTemp->getSubExpr();
  4060. IncrementSrcRange = S->getSourceRange();
  4061. S = S->IgnoreParens();
  4062. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4063. if (UO->isIncrementDecrementOp() &&
  4064. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4065. return setStep(SemaRef
  4066. .ActOnIntegerConstant(UO->getBeginLoc(),
  4067. (UO->isDecrementOp() ? -1 : 1))
  4068. .get(),
  4069. /*Subtract=*/false);
  4070. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4071. switch (BO->getOpcode()) {
  4072. case BO_AddAssign:
  4073. case BO_SubAssign:
  4074. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4075. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4076. break;
  4077. case BO_Assign:
  4078. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4079. return checkAndSetIncRHS(BO->getRHS());
  4080. break;
  4081. default:
  4082. break;
  4083. }
  4084. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4085. switch (CE->getOperator()) {
  4086. case OO_PlusPlus:
  4087. case OO_MinusMinus:
  4088. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4089. return setStep(SemaRef
  4090. .ActOnIntegerConstant(
  4091. CE->getBeginLoc(),
  4092. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  4093. .get(),
  4094. /*Subtract=*/false);
  4095. break;
  4096. case OO_PlusEqual:
  4097. case OO_MinusEqual:
  4098. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4099. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  4100. break;
  4101. case OO_Equal:
  4102. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4103. return checkAndSetIncRHS(CE->getArg(1));
  4104. break;
  4105. default:
  4106. break;
  4107. }
  4108. }
  4109. if (dependent() || SemaRef.CurContext->isDependentContext())
  4110. return false;
  4111. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4112. << S->getSourceRange() << LCDecl;
  4113. return true;
  4114. }
  4115. static ExprResult
  4116. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  4117. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4118. if (SemaRef.CurContext->isDependentContext())
  4119. return ExprResult(Capture);
  4120. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  4121. return SemaRef.PerformImplicitConversion(
  4122. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  4123. /*AllowExplicit=*/true);
  4124. auto I = Captures.find(Capture);
  4125. if (I != Captures.end())
  4126. return buildCapture(SemaRef, Capture, I->second);
  4127. DeclRefExpr *Ref = nullptr;
  4128. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  4129. Captures[Capture] = Ref;
  4130. return Res;
  4131. }
  4132. /// Build the expression to calculate the number of iterations.
  4133. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  4134. Scope *S, const bool LimitedType,
  4135. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4136. ExprResult Diff;
  4137. QualType VarType = LCDecl->getType().getNonReferenceType();
  4138. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4139. SemaRef.getLangOpts().CPlusPlus) {
  4140. // Upper - Lower
  4141. Expr *UBExpr = TestIsLessOp ? UB : LB;
  4142. Expr *LBExpr = TestIsLessOp ? LB : UB;
  4143. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  4144. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  4145. if (!Upper || !Lower)
  4146. return nullptr;
  4147. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4148. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4149. // BuildBinOp already emitted error, this one is to point user to upper
  4150. // and lower bound, and to tell what is passed to 'operator-'.
  4151. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4152. << Upper->getSourceRange() << Lower->getSourceRange();
  4153. return nullptr;
  4154. }
  4155. }
  4156. if (!Diff.isUsable())
  4157. return nullptr;
  4158. // Upper - Lower [- 1]
  4159. if (TestIsStrictOp)
  4160. Diff = SemaRef.BuildBinOp(
  4161. S, DefaultLoc, BO_Sub, Diff.get(),
  4162. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4163. if (!Diff.isUsable())
  4164. return nullptr;
  4165. // Upper - Lower [- 1] + Step
  4166. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4167. if (!NewStep.isUsable())
  4168. return nullptr;
  4169. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  4170. if (!Diff.isUsable())
  4171. return nullptr;
  4172. // Parentheses (for dumping/debugging purposes only).
  4173. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4174. if (!Diff.isUsable())
  4175. return nullptr;
  4176. // (Upper - Lower [- 1] + Step) / Step
  4177. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4178. if (!Diff.isUsable())
  4179. return nullptr;
  4180. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  4181. QualType Type = Diff.get()->getType();
  4182. ASTContext &C = SemaRef.Context;
  4183. bool UseVarType = VarType->hasIntegerRepresentation() &&
  4184. C.getTypeSize(Type) > C.getTypeSize(VarType);
  4185. if (!Type->isIntegerType() || UseVarType) {
  4186. unsigned NewSize =
  4187. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  4188. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  4189. : Type->hasSignedIntegerRepresentation();
  4190. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  4191. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  4192. Diff = SemaRef.PerformImplicitConversion(
  4193. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  4194. if (!Diff.isUsable())
  4195. return nullptr;
  4196. }
  4197. }
  4198. if (LimitedType) {
  4199. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  4200. if (NewSize != C.getTypeSize(Type)) {
  4201. if (NewSize < C.getTypeSize(Type)) {
  4202. assert(NewSize == 64 && "incorrect loop var size");
  4203. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  4204. << InitSrcRange << ConditionSrcRange;
  4205. }
  4206. QualType NewType = C.getIntTypeForBitwidth(
  4207. NewSize, Type->hasSignedIntegerRepresentation() ||
  4208. C.getTypeSize(Type) < NewSize);
  4209. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  4210. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  4211. Sema::AA_Converting, true);
  4212. if (!Diff.isUsable())
  4213. return nullptr;
  4214. }
  4215. }
  4216. }
  4217. return Diff.get();
  4218. }
  4219. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4220. Scope *S, Expr *Cond,
  4221. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4222. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4223. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4224. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4225. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4226. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4227. if (!NewLB.isUsable() || !NewUB.isUsable())
  4228. return nullptr;
  4229. ExprResult CondExpr =
  4230. SemaRef.BuildBinOp(S, DefaultLoc,
  4231. TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  4232. : (TestIsStrictOp ? BO_GT : BO_GE),
  4233. NewLB.get(), NewUB.get());
  4234. if (CondExpr.isUsable()) {
  4235. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4236. SemaRef.Context.BoolTy))
  4237. CondExpr = SemaRef.PerformImplicitConversion(
  4238. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4239. /*AllowExplicit=*/true);
  4240. }
  4241. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4242. // Otherwise use original loop conditon and evaluate it in runtime.
  4243. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4244. }
  4245. /// Build reference expression to the counter be used for codegen.
  4246. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4247. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4248. DSAStackTy &DSA) const {
  4249. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4250. if (!VD) {
  4251. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4252. DeclRefExpr *Ref = buildDeclRefExpr(
  4253. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4254. const DSAStackTy::DSAVarData Data =
  4255. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4256. // If the loop control decl is explicitly marked as private, do not mark it
  4257. // as captured again.
  4258. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4259. Captures.insert(std::make_pair(LCRef, Ref));
  4260. return Ref;
  4261. }
  4262. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  4263. DefaultLoc);
  4264. }
  4265. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4266. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4267. QualType Type = LCDecl->getType().getNonReferenceType();
  4268. VarDecl *PrivateVar = buildVarDecl(
  4269. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4270. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4271. isa<VarDecl>(LCDecl)
  4272. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4273. : nullptr);
  4274. if (PrivateVar->isInvalidDecl())
  4275. return nullptr;
  4276. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4277. }
  4278. return nullptr;
  4279. }
  4280. /// Build initialization of the counter to be used for codegen.
  4281. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4282. /// Build step of the counter be used for codegen.
  4283. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4284. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  4285. Scope *S, Expr *Counter,
  4286. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  4287. Expr *Inc, OverloadedOperatorKind OOK) {
  4288. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  4289. if (!Cnt)
  4290. return nullptr;
  4291. if (Inc) {
  4292. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  4293. "Expected only + or - operations for depend clauses.");
  4294. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  4295. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  4296. if (!Cnt)
  4297. return nullptr;
  4298. }
  4299. ExprResult Diff;
  4300. QualType VarType = LCDecl->getType().getNonReferenceType();
  4301. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4302. SemaRef.getLangOpts().CPlusPlus) {
  4303. // Upper - Lower
  4304. Expr *Upper =
  4305. TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
  4306. Expr *Lower =
  4307. TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
  4308. if (!Upper || !Lower)
  4309. return nullptr;
  4310. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4311. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4312. // BuildBinOp already emitted error, this one is to point user to upper
  4313. // and lower bound, and to tell what is passed to 'operator-'.
  4314. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4315. << Upper->getSourceRange() << Lower->getSourceRange();
  4316. return nullptr;
  4317. }
  4318. }
  4319. if (!Diff.isUsable())
  4320. return nullptr;
  4321. // Parentheses (for dumping/debugging purposes only).
  4322. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4323. if (!Diff.isUsable())
  4324. return nullptr;
  4325. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4326. if (!NewStep.isUsable())
  4327. return nullptr;
  4328. // (Upper - Lower) / Step
  4329. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4330. if (!Diff.isUsable())
  4331. return nullptr;
  4332. return Diff.get();
  4333. }
  4334. /// Iteration space of a single for loop.
  4335. struct LoopIterationSpace final {
  4336. /// Condition of the loop.
  4337. Expr *PreCond = nullptr;
  4338. /// This expression calculates the number of iterations in the loop.
  4339. /// It is always possible to calculate it before starting the loop.
  4340. Expr *NumIterations = nullptr;
  4341. /// The loop counter variable.
  4342. Expr *CounterVar = nullptr;
  4343. /// Private loop counter variable.
  4344. Expr *PrivateCounterVar = nullptr;
  4345. /// This is initializer for the initial value of #CounterVar.
  4346. Expr *CounterInit = nullptr;
  4347. /// This is step for the #CounterVar used to generate its update:
  4348. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4349. Expr *CounterStep = nullptr;
  4350. /// Should step be subtracted?
  4351. bool Subtract = false;
  4352. /// Source range of the loop init.
  4353. SourceRange InitSrcRange;
  4354. /// Source range of the loop condition.
  4355. SourceRange CondSrcRange;
  4356. /// Source range of the loop increment.
  4357. SourceRange IncSrcRange;
  4358. };
  4359. } // namespace
  4360. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4361. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4362. assert(Init && "Expected loop in canonical form.");
  4363. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4364. if (AssociatedLoops > 0 &&
  4365. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4366. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4367. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4368. if (ValueDecl *D = ISC.getLoopDecl()) {
  4369. auto *VD = dyn_cast<VarDecl>(D);
  4370. if (!VD) {
  4371. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4372. VD = Private;
  4373. } else {
  4374. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4375. /*WithInit=*/false);
  4376. VD = cast<VarDecl>(Ref->getDecl());
  4377. }
  4378. }
  4379. DSAStack->addLoopControlVariable(D, VD);
  4380. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  4381. if (LD != D->getCanonicalDecl()) {
  4382. DSAStack->resetPossibleLoopCounter();
  4383. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  4384. MarkDeclarationsReferencedInExpr(
  4385. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  4386. Var->getType().getNonLValueExprType(Context),
  4387. ForLoc, /*RefersToCapture=*/true));
  4388. }
  4389. }
  4390. }
  4391. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4392. }
  4393. }
  4394. /// Called on a for stmt to check and extract its iteration space
  4395. /// for further processing (such as collapsing).
  4396. static bool checkOpenMPIterationSpace(
  4397. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4398. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4399. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  4400. Expr *OrderedLoopCountExpr,
  4401. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4402. LoopIterationSpace &ResultIterSpace,
  4403. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4404. // OpenMP [2.6, Canonical Loop Form]
  4405. // for (init-expr; test-expr; incr-expr) structured-block
  4406. auto *For = dyn_cast_or_null<ForStmt>(S);
  4407. if (!For) {
  4408. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  4409. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4410. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  4411. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4412. if (TotalNestedLoopCount > 1) {
  4413. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4414. SemaRef.Diag(DSA.getConstructLoc(),
  4415. diag::note_omp_collapse_ordered_expr)
  4416. << 2 << CollapseLoopCountExpr->getSourceRange()
  4417. << OrderedLoopCountExpr->getSourceRange();
  4418. else if (CollapseLoopCountExpr)
  4419. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4420. diag::note_omp_collapse_ordered_expr)
  4421. << 0 << CollapseLoopCountExpr->getSourceRange();
  4422. else
  4423. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4424. diag::note_omp_collapse_ordered_expr)
  4425. << 1 << OrderedLoopCountExpr->getSourceRange();
  4426. }
  4427. return true;
  4428. }
  4429. assert(For->getBody());
  4430. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4431. // Check init.
  4432. Stmt *Init = For->getInit();
  4433. if (ISC.checkAndSetInit(Init))
  4434. return true;
  4435. bool HasErrors = false;
  4436. // Check loop variable's type.
  4437. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  4438. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  4439. // OpenMP [2.6, Canonical Loop Form]
  4440. // Var is one of the following:
  4441. // A variable of signed or unsigned integer type.
  4442. // For C++, a variable of a random access iterator type.
  4443. // For C, a variable of a pointer type.
  4444. QualType VarType = LCDecl->getType().getNonReferenceType();
  4445. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  4446. !VarType->isPointerType() &&
  4447. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  4448. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  4449. << SemaRef.getLangOpts().CPlusPlus;
  4450. HasErrors = true;
  4451. }
  4452. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  4453. // a Construct
  4454. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4455. // parallel for construct is (are) private.
  4456. // The loop iteration variable in the associated for-loop of a simd
  4457. // construct with just one associated for-loop is linear with a
  4458. // constant-linear-step that is the increment of the associated for-loop.
  4459. // Exclude loop var from the list of variables with implicitly defined data
  4460. // sharing attributes.
  4461. VarsWithImplicitDSA.erase(LCDecl);
  4462. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4463. // in a Construct, C/C++].
  4464. // The loop iteration variable in the associated for-loop of a simd
  4465. // construct with just one associated for-loop may be listed in a linear
  4466. // clause with a constant-linear-step that is the increment of the
  4467. // associated for-loop.
  4468. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4469. // parallel for construct may be listed in a private or lastprivate clause.
  4470. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  4471. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  4472. // declared in the loop and it is predetermined as a private.
  4473. OpenMPClauseKind PredeterminedCKind =
  4474. isOpenMPSimdDirective(DKind)
  4475. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  4476. : OMPC_private;
  4477. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4478. DVar.CKind != PredeterminedCKind) ||
  4479. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  4480. isOpenMPDistributeDirective(DKind)) &&
  4481. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4482. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  4483. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4484. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  4485. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  4486. << getOpenMPClauseName(PredeterminedCKind);
  4487. if (DVar.RefExpr == nullptr)
  4488. DVar.CKind = PredeterminedCKind;
  4489. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  4490. HasErrors = true;
  4491. } else if (LoopDeclRefExpr != nullptr) {
  4492. // Make the loop iteration variable private (for worksharing constructs),
  4493. // linear (for simd directives with the only one associated loop) or
  4494. // lastprivate (for simd directives with several collapsed or ordered
  4495. // loops).
  4496. if (DVar.CKind == OMPC_unknown)
  4497. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  4498. [](OpenMPDirectiveKind) -> bool { return true; },
  4499. /*FromParent=*/false);
  4500. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  4501. }
  4502. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  4503. // Check test-expr.
  4504. HasErrors |= ISC.checkAndSetCond(For->getCond());
  4505. // Check incr-expr.
  4506. HasErrors |= ISC.checkAndSetInc(For->getInc());
  4507. }
  4508. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4509. return HasErrors;
  4510. // Build the loop's iteration space representation.
  4511. ResultIterSpace.PreCond =
  4512. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4513. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  4514. DSA.getCurScope(),
  4515. (isOpenMPWorksharingDirective(DKind) ||
  4516. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4517. Captures);
  4518. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  4519. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  4520. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  4521. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  4522. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  4523. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  4524. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  4525. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  4526. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4527. ResultIterSpace.NumIterations == nullptr ||
  4528. ResultIterSpace.CounterVar == nullptr ||
  4529. ResultIterSpace.PrivateCounterVar == nullptr ||
  4530. ResultIterSpace.CounterInit == nullptr ||
  4531. ResultIterSpace.CounterStep == nullptr);
  4532. if (!HasErrors && DSA.isOrderedRegion()) {
  4533. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  4534. if (CurrentNestedLoopCount <
  4535. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  4536. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  4537. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  4538. DSA.getOrderedRegionParam().second->setLoopCounter(
  4539. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  4540. }
  4541. }
  4542. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  4543. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  4544. // Erroneous case - clause has some problems.
  4545. continue;
  4546. }
  4547. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  4548. Pair.second.size() <= CurrentNestedLoopCount) {
  4549. // Erroneous case - clause has some problems.
  4550. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  4551. continue;
  4552. }
  4553. Expr *CntValue;
  4554. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4555. CntValue = ISC.buildOrderedLoopData(
  4556. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4557. Pair.first->getDependencyLoc());
  4558. else
  4559. CntValue = ISC.buildOrderedLoopData(
  4560. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4561. Pair.first->getDependencyLoc(),
  4562. Pair.second[CurrentNestedLoopCount].first,
  4563. Pair.second[CurrentNestedLoopCount].second);
  4564. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  4565. }
  4566. }
  4567. return HasErrors;
  4568. }
  4569. /// Build 'VarRef = Start.
  4570. static ExprResult
  4571. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4572. ExprResult Start,
  4573. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4574. // Build 'VarRef = Start.
  4575. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4576. if (!NewStart.isUsable())
  4577. return ExprError();
  4578. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4579. VarRef.get()->getType())) {
  4580. NewStart = SemaRef.PerformImplicitConversion(
  4581. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4582. /*AllowExplicit=*/true);
  4583. if (!NewStart.isUsable())
  4584. return ExprError();
  4585. }
  4586. ExprResult Init =
  4587. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4588. return Init;
  4589. }
  4590. /// Build 'VarRef = Start + Iter * Step'.
  4591. static ExprResult buildCounterUpdate(
  4592. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4593. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  4594. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  4595. // Add parentheses (for debugging purposes only).
  4596. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4597. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4598. !Step.isUsable())
  4599. return ExprError();
  4600. ExprResult NewStep = Step;
  4601. if (Captures)
  4602. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4603. if (NewStep.isInvalid())
  4604. return ExprError();
  4605. ExprResult Update =
  4606. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4607. if (!Update.isUsable())
  4608. return ExprError();
  4609. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4610. // 'VarRef = Start (+|-) Iter * Step'.
  4611. ExprResult NewStart = Start;
  4612. if (Captures)
  4613. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4614. if (NewStart.isInvalid())
  4615. return ExprError();
  4616. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4617. ExprResult SavedUpdate = Update;
  4618. ExprResult UpdateVal;
  4619. if (VarRef.get()->getType()->isOverloadableType() ||
  4620. NewStart.get()->getType()->isOverloadableType() ||
  4621. Update.get()->getType()->isOverloadableType()) {
  4622. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4623. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4624. Update =
  4625. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4626. if (Update.isUsable()) {
  4627. UpdateVal =
  4628. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4629. VarRef.get(), SavedUpdate.get());
  4630. if (UpdateVal.isUsable()) {
  4631. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4632. UpdateVal.get());
  4633. }
  4634. }
  4635. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4636. }
  4637. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4638. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4639. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4640. NewStart.get(), SavedUpdate.get());
  4641. if (!Update.isUsable())
  4642. return ExprError();
  4643. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4644. VarRef.get()->getType())) {
  4645. Update = SemaRef.PerformImplicitConversion(
  4646. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4647. if (!Update.isUsable())
  4648. return ExprError();
  4649. }
  4650. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4651. }
  4652. return Update;
  4653. }
  4654. /// Convert integer expression \a E to make it have at least \a Bits
  4655. /// bits.
  4656. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4657. if (E == nullptr)
  4658. return ExprError();
  4659. ASTContext &C = SemaRef.Context;
  4660. QualType OldType = E->getType();
  4661. unsigned HasBits = C.getTypeSize(OldType);
  4662. if (HasBits >= Bits)
  4663. return ExprResult(E);
  4664. // OK to convert to signed, because new type has more bits than old.
  4665. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4666. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4667. true);
  4668. }
  4669. /// Check if the given expression \a E is a constant integer that fits
  4670. /// into \a Bits bits.
  4671. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  4672. if (E == nullptr)
  4673. return false;
  4674. llvm::APSInt Result;
  4675. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4676. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4677. return false;
  4678. }
  4679. /// Build preinits statement for the given declarations.
  4680. static Stmt *buildPreInits(ASTContext &Context,
  4681. MutableArrayRef<Decl *> PreInits) {
  4682. if (!PreInits.empty()) {
  4683. return new (Context) DeclStmt(
  4684. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4685. SourceLocation(), SourceLocation());
  4686. }
  4687. return nullptr;
  4688. }
  4689. /// Build preinits statement for the given declarations.
  4690. static Stmt *
  4691. buildPreInits(ASTContext &Context,
  4692. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4693. if (!Captures.empty()) {
  4694. SmallVector<Decl *, 16> PreInits;
  4695. for (const auto &Pair : Captures)
  4696. PreInits.push_back(Pair.second->getDecl());
  4697. return buildPreInits(Context, PreInits);
  4698. }
  4699. return nullptr;
  4700. }
  4701. /// Build postupdate expression for the given list of postupdates expressions.
  4702. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4703. Expr *PostUpdate = nullptr;
  4704. if (!PostUpdates.empty()) {
  4705. for (Expr *E : PostUpdates) {
  4706. Expr *ConvE = S.BuildCStyleCastExpr(
  4707. E->getExprLoc(),
  4708. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4709. E->getExprLoc(), E)
  4710. .get();
  4711. PostUpdate = PostUpdate
  4712. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4713. PostUpdate, ConvE)
  4714. .get()
  4715. : ConvE;
  4716. }
  4717. }
  4718. return PostUpdate;
  4719. }
  4720. /// Called on a for stmt to check itself and nested loops (if any).
  4721. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4722. /// number of collapsed loops otherwise.
  4723. static unsigned
  4724. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4725. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4726. DSAStackTy &DSA,
  4727. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4728. OMPLoopDirective::HelperExprs &Built) {
  4729. unsigned NestedLoopCount = 1;
  4730. if (CollapseLoopCountExpr) {
  4731. // Found 'collapse' clause - calculate collapse number.
  4732. llvm::APSInt Result;
  4733. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4734. NestedLoopCount = Result.getLimitedValue();
  4735. }
  4736. unsigned OrderedLoopCount = 1;
  4737. if (OrderedLoopCountExpr) {
  4738. // Found 'ordered' clause - calculate collapse number.
  4739. llvm::APSInt Result;
  4740. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4741. if (Result.getLimitedValue() < NestedLoopCount) {
  4742. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4743. diag::err_omp_wrong_ordered_loop_count)
  4744. << OrderedLoopCountExpr->getSourceRange();
  4745. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4746. diag::note_collapse_loop_count)
  4747. << CollapseLoopCountExpr->getSourceRange();
  4748. }
  4749. OrderedLoopCount = Result.getLimitedValue();
  4750. }
  4751. }
  4752. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4753. // 'for simd', etc.).
  4754. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  4755. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4756. IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
  4757. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4758. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4759. if (checkOpenMPIterationSpace(
  4760. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4761. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4762. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4763. Captures))
  4764. return 0;
  4765. // Move on to the next nested for loop, or to the loop body.
  4766. // OpenMP [2.8.1, simd construct, Restrictions]
  4767. // All loops associated with the construct must be perfectly nested; that
  4768. // is, there must be no intervening code nor any OpenMP directive between
  4769. // any two loops.
  4770. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4771. }
  4772. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  4773. if (checkOpenMPIterationSpace(
  4774. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4775. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4776. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4777. Captures))
  4778. return 0;
  4779. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  4780. // Handle initialization of captured loop iterator variables.
  4781. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  4782. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  4783. Captures[DRE] = DRE;
  4784. }
  4785. }
  4786. // Move on to the next nested for loop, or to the loop body.
  4787. // OpenMP [2.8.1, simd construct, Restrictions]
  4788. // All loops associated with the construct must be perfectly nested; that
  4789. // is, there must be no intervening code nor any OpenMP directive between
  4790. // any two loops.
  4791. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4792. }
  4793. Built.clear(/* size */ NestedLoopCount);
  4794. if (SemaRef.CurContext->isDependentContext())
  4795. return NestedLoopCount;
  4796. // An example of what is generated for the following code:
  4797. //
  4798. // #pragma omp simd collapse(2) ordered(2)
  4799. // for (i = 0; i < NI; ++i)
  4800. // for (k = 0; k < NK; ++k)
  4801. // for (j = J0; j < NJ; j+=2) {
  4802. // <loop body>
  4803. // }
  4804. //
  4805. // We generate the code below.
  4806. // Note: the loop body may be outlined in CodeGen.
  4807. // Note: some counters may be C++ classes, operator- is used to find number of
  4808. // iterations and operator+= to calculate counter value.
  4809. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4810. // or i64 is currently supported).
  4811. //
  4812. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4813. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4814. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4815. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4816. // // similar updates for vars in clauses (e.g. 'linear')
  4817. // <loop body (using local i and j)>
  4818. // }
  4819. // i = NI; // assign final values of counters
  4820. // j = NJ;
  4821. //
  4822. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4823. // the iteration counts of the collapsed for loops.
  4824. // Precondition tests if there is at least one iteration (all conditions are
  4825. // true).
  4826. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4827. Expr *N0 = IterSpaces[0].NumIterations;
  4828. ExprResult LastIteration32 =
  4829. widenIterationCount(/*Bits=*/32,
  4830. SemaRef
  4831. .PerformImplicitConversion(
  4832. N0->IgnoreImpCasts(), N0->getType(),
  4833. Sema::AA_Converting, /*AllowExplicit=*/true)
  4834. .get(),
  4835. SemaRef);
  4836. ExprResult LastIteration64 = widenIterationCount(
  4837. /*Bits=*/64,
  4838. SemaRef
  4839. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  4840. Sema::AA_Converting,
  4841. /*AllowExplicit=*/true)
  4842. .get(),
  4843. SemaRef);
  4844. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4845. return NestedLoopCount;
  4846. ASTContext &C = SemaRef.Context;
  4847. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4848. Scope *CurScope = DSA.getCurScope();
  4849. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4850. if (PreCond.isUsable()) {
  4851. PreCond =
  4852. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4853. PreCond.get(), IterSpaces[Cnt].PreCond);
  4854. }
  4855. Expr *N = IterSpaces[Cnt].NumIterations;
  4856. SourceLocation Loc = N->getExprLoc();
  4857. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4858. if (LastIteration32.isUsable())
  4859. LastIteration32 = SemaRef.BuildBinOp(
  4860. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4861. SemaRef
  4862. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4863. Sema::AA_Converting,
  4864. /*AllowExplicit=*/true)
  4865. .get());
  4866. if (LastIteration64.isUsable())
  4867. LastIteration64 = SemaRef.BuildBinOp(
  4868. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4869. SemaRef
  4870. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4871. Sema::AA_Converting,
  4872. /*AllowExplicit=*/true)
  4873. .get());
  4874. }
  4875. // Choose either the 32-bit or 64-bit version.
  4876. ExprResult LastIteration = LastIteration64;
  4877. if (LastIteration32.isUsable() &&
  4878. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4879. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4880. fitsInto(
  4881. /*Bits=*/32,
  4882. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4883. LastIteration64.get(), SemaRef)))
  4884. LastIteration = LastIteration32;
  4885. QualType VType = LastIteration.get()->getType();
  4886. QualType RealVType = VType;
  4887. QualType StrideVType = VType;
  4888. if (isOpenMPTaskLoopDirective(DKind)) {
  4889. VType =
  4890. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4891. StrideVType =
  4892. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4893. }
  4894. if (!LastIteration.isUsable())
  4895. return 0;
  4896. // Save the number of iterations.
  4897. ExprResult NumIterations = LastIteration;
  4898. {
  4899. LastIteration = SemaRef.BuildBinOp(
  4900. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4901. LastIteration.get(),
  4902. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4903. if (!LastIteration.isUsable())
  4904. return 0;
  4905. }
  4906. // Calculate the last iteration number beforehand instead of doing this on
  4907. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4908. llvm::APSInt Result;
  4909. bool IsConstant =
  4910. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4911. ExprResult CalcLastIteration;
  4912. if (!IsConstant) {
  4913. ExprResult SaveRef =
  4914. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4915. LastIteration = SaveRef;
  4916. // Prepare SaveRef + 1.
  4917. NumIterations = SemaRef.BuildBinOp(
  4918. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4919. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4920. if (!NumIterations.isUsable())
  4921. return 0;
  4922. }
  4923. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4924. // Build variables passed into runtime, necessary for worksharing directives.
  4925. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4926. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4927. isOpenMPDistributeDirective(DKind)) {
  4928. // Lower bound variable, initialized with zero.
  4929. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4930. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4931. SemaRef.AddInitializerToDecl(LBDecl,
  4932. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4933. /*DirectInit*/ false);
  4934. // Upper bound variable, initialized with last iteration number.
  4935. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4936. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4937. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4938. /*DirectInit*/ false);
  4939. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4940. // This will be used to implement clause 'lastprivate'.
  4941. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4942. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4943. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4944. SemaRef.AddInitializerToDecl(ILDecl,
  4945. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4946. /*DirectInit*/ false);
  4947. // Stride variable returned by runtime (we initialize it to 1 by default).
  4948. VarDecl *STDecl =
  4949. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4950. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4951. SemaRef.AddInitializerToDecl(STDecl,
  4952. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4953. /*DirectInit*/ false);
  4954. // Build expression: UB = min(UB, LastIteration)
  4955. // It is necessary for CodeGen of directives with static scheduling.
  4956. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4957. UB.get(), LastIteration.get());
  4958. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4959. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  4960. LastIteration.get(), UB.get());
  4961. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4962. CondOp.get());
  4963. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4964. // If we have a combined directive that combines 'distribute', 'for' or
  4965. // 'simd' we need to be able to access the bounds of the schedule of the
  4966. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4967. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4968. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4969. // Lower bound variable, initialized with zero.
  4970. VarDecl *CombLBDecl =
  4971. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4972. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4973. SemaRef.AddInitializerToDecl(
  4974. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4975. /*DirectInit*/ false);
  4976. // Upper bound variable, initialized with last iteration number.
  4977. VarDecl *CombUBDecl =
  4978. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4979. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4980. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4981. /*DirectInit*/ false);
  4982. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4983. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4984. ExprResult CombCondOp =
  4985. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4986. LastIteration.get(), CombUB.get());
  4987. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4988. CombCondOp.get());
  4989. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4990. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4991. // We expect to have at least 2 more parameters than the 'parallel'
  4992. // directive does - the lower and upper bounds of the previous schedule.
  4993. assert(CD->getNumParams() >= 4 &&
  4994. "Unexpected number of parameters in loop combined directive");
  4995. // Set the proper type for the bounds given what we learned from the
  4996. // enclosed loops.
  4997. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4998. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4999. // Previous lower and upper bounds are obtained from the region
  5000. // parameters.
  5001. PrevLB =
  5002. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5003. PrevUB =
  5004. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5005. }
  5006. }
  5007. // Build the iteration variable and its initialization before loop.
  5008. ExprResult IV;
  5009. ExprResult Init, CombInit;
  5010. {
  5011. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5012. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5013. Expr *RHS =
  5014. (isOpenMPWorksharingDirective(DKind) ||
  5015. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5016. ? LB.get()
  5017. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5018. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5019. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  5020. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5021. Expr *CombRHS =
  5022. (isOpenMPWorksharingDirective(DKind) ||
  5023. isOpenMPTaskLoopDirective(DKind) ||
  5024. isOpenMPDistributeDirective(DKind))
  5025. ? CombLB.get()
  5026. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5027. CombInit =
  5028. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5029. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  5030. }
  5031. }
  5032. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  5033. SourceLocation CondLoc = AStmt->getBeginLoc();
  5034. ExprResult Cond =
  5035. (isOpenMPWorksharingDirective(DKind) ||
  5036. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5037. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  5038. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5039. NumIterations.get());
  5040. ExprResult CombDistCond;
  5041. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5042. CombDistCond =
  5043. SemaRef.BuildBinOp(
  5044. CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
  5045. }
  5046. ExprResult CombCond;
  5047. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5048. CombCond =
  5049. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  5050. }
  5051. // Loop increment (IV = IV + 1)
  5052. SourceLocation IncLoc = AStmt->getBeginLoc();
  5053. ExprResult Inc =
  5054. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  5055. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  5056. if (!Inc.isUsable())
  5057. return 0;
  5058. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  5059. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  5060. if (!Inc.isUsable())
  5061. return 0;
  5062. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  5063. // Used for directives with static scheduling.
  5064. // In combined construct, add combined version that use CombLB and CombUB
  5065. // base variables for the update
  5066. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  5067. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5068. isOpenMPDistributeDirective(DKind)) {
  5069. // LB + ST
  5070. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  5071. if (!NextLB.isUsable())
  5072. return 0;
  5073. // LB = LB + ST
  5074. NextLB =
  5075. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  5076. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  5077. if (!NextLB.isUsable())
  5078. return 0;
  5079. // UB + ST
  5080. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  5081. if (!NextUB.isUsable())
  5082. return 0;
  5083. // UB = UB + ST
  5084. NextUB =
  5085. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  5086. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  5087. if (!NextUB.isUsable())
  5088. return 0;
  5089. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5090. CombNextLB =
  5091. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  5092. if (!NextLB.isUsable())
  5093. return 0;
  5094. // LB = LB + ST
  5095. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  5096. CombNextLB.get());
  5097. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  5098. if (!CombNextLB.isUsable())
  5099. return 0;
  5100. // UB + ST
  5101. CombNextUB =
  5102. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  5103. if (!CombNextUB.isUsable())
  5104. return 0;
  5105. // UB = UB + ST
  5106. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  5107. CombNextUB.get());
  5108. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  5109. if (!CombNextUB.isUsable())
  5110. return 0;
  5111. }
  5112. }
  5113. // Create increment expression for distribute loop when combined in a same
  5114. // directive with for as IV = IV + ST; ensure upper bound expression based
  5115. // on PrevUB instead of NumIterations - used to implement 'for' when found
  5116. // in combination with 'distribute', like in 'distribute parallel for'
  5117. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  5118. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  5119. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5120. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  5121. assert(DistCond.isUsable() && "distribute cond expr was not built");
  5122. DistInc =
  5123. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  5124. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5125. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  5126. DistInc.get());
  5127. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  5128. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5129. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  5130. // construct
  5131. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  5132. ExprResult IsUBGreater =
  5133. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  5134. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5135. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  5136. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  5137. CondOp.get());
  5138. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  5139. // Build IV <= PrevUB to be used in parallel for is in combination with
  5140. // a distribute directive with schedule(static, 1)
  5141. ParForInDistCond =
  5142. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
  5143. }
  5144. // Build updates and final values of the loop counters.
  5145. bool HasErrors = false;
  5146. Built.Counters.resize(NestedLoopCount);
  5147. Built.Inits.resize(NestedLoopCount);
  5148. Built.Updates.resize(NestedLoopCount);
  5149. Built.Finals.resize(NestedLoopCount);
  5150. {
  5151. ExprResult Div;
  5152. // Go from inner nested loop to outer.
  5153. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  5154. LoopIterationSpace &IS = IterSpaces[Cnt];
  5155. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  5156. // Build: Iter = (IV / Div) % IS.NumIters
  5157. // where Div is product of previous iterations' IS.NumIters.
  5158. ExprResult Iter;
  5159. if (Div.isUsable()) {
  5160. Iter =
  5161. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  5162. } else {
  5163. Iter = IV;
  5164. assert((Cnt == (int)NestedLoopCount - 1) &&
  5165. "unusable div expected on first iteration only");
  5166. }
  5167. if (Cnt != 0 && Iter.isUsable())
  5168. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  5169. IS.NumIterations);
  5170. if (!Iter.isUsable()) {
  5171. HasErrors = true;
  5172. break;
  5173. }
  5174. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  5175. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  5176. DeclRefExpr *CounterVar = buildDeclRefExpr(
  5177. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  5178. /*RefersToCapture=*/true);
  5179. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  5180. IS.CounterInit, Captures);
  5181. if (!Init.isUsable()) {
  5182. HasErrors = true;
  5183. break;
  5184. }
  5185. ExprResult Update = buildCounterUpdate(
  5186. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  5187. IS.CounterStep, IS.Subtract, &Captures);
  5188. if (!Update.isUsable()) {
  5189. HasErrors = true;
  5190. break;
  5191. }
  5192. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  5193. ExprResult Final = buildCounterUpdate(
  5194. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  5195. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  5196. if (!Final.isUsable()) {
  5197. HasErrors = true;
  5198. break;
  5199. }
  5200. // Build Div for the next iteration: Div <- Div * IS.NumIters
  5201. if (Cnt != 0) {
  5202. if (Div.isUnset())
  5203. Div = IS.NumIterations;
  5204. else
  5205. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  5206. IS.NumIterations);
  5207. // Add parentheses (for debugging purposes only).
  5208. if (Div.isUsable())
  5209. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  5210. if (!Div.isUsable()) {
  5211. HasErrors = true;
  5212. break;
  5213. }
  5214. }
  5215. if (!Update.isUsable() || !Final.isUsable()) {
  5216. HasErrors = true;
  5217. break;
  5218. }
  5219. // Save results
  5220. Built.Counters[Cnt] = IS.CounterVar;
  5221. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  5222. Built.Inits[Cnt] = Init.get();
  5223. Built.Updates[Cnt] = Update.get();
  5224. Built.Finals[Cnt] = Final.get();
  5225. }
  5226. }
  5227. if (HasErrors)
  5228. return 0;
  5229. // Save results
  5230. Built.IterationVarRef = IV.get();
  5231. Built.LastIteration = LastIteration.get();
  5232. Built.NumIterations = NumIterations.get();
  5233. Built.CalcLastIteration =
  5234. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  5235. Built.PreCond = PreCond.get();
  5236. Built.PreInits = buildPreInits(C, Captures);
  5237. Built.Cond = Cond.get();
  5238. Built.Init = Init.get();
  5239. Built.Inc = Inc.get();
  5240. Built.LB = LB.get();
  5241. Built.UB = UB.get();
  5242. Built.IL = IL.get();
  5243. Built.ST = ST.get();
  5244. Built.EUB = EUB.get();
  5245. Built.NLB = NextLB.get();
  5246. Built.NUB = NextUB.get();
  5247. Built.PrevLB = PrevLB.get();
  5248. Built.PrevUB = PrevUB.get();
  5249. Built.DistInc = DistInc.get();
  5250. Built.PrevEUB = PrevEUB.get();
  5251. Built.DistCombinedFields.LB = CombLB.get();
  5252. Built.DistCombinedFields.UB = CombUB.get();
  5253. Built.DistCombinedFields.EUB = CombEUB.get();
  5254. Built.DistCombinedFields.Init = CombInit.get();
  5255. Built.DistCombinedFields.Cond = CombCond.get();
  5256. Built.DistCombinedFields.NLB = CombNextLB.get();
  5257. Built.DistCombinedFields.NUB = CombNextUB.get();
  5258. Built.DistCombinedFields.DistCond = CombDistCond.get();
  5259. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  5260. return NestedLoopCount;
  5261. }
  5262. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5263. auto CollapseClauses =
  5264. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  5265. if (CollapseClauses.begin() != CollapseClauses.end())
  5266. return (*CollapseClauses.begin())->getNumForLoops();
  5267. return nullptr;
  5268. }
  5269. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5270. auto OrderedClauses =
  5271. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  5272. if (OrderedClauses.begin() != OrderedClauses.end())
  5273. return (*OrderedClauses.begin())->getNumForLoops();
  5274. return nullptr;
  5275. }
  5276. static bool checkSimdlenSafelenSpecified(Sema &S,
  5277. const ArrayRef<OMPClause *> Clauses) {
  5278. const OMPSafelenClause *Safelen = nullptr;
  5279. const OMPSimdlenClause *Simdlen = nullptr;
  5280. for (const OMPClause *Clause : Clauses) {
  5281. if (Clause->getClauseKind() == OMPC_safelen)
  5282. Safelen = cast<OMPSafelenClause>(Clause);
  5283. else if (Clause->getClauseKind() == OMPC_simdlen)
  5284. Simdlen = cast<OMPSimdlenClause>(Clause);
  5285. if (Safelen && Simdlen)
  5286. break;
  5287. }
  5288. if (Simdlen && Safelen) {
  5289. llvm::APSInt SimdlenRes, SafelenRes;
  5290. const Expr *SimdlenLength = Simdlen->getSimdlen();
  5291. const Expr *SafelenLength = Safelen->getSafelen();
  5292. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  5293. SimdlenLength->isInstantiationDependent() ||
  5294. SimdlenLength->containsUnexpandedParameterPack())
  5295. return false;
  5296. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  5297. SafelenLength->isInstantiationDependent() ||
  5298. SafelenLength->containsUnexpandedParameterPack())
  5299. return false;
  5300. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  5301. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  5302. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5303. // If both simdlen and safelen clauses are specified, the value of the
  5304. // simdlen parameter must be less than or equal to the value of the safelen
  5305. // parameter.
  5306. if (SimdlenRes > SafelenRes) {
  5307. S.Diag(SimdlenLength->getExprLoc(),
  5308. diag::err_omp_wrong_simdlen_safelen_values)
  5309. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5310. return true;
  5311. }
  5312. }
  5313. return false;
  5314. }
  5315. StmtResult
  5316. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5317. SourceLocation StartLoc, SourceLocation EndLoc,
  5318. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5319. if (!AStmt)
  5320. return StmtError();
  5321. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5322. OMPLoopDirective::HelperExprs B;
  5323. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5324. // define the nested loops number.
  5325. unsigned NestedLoopCount = checkOpenMPLoop(
  5326. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5327. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5328. if (NestedLoopCount == 0)
  5329. return StmtError();
  5330. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5331. "omp simd loop exprs were not built");
  5332. if (!CurContext->isDependentContext()) {
  5333. // Finalize the clauses that need pre-built expressions for CodeGen.
  5334. for (OMPClause *C : Clauses) {
  5335. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5336. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5337. B.NumIterations, *this, CurScope,
  5338. DSAStack))
  5339. return StmtError();
  5340. }
  5341. }
  5342. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5343. return StmtError();
  5344. setFunctionHasBranchProtectedScope();
  5345. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5346. Clauses, AStmt, B);
  5347. }
  5348. StmtResult
  5349. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5350. SourceLocation StartLoc, SourceLocation EndLoc,
  5351. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5352. if (!AStmt)
  5353. return StmtError();
  5354. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5355. OMPLoopDirective::HelperExprs B;
  5356. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5357. // define the nested loops number.
  5358. unsigned NestedLoopCount = checkOpenMPLoop(
  5359. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5360. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5361. if (NestedLoopCount == 0)
  5362. return StmtError();
  5363. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5364. "omp for loop exprs were not built");
  5365. if (!CurContext->isDependentContext()) {
  5366. // Finalize the clauses that need pre-built expressions for CodeGen.
  5367. for (OMPClause *C : Clauses) {
  5368. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5369. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5370. B.NumIterations, *this, CurScope,
  5371. DSAStack))
  5372. return StmtError();
  5373. }
  5374. }
  5375. setFunctionHasBranchProtectedScope();
  5376. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5377. Clauses, AStmt, B, DSAStack->isCancelRegion());
  5378. }
  5379. StmtResult Sema::ActOnOpenMPForSimdDirective(
  5380. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5381. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5382. if (!AStmt)
  5383. return StmtError();
  5384. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5385. OMPLoopDirective::HelperExprs B;
  5386. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5387. // define the nested loops number.
  5388. unsigned NestedLoopCount =
  5389. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  5390. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5391. VarsWithImplicitDSA, B);
  5392. if (NestedLoopCount == 0)
  5393. return StmtError();
  5394. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5395. "omp for simd loop exprs were not built");
  5396. if (!CurContext->isDependentContext()) {
  5397. // Finalize the clauses that need pre-built expressions for CodeGen.
  5398. for (OMPClause *C : Clauses) {
  5399. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5400. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5401. B.NumIterations, *this, CurScope,
  5402. DSAStack))
  5403. return StmtError();
  5404. }
  5405. }
  5406. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5407. return StmtError();
  5408. setFunctionHasBranchProtectedScope();
  5409. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5410. Clauses, AStmt, B);
  5411. }
  5412. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5413. Stmt *AStmt,
  5414. SourceLocation StartLoc,
  5415. SourceLocation EndLoc) {
  5416. if (!AStmt)
  5417. return StmtError();
  5418. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5419. auto BaseStmt = AStmt;
  5420. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5421. BaseStmt = CS->getCapturedStmt();
  5422. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5423. auto S = C->children();
  5424. if (S.begin() == S.end())
  5425. return StmtError();
  5426. // All associated statements must be '#pragma omp section' except for
  5427. // the first one.
  5428. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5429. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5430. if (SectionStmt)
  5431. Diag(SectionStmt->getBeginLoc(),
  5432. diag::err_omp_sections_substmt_not_section);
  5433. return StmtError();
  5434. }
  5435. cast<OMPSectionDirective>(SectionStmt)
  5436. ->setHasCancel(DSAStack->isCancelRegion());
  5437. }
  5438. } else {
  5439. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  5440. return StmtError();
  5441. }
  5442. setFunctionHasBranchProtectedScope();
  5443. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5444. DSAStack->isCancelRegion());
  5445. }
  5446. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  5447. SourceLocation StartLoc,
  5448. SourceLocation EndLoc) {
  5449. if (!AStmt)
  5450. return StmtError();
  5451. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5452. setFunctionHasBranchProtectedScope();
  5453. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  5454. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  5455. DSAStack->isCancelRegion());
  5456. }
  5457. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  5458. Stmt *AStmt,
  5459. SourceLocation StartLoc,
  5460. SourceLocation EndLoc) {
  5461. if (!AStmt)
  5462. return StmtError();
  5463. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5464. setFunctionHasBranchProtectedScope();
  5465. // OpenMP [2.7.3, single Construct, Restrictions]
  5466. // The copyprivate clause must not be used with the nowait clause.
  5467. const OMPClause *Nowait = nullptr;
  5468. const OMPClause *Copyprivate = nullptr;
  5469. for (const OMPClause *Clause : Clauses) {
  5470. if (Clause->getClauseKind() == OMPC_nowait)
  5471. Nowait = Clause;
  5472. else if (Clause->getClauseKind() == OMPC_copyprivate)
  5473. Copyprivate = Clause;
  5474. if (Copyprivate && Nowait) {
  5475. Diag(Copyprivate->getBeginLoc(),
  5476. diag::err_omp_single_copyprivate_with_nowait);
  5477. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  5478. return StmtError();
  5479. }
  5480. }
  5481. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5482. }
  5483. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  5484. SourceLocation StartLoc,
  5485. SourceLocation EndLoc) {
  5486. if (!AStmt)
  5487. return StmtError();
  5488. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5489. setFunctionHasBranchProtectedScope();
  5490. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  5491. }
  5492. StmtResult Sema::ActOnOpenMPCriticalDirective(
  5493. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  5494. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5495. if (!AStmt)
  5496. return StmtError();
  5497. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5498. bool ErrorFound = false;
  5499. llvm::APSInt Hint;
  5500. SourceLocation HintLoc;
  5501. bool DependentHint = false;
  5502. for (const OMPClause *C : Clauses) {
  5503. if (C->getClauseKind() == OMPC_hint) {
  5504. if (!DirName.getName()) {
  5505. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  5506. ErrorFound = true;
  5507. }
  5508. Expr *E = cast<OMPHintClause>(C)->getHint();
  5509. if (E->isTypeDependent() || E->isValueDependent() ||
  5510. E->isInstantiationDependent()) {
  5511. DependentHint = true;
  5512. } else {
  5513. Hint = E->EvaluateKnownConstInt(Context);
  5514. HintLoc = C->getBeginLoc();
  5515. }
  5516. }
  5517. }
  5518. if (ErrorFound)
  5519. return StmtError();
  5520. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  5521. if (Pair.first && DirName.getName() && !DependentHint) {
  5522. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  5523. Diag(StartLoc, diag::err_omp_critical_with_hint);
  5524. if (HintLoc.isValid())
  5525. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5526. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5527. else
  5528. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5529. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5530. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  5531. << 1
  5532. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5533. /*Radix=*/10, /*Signed=*/false);
  5534. } else {
  5535. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  5536. }
  5537. }
  5538. }
  5539. setFunctionHasBranchProtectedScope();
  5540. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5541. Clauses, AStmt);
  5542. if (!Pair.first && DirName.getName() && !DependentHint)
  5543. DSAStack->addCriticalWithHint(Dir, Hint);
  5544. return Dir;
  5545. }
  5546. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5547. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5548. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5549. if (!AStmt)
  5550. return StmtError();
  5551. auto *CS = cast<CapturedStmt>(AStmt);
  5552. // 1.2.2 OpenMP Language Terminology
  5553. // Structured block - An executable statement with a single entry at the
  5554. // top and a single exit at the bottom.
  5555. // The point of exit cannot be a branch out of the structured block.
  5556. // longjmp() and throw() must not violate the entry/exit criteria.
  5557. CS->getCapturedDecl()->setNothrow();
  5558. OMPLoopDirective::HelperExprs B;
  5559. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5560. // define the nested loops number.
  5561. unsigned NestedLoopCount =
  5562. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5563. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5564. VarsWithImplicitDSA, B);
  5565. if (NestedLoopCount == 0)
  5566. return StmtError();
  5567. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5568. "omp parallel for loop exprs were not built");
  5569. if (!CurContext->isDependentContext()) {
  5570. // Finalize the clauses that need pre-built expressions for CodeGen.
  5571. for (OMPClause *C : Clauses) {
  5572. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5573. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5574. B.NumIterations, *this, CurScope,
  5575. DSAStack))
  5576. return StmtError();
  5577. }
  5578. }
  5579. setFunctionHasBranchProtectedScope();
  5580. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5581. NestedLoopCount, Clauses, AStmt, B,
  5582. DSAStack->isCancelRegion());
  5583. }
  5584. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5585. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5586. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5587. if (!AStmt)
  5588. return StmtError();
  5589. auto *CS = cast<CapturedStmt>(AStmt);
  5590. // 1.2.2 OpenMP Language Terminology
  5591. // Structured block - An executable statement with a single entry at the
  5592. // top and a single exit at the bottom.
  5593. // The point of exit cannot be a branch out of the structured block.
  5594. // longjmp() and throw() must not violate the entry/exit criteria.
  5595. CS->getCapturedDecl()->setNothrow();
  5596. OMPLoopDirective::HelperExprs B;
  5597. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5598. // define the nested loops number.
  5599. unsigned NestedLoopCount =
  5600. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5601. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5602. VarsWithImplicitDSA, B);
  5603. if (NestedLoopCount == 0)
  5604. return StmtError();
  5605. if (!CurContext->isDependentContext()) {
  5606. // Finalize the clauses that need pre-built expressions for CodeGen.
  5607. for (OMPClause *C : Clauses) {
  5608. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5609. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5610. B.NumIterations, *this, CurScope,
  5611. DSAStack))
  5612. return StmtError();
  5613. }
  5614. }
  5615. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5616. return StmtError();
  5617. setFunctionHasBranchProtectedScope();
  5618. return OMPParallelForSimdDirective::Create(
  5619. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5620. }
  5621. StmtResult
  5622. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5623. Stmt *AStmt, SourceLocation StartLoc,
  5624. SourceLocation EndLoc) {
  5625. if (!AStmt)
  5626. return StmtError();
  5627. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5628. auto BaseStmt = AStmt;
  5629. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5630. BaseStmt = CS->getCapturedStmt();
  5631. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5632. auto S = C->children();
  5633. if (S.begin() == S.end())
  5634. return StmtError();
  5635. // All associated statements must be '#pragma omp section' except for
  5636. // the first one.
  5637. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5638. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5639. if (SectionStmt)
  5640. Diag(SectionStmt->getBeginLoc(),
  5641. diag::err_omp_parallel_sections_substmt_not_section);
  5642. return StmtError();
  5643. }
  5644. cast<OMPSectionDirective>(SectionStmt)
  5645. ->setHasCancel(DSAStack->isCancelRegion());
  5646. }
  5647. } else {
  5648. Diag(AStmt->getBeginLoc(),
  5649. diag::err_omp_parallel_sections_not_compound_stmt);
  5650. return StmtError();
  5651. }
  5652. setFunctionHasBranchProtectedScope();
  5653. return OMPParallelSectionsDirective::Create(
  5654. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5655. }
  5656. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5657. Stmt *AStmt, SourceLocation StartLoc,
  5658. SourceLocation EndLoc) {
  5659. if (!AStmt)
  5660. return StmtError();
  5661. auto *CS = cast<CapturedStmt>(AStmt);
  5662. // 1.2.2 OpenMP Language Terminology
  5663. // Structured block - An executable statement with a single entry at the
  5664. // top and a single exit at the bottom.
  5665. // The point of exit cannot be a branch out of the structured block.
  5666. // longjmp() and throw() must not violate the entry/exit criteria.
  5667. CS->getCapturedDecl()->setNothrow();
  5668. setFunctionHasBranchProtectedScope();
  5669. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5670. DSAStack->isCancelRegion());
  5671. }
  5672. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5673. SourceLocation EndLoc) {
  5674. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5675. }
  5676. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5677. SourceLocation EndLoc) {
  5678. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5679. }
  5680. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5681. SourceLocation EndLoc) {
  5682. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5683. }
  5684. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5685. Stmt *AStmt,
  5686. SourceLocation StartLoc,
  5687. SourceLocation EndLoc) {
  5688. if (!AStmt)
  5689. return StmtError();
  5690. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5691. setFunctionHasBranchProtectedScope();
  5692. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5693. AStmt,
  5694. DSAStack->getTaskgroupReductionRef());
  5695. }
  5696. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5697. SourceLocation StartLoc,
  5698. SourceLocation EndLoc) {
  5699. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5700. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5701. }
  5702. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5703. Stmt *AStmt,
  5704. SourceLocation StartLoc,
  5705. SourceLocation EndLoc) {
  5706. const OMPClause *DependFound = nullptr;
  5707. const OMPClause *DependSourceClause = nullptr;
  5708. const OMPClause *DependSinkClause = nullptr;
  5709. bool ErrorFound = false;
  5710. const OMPThreadsClause *TC = nullptr;
  5711. const OMPSIMDClause *SC = nullptr;
  5712. for (const OMPClause *C : Clauses) {
  5713. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5714. DependFound = C;
  5715. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5716. if (DependSourceClause) {
  5717. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  5718. << getOpenMPDirectiveName(OMPD_ordered)
  5719. << getOpenMPClauseName(OMPC_depend) << 2;
  5720. ErrorFound = true;
  5721. } else {
  5722. DependSourceClause = C;
  5723. }
  5724. if (DependSinkClause) {
  5725. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5726. << 0;
  5727. ErrorFound = true;
  5728. }
  5729. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5730. if (DependSourceClause) {
  5731. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5732. << 1;
  5733. ErrorFound = true;
  5734. }
  5735. DependSinkClause = C;
  5736. }
  5737. } else if (C->getClauseKind() == OMPC_threads) {
  5738. TC = cast<OMPThreadsClause>(C);
  5739. } else if (C->getClauseKind() == OMPC_simd) {
  5740. SC = cast<OMPSIMDClause>(C);
  5741. }
  5742. }
  5743. if (!ErrorFound && !SC &&
  5744. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5745. // OpenMP [2.8.1,simd Construct, Restrictions]
  5746. // An ordered construct with the simd clause is the only OpenMP construct
  5747. // that can appear in the simd region.
  5748. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5749. ErrorFound = true;
  5750. } else if (DependFound && (TC || SC)) {
  5751. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  5752. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5753. ErrorFound = true;
  5754. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  5755. Diag(DependFound->getBeginLoc(),
  5756. diag::err_omp_ordered_directive_without_param);
  5757. ErrorFound = true;
  5758. } else if (TC || Clauses.empty()) {
  5759. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  5760. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  5761. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5762. << (TC != nullptr);
  5763. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  5764. ErrorFound = true;
  5765. }
  5766. }
  5767. if ((!AStmt && !DependFound) || ErrorFound)
  5768. return StmtError();
  5769. if (AStmt) {
  5770. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5771. setFunctionHasBranchProtectedScope();
  5772. }
  5773. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5774. }
  5775. namespace {
  5776. /// Helper class for checking expression in 'omp atomic [update]'
  5777. /// construct.
  5778. class OpenMPAtomicUpdateChecker {
  5779. /// Error results for atomic update expressions.
  5780. enum ExprAnalysisErrorCode {
  5781. /// A statement is not an expression statement.
  5782. NotAnExpression,
  5783. /// Expression is not builtin binary or unary operation.
  5784. NotABinaryOrUnaryExpression,
  5785. /// Unary operation is not post-/pre- increment/decrement operation.
  5786. NotAnUnaryIncDecExpression,
  5787. /// An expression is not of scalar type.
  5788. NotAScalarType,
  5789. /// A binary operation is not an assignment operation.
  5790. NotAnAssignmentOp,
  5791. /// RHS part of the binary operation is not a binary expression.
  5792. NotABinaryExpression,
  5793. /// RHS part is not additive/multiplicative/shift/biwise binary
  5794. /// expression.
  5795. NotABinaryOperator,
  5796. /// RHS binary operation does not have reference to the updated LHS
  5797. /// part.
  5798. NotAnUpdateExpression,
  5799. /// No errors is found.
  5800. NoError
  5801. };
  5802. /// Reference to Sema.
  5803. Sema &SemaRef;
  5804. /// A location for note diagnostics (when error is found).
  5805. SourceLocation NoteLoc;
  5806. /// 'x' lvalue part of the source atomic expression.
  5807. Expr *X;
  5808. /// 'expr' rvalue part of the source atomic expression.
  5809. Expr *E;
  5810. /// Helper expression of the form
  5811. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5812. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5813. Expr *UpdateExpr;
  5814. /// Is 'x' a LHS in a RHS part of full update expression. It is
  5815. /// important for non-associative operations.
  5816. bool IsXLHSInRHSPart;
  5817. BinaryOperatorKind Op;
  5818. SourceLocation OpLoc;
  5819. /// true if the source expression is a postfix unary operation, false
  5820. /// if it is a prefix unary operation.
  5821. bool IsPostfixUpdate;
  5822. public:
  5823. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5824. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5825. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5826. /// Check specified statement that it is suitable for 'atomic update'
  5827. /// constructs and extract 'x', 'expr' and Operation from the original
  5828. /// expression. If DiagId and NoteId == 0, then only check is performed
  5829. /// without error notification.
  5830. /// \param DiagId Diagnostic which should be emitted if error is found.
  5831. /// \param NoteId Diagnostic note for the main error message.
  5832. /// \return true if statement is not an update expression, false otherwise.
  5833. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5834. /// Return the 'x' lvalue part of the source atomic expression.
  5835. Expr *getX() const { return X; }
  5836. /// Return the 'expr' rvalue part of the source atomic expression.
  5837. Expr *getExpr() const { return E; }
  5838. /// Return the update expression used in calculation of the updated
  5839. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5840. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5841. Expr *getUpdateExpr() const { return UpdateExpr; }
  5842. /// Return true if 'x' is LHS in RHS part of full update expression,
  5843. /// false otherwise.
  5844. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5845. /// true if the source expression is a postfix unary operation, false
  5846. /// if it is a prefix unary operation.
  5847. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5848. private:
  5849. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5850. unsigned NoteId = 0);
  5851. };
  5852. } // namespace
  5853. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5854. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5855. ExprAnalysisErrorCode ErrorFound = NoError;
  5856. SourceLocation ErrorLoc, NoteLoc;
  5857. SourceRange ErrorRange, NoteRange;
  5858. // Allowed constructs are:
  5859. // x = x binop expr;
  5860. // x = expr binop x;
  5861. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5862. X = AtomicBinOp->getLHS();
  5863. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5864. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5865. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5866. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5867. AtomicInnerBinOp->isBitwiseOp()) {
  5868. Op = AtomicInnerBinOp->getOpcode();
  5869. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5870. Expr *LHS = AtomicInnerBinOp->getLHS();
  5871. Expr *RHS = AtomicInnerBinOp->getRHS();
  5872. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5873. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5874. /*Canonical=*/true);
  5875. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5876. /*Canonical=*/true);
  5877. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5878. /*Canonical=*/true);
  5879. if (XId == LHSId) {
  5880. E = RHS;
  5881. IsXLHSInRHSPart = true;
  5882. } else if (XId == RHSId) {
  5883. E = LHS;
  5884. IsXLHSInRHSPart = false;
  5885. } else {
  5886. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5887. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5888. NoteLoc = X->getExprLoc();
  5889. NoteRange = X->getSourceRange();
  5890. ErrorFound = NotAnUpdateExpression;
  5891. }
  5892. } else {
  5893. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5894. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5895. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5896. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5897. ErrorFound = NotABinaryOperator;
  5898. }
  5899. } else {
  5900. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5901. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5902. ErrorFound = NotABinaryExpression;
  5903. }
  5904. } else {
  5905. ErrorLoc = AtomicBinOp->getExprLoc();
  5906. ErrorRange = AtomicBinOp->getSourceRange();
  5907. NoteLoc = AtomicBinOp->getOperatorLoc();
  5908. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5909. ErrorFound = NotAnAssignmentOp;
  5910. }
  5911. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5912. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5913. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5914. return true;
  5915. }
  5916. if (SemaRef.CurContext->isDependentContext())
  5917. E = X = UpdateExpr = nullptr;
  5918. return ErrorFound != NoError;
  5919. }
  5920. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5921. unsigned NoteId) {
  5922. ExprAnalysisErrorCode ErrorFound = NoError;
  5923. SourceLocation ErrorLoc, NoteLoc;
  5924. SourceRange ErrorRange, NoteRange;
  5925. // Allowed constructs are:
  5926. // x++;
  5927. // x--;
  5928. // ++x;
  5929. // --x;
  5930. // x binop= expr;
  5931. // x = x binop expr;
  5932. // x = expr binop x;
  5933. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5934. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5935. if (AtomicBody->getType()->isScalarType() ||
  5936. AtomicBody->isInstantiationDependent()) {
  5937. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5938. AtomicBody->IgnoreParenImpCasts())) {
  5939. // Check for Compound Assignment Operation
  5940. Op = BinaryOperator::getOpForCompoundAssignment(
  5941. AtomicCompAssignOp->getOpcode());
  5942. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5943. E = AtomicCompAssignOp->getRHS();
  5944. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5945. IsXLHSInRHSPart = true;
  5946. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5947. AtomicBody->IgnoreParenImpCasts())) {
  5948. // Check for Binary Operation
  5949. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5950. return true;
  5951. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5952. AtomicBody->IgnoreParenImpCasts())) {
  5953. // Check for Unary Operation
  5954. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5955. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5956. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5957. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5958. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5959. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5960. IsXLHSInRHSPart = true;
  5961. } else {
  5962. ErrorFound = NotAnUnaryIncDecExpression;
  5963. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5964. ErrorRange = AtomicUnaryOp->getSourceRange();
  5965. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5966. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5967. }
  5968. } else if (!AtomicBody->isInstantiationDependent()) {
  5969. ErrorFound = NotABinaryOrUnaryExpression;
  5970. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5971. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5972. }
  5973. } else {
  5974. ErrorFound = NotAScalarType;
  5975. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  5976. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5977. }
  5978. } else {
  5979. ErrorFound = NotAnExpression;
  5980. NoteLoc = ErrorLoc = S->getBeginLoc();
  5981. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5982. }
  5983. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5984. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5985. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5986. return true;
  5987. }
  5988. if (SemaRef.CurContext->isDependentContext())
  5989. E = X = UpdateExpr = nullptr;
  5990. if (ErrorFound == NoError && E && X) {
  5991. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5992. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5993. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5994. auto *OVEX = new (SemaRef.getASTContext())
  5995. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5996. auto *OVEExpr = new (SemaRef.getASTContext())
  5997. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5998. ExprResult Update =
  5999. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6000. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6001. if (Update.isInvalid())
  6002. return true;
  6003. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  6004. Sema::AA_Casting);
  6005. if (Update.isInvalid())
  6006. return true;
  6007. UpdateExpr = Update.get();
  6008. }
  6009. return ErrorFound != NoError;
  6010. }
  6011. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  6012. Stmt *AStmt,
  6013. SourceLocation StartLoc,
  6014. SourceLocation EndLoc) {
  6015. if (!AStmt)
  6016. return StmtError();
  6017. auto *CS = cast<CapturedStmt>(AStmt);
  6018. // 1.2.2 OpenMP Language Terminology
  6019. // Structured block - An executable statement with a single entry at the
  6020. // top and a single exit at the bottom.
  6021. // The point of exit cannot be a branch out of the structured block.
  6022. // longjmp() and throw() must not violate the entry/exit criteria.
  6023. OpenMPClauseKind AtomicKind = OMPC_unknown;
  6024. SourceLocation AtomicKindLoc;
  6025. for (const OMPClause *C : Clauses) {
  6026. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  6027. C->getClauseKind() == OMPC_update ||
  6028. C->getClauseKind() == OMPC_capture) {
  6029. if (AtomicKind != OMPC_unknown) {
  6030. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  6031. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  6032. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  6033. << getOpenMPClauseName(AtomicKind);
  6034. } else {
  6035. AtomicKind = C->getClauseKind();
  6036. AtomicKindLoc = C->getBeginLoc();
  6037. }
  6038. }
  6039. }
  6040. Stmt *Body = CS->getCapturedStmt();
  6041. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  6042. Body = EWC->getSubExpr();
  6043. Expr *X = nullptr;
  6044. Expr *V = nullptr;
  6045. Expr *E = nullptr;
  6046. Expr *UE = nullptr;
  6047. bool IsXLHSInRHSPart = false;
  6048. bool IsPostfixUpdate = false;
  6049. // OpenMP [2.12.6, atomic Construct]
  6050. // In the next expressions:
  6051. // * x and v (as applicable) are both l-value expressions with scalar type.
  6052. // * During the execution of an atomic region, multiple syntactic
  6053. // occurrences of x must designate the same storage location.
  6054. // * Neither of v and expr (as applicable) may access the storage location
  6055. // designated by x.
  6056. // * Neither of x and expr (as applicable) may access the storage location
  6057. // designated by v.
  6058. // * expr is an expression with scalar type.
  6059. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  6060. // * binop, binop=, ++, and -- are not overloaded operators.
  6061. // * The expression x binop expr must be numerically equivalent to x binop
  6062. // (expr). This requirement is satisfied if the operators in expr have
  6063. // precedence greater than binop, or by using parentheses around expr or
  6064. // subexpressions of expr.
  6065. // * The expression expr binop x must be numerically equivalent to (expr)
  6066. // binop x. This requirement is satisfied if the operators in expr have
  6067. // precedence equal to or greater than binop, or by using parentheses around
  6068. // expr or subexpressions of expr.
  6069. // * For forms that allow multiple occurrences of x, the number of times
  6070. // that x is evaluated is unspecified.
  6071. if (AtomicKind == OMPC_read) {
  6072. enum {
  6073. NotAnExpression,
  6074. NotAnAssignmentOp,
  6075. NotAScalarType,
  6076. NotAnLValue,
  6077. NoError
  6078. } ErrorFound = NoError;
  6079. SourceLocation ErrorLoc, NoteLoc;
  6080. SourceRange ErrorRange, NoteRange;
  6081. // If clause is read:
  6082. // v = x;
  6083. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6084. const auto *AtomicBinOp =
  6085. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6086. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6087. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6088. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  6089. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6090. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  6091. if (!X->isLValue() || !V->isLValue()) {
  6092. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  6093. ErrorFound = NotAnLValue;
  6094. ErrorLoc = AtomicBinOp->getExprLoc();
  6095. ErrorRange = AtomicBinOp->getSourceRange();
  6096. NoteLoc = NotLValueExpr->getExprLoc();
  6097. NoteRange = NotLValueExpr->getSourceRange();
  6098. }
  6099. } else if (!X->isInstantiationDependent() ||
  6100. !V->isInstantiationDependent()) {
  6101. const Expr *NotScalarExpr =
  6102. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6103. ? V
  6104. : X;
  6105. ErrorFound = NotAScalarType;
  6106. ErrorLoc = AtomicBinOp->getExprLoc();
  6107. ErrorRange = AtomicBinOp->getSourceRange();
  6108. NoteLoc = NotScalarExpr->getExprLoc();
  6109. NoteRange = NotScalarExpr->getSourceRange();
  6110. }
  6111. } else if (!AtomicBody->isInstantiationDependent()) {
  6112. ErrorFound = NotAnAssignmentOp;
  6113. ErrorLoc = AtomicBody->getExprLoc();
  6114. ErrorRange = AtomicBody->getSourceRange();
  6115. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6116. : AtomicBody->getExprLoc();
  6117. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6118. : AtomicBody->getSourceRange();
  6119. }
  6120. } else {
  6121. ErrorFound = NotAnExpression;
  6122. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6123. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6124. }
  6125. if (ErrorFound != NoError) {
  6126. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  6127. << ErrorRange;
  6128. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6129. << NoteRange;
  6130. return StmtError();
  6131. }
  6132. if (CurContext->isDependentContext())
  6133. V = X = nullptr;
  6134. } else if (AtomicKind == OMPC_write) {
  6135. enum {
  6136. NotAnExpression,
  6137. NotAnAssignmentOp,
  6138. NotAScalarType,
  6139. NotAnLValue,
  6140. NoError
  6141. } ErrorFound = NoError;
  6142. SourceLocation ErrorLoc, NoteLoc;
  6143. SourceRange ErrorRange, NoteRange;
  6144. // If clause is write:
  6145. // x = expr;
  6146. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6147. const auto *AtomicBinOp =
  6148. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6149. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6150. X = AtomicBinOp->getLHS();
  6151. E = AtomicBinOp->getRHS();
  6152. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6153. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  6154. if (!X->isLValue()) {
  6155. ErrorFound = NotAnLValue;
  6156. ErrorLoc = AtomicBinOp->getExprLoc();
  6157. ErrorRange = AtomicBinOp->getSourceRange();
  6158. NoteLoc = X->getExprLoc();
  6159. NoteRange = X->getSourceRange();
  6160. }
  6161. } else if (!X->isInstantiationDependent() ||
  6162. !E->isInstantiationDependent()) {
  6163. const Expr *NotScalarExpr =
  6164. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6165. ? E
  6166. : X;
  6167. ErrorFound = NotAScalarType;
  6168. ErrorLoc = AtomicBinOp->getExprLoc();
  6169. ErrorRange = AtomicBinOp->getSourceRange();
  6170. NoteLoc = NotScalarExpr->getExprLoc();
  6171. NoteRange = NotScalarExpr->getSourceRange();
  6172. }
  6173. } else if (!AtomicBody->isInstantiationDependent()) {
  6174. ErrorFound = NotAnAssignmentOp;
  6175. ErrorLoc = AtomicBody->getExprLoc();
  6176. ErrorRange = AtomicBody->getSourceRange();
  6177. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6178. : AtomicBody->getExprLoc();
  6179. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6180. : AtomicBody->getSourceRange();
  6181. }
  6182. } else {
  6183. ErrorFound = NotAnExpression;
  6184. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6185. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6186. }
  6187. if (ErrorFound != NoError) {
  6188. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  6189. << ErrorRange;
  6190. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6191. << NoteRange;
  6192. return StmtError();
  6193. }
  6194. if (CurContext->isDependentContext())
  6195. E = X = nullptr;
  6196. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  6197. // If clause is update:
  6198. // x++;
  6199. // x--;
  6200. // ++x;
  6201. // --x;
  6202. // x binop= expr;
  6203. // x = x binop expr;
  6204. // x = expr binop x;
  6205. OpenMPAtomicUpdateChecker Checker(*this);
  6206. if (Checker.checkStatement(
  6207. Body, (AtomicKind == OMPC_update)
  6208. ? diag::err_omp_atomic_update_not_expression_statement
  6209. : diag::err_omp_atomic_not_expression_statement,
  6210. diag::note_omp_atomic_update))
  6211. return StmtError();
  6212. if (!CurContext->isDependentContext()) {
  6213. E = Checker.getExpr();
  6214. X = Checker.getX();
  6215. UE = Checker.getUpdateExpr();
  6216. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6217. }
  6218. } else if (AtomicKind == OMPC_capture) {
  6219. enum {
  6220. NotAnAssignmentOp,
  6221. NotACompoundStatement,
  6222. NotTwoSubstatements,
  6223. NotASpecificExpression,
  6224. NoError
  6225. } ErrorFound = NoError;
  6226. SourceLocation ErrorLoc, NoteLoc;
  6227. SourceRange ErrorRange, NoteRange;
  6228. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6229. // If clause is a capture:
  6230. // v = x++;
  6231. // v = x--;
  6232. // v = ++x;
  6233. // v = --x;
  6234. // v = x binop= expr;
  6235. // v = x = x binop expr;
  6236. // v = x = expr binop x;
  6237. const auto *AtomicBinOp =
  6238. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6239. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6240. V = AtomicBinOp->getLHS();
  6241. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6242. OpenMPAtomicUpdateChecker Checker(*this);
  6243. if (Checker.checkStatement(
  6244. Body, diag::err_omp_atomic_capture_not_expression_statement,
  6245. diag::note_omp_atomic_update))
  6246. return StmtError();
  6247. E = Checker.getExpr();
  6248. X = Checker.getX();
  6249. UE = Checker.getUpdateExpr();
  6250. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6251. IsPostfixUpdate = Checker.isPostfixUpdate();
  6252. } else if (!AtomicBody->isInstantiationDependent()) {
  6253. ErrorLoc = AtomicBody->getExprLoc();
  6254. ErrorRange = AtomicBody->getSourceRange();
  6255. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6256. : AtomicBody->getExprLoc();
  6257. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6258. : AtomicBody->getSourceRange();
  6259. ErrorFound = NotAnAssignmentOp;
  6260. }
  6261. if (ErrorFound != NoError) {
  6262. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  6263. << ErrorRange;
  6264. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6265. return StmtError();
  6266. }
  6267. if (CurContext->isDependentContext())
  6268. UE = V = E = X = nullptr;
  6269. } else {
  6270. // If clause is a capture:
  6271. // { v = x; x = expr; }
  6272. // { v = x; x++; }
  6273. // { v = x; x--; }
  6274. // { v = x; ++x; }
  6275. // { v = x; --x; }
  6276. // { v = x; x binop= expr; }
  6277. // { v = x; x = x binop expr; }
  6278. // { v = x; x = expr binop x; }
  6279. // { x++; v = x; }
  6280. // { x--; v = x; }
  6281. // { ++x; v = x; }
  6282. // { --x; v = x; }
  6283. // { x binop= expr; v = x; }
  6284. // { x = x binop expr; v = x; }
  6285. // { x = expr binop x; v = x; }
  6286. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  6287. // Check that this is { expr1; expr2; }
  6288. if (CS->size() == 2) {
  6289. Stmt *First = CS->body_front();
  6290. Stmt *Second = CS->body_back();
  6291. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  6292. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  6293. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  6294. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  6295. // Need to find what subexpression is 'v' and what is 'x'.
  6296. OpenMPAtomicUpdateChecker Checker(*this);
  6297. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6298. BinaryOperator *BinOp = nullptr;
  6299. if (IsUpdateExprFound) {
  6300. BinOp = dyn_cast<BinaryOperator>(First);
  6301. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6302. }
  6303. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6304. // { v = x; x++; }
  6305. // { v = x; x--; }
  6306. // { v = x; ++x; }
  6307. // { v = x; --x; }
  6308. // { v = x; x binop= expr; }
  6309. // { v = x; x = x binop expr; }
  6310. // { v = x; x = expr binop x; }
  6311. // Check that the first expression has form v = x.
  6312. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6313. llvm::FoldingSetNodeID XId, PossibleXId;
  6314. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6315. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6316. IsUpdateExprFound = XId == PossibleXId;
  6317. if (IsUpdateExprFound) {
  6318. V = BinOp->getLHS();
  6319. X = Checker.getX();
  6320. E = Checker.getExpr();
  6321. UE = Checker.getUpdateExpr();
  6322. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6323. IsPostfixUpdate = true;
  6324. }
  6325. }
  6326. if (!IsUpdateExprFound) {
  6327. IsUpdateExprFound = !Checker.checkStatement(First);
  6328. BinOp = nullptr;
  6329. if (IsUpdateExprFound) {
  6330. BinOp = dyn_cast<BinaryOperator>(Second);
  6331. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6332. }
  6333. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6334. // { x++; v = x; }
  6335. // { x--; v = x; }
  6336. // { ++x; v = x; }
  6337. // { --x; v = x; }
  6338. // { x binop= expr; v = x; }
  6339. // { x = x binop expr; v = x; }
  6340. // { x = expr binop x; v = x; }
  6341. // Check that the second expression has form v = x.
  6342. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6343. llvm::FoldingSetNodeID XId, PossibleXId;
  6344. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6345. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6346. IsUpdateExprFound = XId == PossibleXId;
  6347. if (IsUpdateExprFound) {
  6348. V = BinOp->getLHS();
  6349. X = Checker.getX();
  6350. E = Checker.getExpr();
  6351. UE = Checker.getUpdateExpr();
  6352. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6353. IsPostfixUpdate = false;
  6354. }
  6355. }
  6356. }
  6357. if (!IsUpdateExprFound) {
  6358. // { v = x; x = expr; }
  6359. auto *FirstExpr = dyn_cast<Expr>(First);
  6360. auto *SecondExpr = dyn_cast<Expr>(Second);
  6361. if (!FirstExpr || !SecondExpr ||
  6362. !(FirstExpr->isInstantiationDependent() ||
  6363. SecondExpr->isInstantiationDependent())) {
  6364. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6365. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6366. ErrorFound = NotAnAssignmentOp;
  6367. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6368. : First->getBeginLoc();
  6369. NoteRange = ErrorRange = FirstBinOp
  6370. ? FirstBinOp->getSourceRange()
  6371. : SourceRange(ErrorLoc, ErrorLoc);
  6372. } else {
  6373. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  6374. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  6375. ErrorFound = NotAnAssignmentOp;
  6376. NoteLoc = ErrorLoc = SecondBinOp
  6377. ? SecondBinOp->getOperatorLoc()
  6378. : Second->getBeginLoc();
  6379. NoteRange = ErrorRange =
  6380. SecondBinOp ? SecondBinOp->getSourceRange()
  6381. : SourceRange(ErrorLoc, ErrorLoc);
  6382. } else {
  6383. Expr *PossibleXRHSInFirst =
  6384. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  6385. Expr *PossibleXLHSInSecond =
  6386. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  6387. llvm::FoldingSetNodeID X1Id, X2Id;
  6388. PossibleXRHSInFirst->Profile(X1Id, Context,
  6389. /*Canonical=*/true);
  6390. PossibleXLHSInSecond->Profile(X2Id, Context,
  6391. /*Canonical=*/true);
  6392. IsUpdateExprFound = X1Id == X2Id;
  6393. if (IsUpdateExprFound) {
  6394. V = FirstBinOp->getLHS();
  6395. X = SecondBinOp->getLHS();
  6396. E = SecondBinOp->getRHS();
  6397. UE = nullptr;
  6398. IsXLHSInRHSPart = false;
  6399. IsPostfixUpdate = true;
  6400. } else {
  6401. ErrorFound = NotASpecificExpression;
  6402. ErrorLoc = FirstBinOp->getExprLoc();
  6403. ErrorRange = FirstBinOp->getSourceRange();
  6404. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  6405. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  6406. }
  6407. }
  6408. }
  6409. }
  6410. }
  6411. } else {
  6412. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6413. NoteRange = ErrorRange =
  6414. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6415. ErrorFound = NotTwoSubstatements;
  6416. }
  6417. } else {
  6418. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6419. NoteRange = ErrorRange =
  6420. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6421. ErrorFound = NotACompoundStatement;
  6422. }
  6423. if (ErrorFound != NoError) {
  6424. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  6425. << ErrorRange;
  6426. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6427. return StmtError();
  6428. }
  6429. if (CurContext->isDependentContext())
  6430. UE = V = E = X = nullptr;
  6431. }
  6432. }
  6433. setFunctionHasBranchProtectedScope();
  6434. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6435. X, V, E, UE, IsXLHSInRHSPart,
  6436. IsPostfixUpdate);
  6437. }
  6438. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  6439. Stmt *AStmt,
  6440. SourceLocation StartLoc,
  6441. SourceLocation EndLoc) {
  6442. if (!AStmt)
  6443. return StmtError();
  6444. auto *CS = cast<CapturedStmt>(AStmt);
  6445. // 1.2.2 OpenMP Language Terminology
  6446. // Structured block - An executable statement with a single entry at the
  6447. // top and a single exit at the bottom.
  6448. // The point of exit cannot be a branch out of the structured block.
  6449. // longjmp() and throw() must not violate the entry/exit criteria.
  6450. CS->getCapturedDecl()->setNothrow();
  6451. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  6452. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6453. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6454. // 1.2.2 OpenMP Language Terminology
  6455. // Structured block - An executable statement with a single entry at the
  6456. // top and a single exit at the bottom.
  6457. // The point of exit cannot be a branch out of the structured block.
  6458. // longjmp() and throw() must not violate the entry/exit criteria.
  6459. CS->getCapturedDecl()->setNothrow();
  6460. }
  6461. // OpenMP [2.16, Nesting of Regions]
  6462. // If specified, a teams construct must be contained within a target
  6463. // construct. That target construct must contain no statements or directives
  6464. // outside of the teams construct.
  6465. if (DSAStack->hasInnerTeamsRegion()) {
  6466. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  6467. bool OMPTeamsFound = true;
  6468. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  6469. auto I = CS->body_begin();
  6470. while (I != CS->body_end()) {
  6471. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  6472. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  6473. OMPTeamsFound = false;
  6474. break;
  6475. }
  6476. ++I;
  6477. }
  6478. assert(I != CS->body_end() && "Not found statement");
  6479. S = *I;
  6480. } else {
  6481. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  6482. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  6483. }
  6484. if (!OMPTeamsFound) {
  6485. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  6486. Diag(DSAStack->getInnerTeamsRegionLoc(),
  6487. diag::note_omp_nested_teams_construct_here);
  6488. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  6489. << isa<OMPExecutableDirective>(S);
  6490. return StmtError();
  6491. }
  6492. }
  6493. setFunctionHasBranchProtectedScope();
  6494. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6495. }
  6496. StmtResult
  6497. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  6498. Stmt *AStmt, SourceLocation StartLoc,
  6499. SourceLocation EndLoc) {
  6500. if (!AStmt)
  6501. return StmtError();
  6502. auto *CS = cast<CapturedStmt>(AStmt);
  6503. // 1.2.2 OpenMP Language Terminology
  6504. // Structured block - An executable statement with a single entry at the
  6505. // top and a single exit at the bottom.
  6506. // The point of exit cannot be a branch out of the structured block.
  6507. // longjmp() and throw() must not violate the entry/exit criteria.
  6508. CS->getCapturedDecl()->setNothrow();
  6509. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  6510. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6511. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6512. // 1.2.2 OpenMP Language Terminology
  6513. // Structured block - An executable statement with a single entry at the
  6514. // top and a single exit at the bottom.
  6515. // The point of exit cannot be a branch out of the structured block.
  6516. // longjmp() and throw() must not violate the entry/exit criteria.
  6517. CS->getCapturedDecl()->setNothrow();
  6518. }
  6519. setFunctionHasBranchProtectedScope();
  6520. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6521. AStmt);
  6522. }
  6523. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  6524. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6525. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6526. if (!AStmt)
  6527. return StmtError();
  6528. auto *CS = cast<CapturedStmt>(AStmt);
  6529. // 1.2.2 OpenMP Language Terminology
  6530. // Structured block - An executable statement with a single entry at the
  6531. // top and a single exit at the bottom.
  6532. // The point of exit cannot be a branch out of the structured block.
  6533. // longjmp() and throw() must not violate the entry/exit criteria.
  6534. CS->getCapturedDecl()->setNothrow();
  6535. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6536. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6537. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6538. // 1.2.2 OpenMP Language Terminology
  6539. // Structured block - An executable statement with a single entry at the
  6540. // top and a single exit at the bottom.
  6541. // The point of exit cannot be a branch out of the structured block.
  6542. // longjmp() and throw() must not violate the entry/exit criteria.
  6543. CS->getCapturedDecl()->setNothrow();
  6544. }
  6545. OMPLoopDirective::HelperExprs B;
  6546. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6547. // define the nested loops number.
  6548. unsigned NestedLoopCount =
  6549. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6550. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6551. VarsWithImplicitDSA, B);
  6552. if (NestedLoopCount == 0)
  6553. return StmtError();
  6554. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6555. "omp target parallel for loop exprs were not built");
  6556. if (!CurContext->isDependentContext()) {
  6557. // Finalize the clauses that need pre-built expressions for CodeGen.
  6558. for (OMPClause *C : Clauses) {
  6559. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6560. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6561. B.NumIterations, *this, CurScope,
  6562. DSAStack))
  6563. return StmtError();
  6564. }
  6565. }
  6566. setFunctionHasBranchProtectedScope();
  6567. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6568. NestedLoopCount, Clauses, AStmt,
  6569. B, DSAStack->isCancelRegion());
  6570. }
  6571. /// Check for existence of a map clause in the list of clauses.
  6572. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6573. const OpenMPClauseKind K) {
  6574. return llvm::any_of(
  6575. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6576. }
  6577. template <typename... Params>
  6578. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6579. const Params... ClauseTypes) {
  6580. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6581. }
  6582. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6583. Stmt *AStmt,
  6584. SourceLocation StartLoc,
  6585. SourceLocation EndLoc) {
  6586. if (!AStmt)
  6587. return StmtError();
  6588. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6589. // OpenMP [2.10.1, Restrictions, p. 97]
  6590. // At least one map clause must appear on the directive.
  6591. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6592. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6593. << "'map' or 'use_device_ptr'"
  6594. << getOpenMPDirectiveName(OMPD_target_data);
  6595. return StmtError();
  6596. }
  6597. setFunctionHasBranchProtectedScope();
  6598. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6599. AStmt);
  6600. }
  6601. StmtResult
  6602. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6603. SourceLocation StartLoc,
  6604. SourceLocation EndLoc, Stmt *AStmt) {
  6605. if (!AStmt)
  6606. return StmtError();
  6607. auto *CS = cast<CapturedStmt>(AStmt);
  6608. // 1.2.2 OpenMP Language Terminology
  6609. // Structured block - An executable statement with a single entry at the
  6610. // top and a single exit at the bottom.
  6611. // The point of exit cannot be a branch out of the structured block.
  6612. // longjmp() and throw() must not violate the entry/exit criteria.
  6613. CS->getCapturedDecl()->setNothrow();
  6614. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6615. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6616. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6617. // 1.2.2 OpenMP Language Terminology
  6618. // Structured block - An executable statement with a single entry at the
  6619. // top and a single exit at the bottom.
  6620. // The point of exit cannot be a branch out of the structured block.
  6621. // longjmp() and throw() must not violate the entry/exit criteria.
  6622. CS->getCapturedDecl()->setNothrow();
  6623. }
  6624. // OpenMP [2.10.2, Restrictions, p. 99]
  6625. // At least one map clause must appear on the directive.
  6626. if (!hasClauses(Clauses, OMPC_map)) {
  6627. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6628. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6629. return StmtError();
  6630. }
  6631. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6632. AStmt);
  6633. }
  6634. StmtResult
  6635. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6636. SourceLocation StartLoc,
  6637. SourceLocation EndLoc, Stmt *AStmt) {
  6638. if (!AStmt)
  6639. return StmtError();
  6640. auto *CS = cast<CapturedStmt>(AStmt);
  6641. // 1.2.2 OpenMP Language Terminology
  6642. // Structured block - An executable statement with a single entry at the
  6643. // top and a single exit at the bottom.
  6644. // The point of exit cannot be a branch out of the structured block.
  6645. // longjmp() and throw() must not violate the entry/exit criteria.
  6646. CS->getCapturedDecl()->setNothrow();
  6647. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6648. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6649. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6650. // 1.2.2 OpenMP Language Terminology
  6651. // Structured block - An executable statement with a single entry at the
  6652. // top and a single exit at the bottom.
  6653. // The point of exit cannot be a branch out of the structured block.
  6654. // longjmp() and throw() must not violate the entry/exit criteria.
  6655. CS->getCapturedDecl()->setNothrow();
  6656. }
  6657. // OpenMP [2.10.3, Restrictions, p. 102]
  6658. // At least one map clause must appear on the directive.
  6659. if (!hasClauses(Clauses, OMPC_map)) {
  6660. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6661. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6662. return StmtError();
  6663. }
  6664. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6665. AStmt);
  6666. }
  6667. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6668. SourceLocation StartLoc,
  6669. SourceLocation EndLoc,
  6670. Stmt *AStmt) {
  6671. if (!AStmt)
  6672. return StmtError();
  6673. auto *CS = cast<CapturedStmt>(AStmt);
  6674. // 1.2.2 OpenMP Language Terminology
  6675. // Structured block - An executable statement with a single entry at the
  6676. // top and a single exit at the bottom.
  6677. // The point of exit cannot be a branch out of the structured block.
  6678. // longjmp() and throw() must not violate the entry/exit criteria.
  6679. CS->getCapturedDecl()->setNothrow();
  6680. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6681. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6682. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6683. // 1.2.2 OpenMP Language Terminology
  6684. // Structured block - An executable statement with a single entry at the
  6685. // top and a single exit at the bottom.
  6686. // The point of exit cannot be a branch out of the structured block.
  6687. // longjmp() and throw() must not violate the entry/exit criteria.
  6688. CS->getCapturedDecl()->setNothrow();
  6689. }
  6690. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6691. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6692. return StmtError();
  6693. }
  6694. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6695. AStmt);
  6696. }
  6697. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6698. Stmt *AStmt, SourceLocation StartLoc,
  6699. SourceLocation EndLoc) {
  6700. if (!AStmt)
  6701. return StmtError();
  6702. auto *CS = cast<CapturedStmt>(AStmt);
  6703. // 1.2.2 OpenMP Language Terminology
  6704. // Structured block - An executable statement with a single entry at the
  6705. // top and a single exit at the bottom.
  6706. // The point of exit cannot be a branch out of the structured block.
  6707. // longjmp() and throw() must not violate the entry/exit criteria.
  6708. CS->getCapturedDecl()->setNothrow();
  6709. setFunctionHasBranchProtectedScope();
  6710. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6711. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6712. }
  6713. StmtResult
  6714. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6715. SourceLocation EndLoc,
  6716. OpenMPDirectiveKind CancelRegion) {
  6717. if (DSAStack->isParentNowaitRegion()) {
  6718. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6719. return StmtError();
  6720. }
  6721. if (DSAStack->isParentOrderedRegion()) {
  6722. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6723. return StmtError();
  6724. }
  6725. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6726. CancelRegion);
  6727. }
  6728. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6729. SourceLocation StartLoc,
  6730. SourceLocation EndLoc,
  6731. OpenMPDirectiveKind CancelRegion) {
  6732. if (DSAStack->isParentNowaitRegion()) {
  6733. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6734. return StmtError();
  6735. }
  6736. if (DSAStack->isParentOrderedRegion()) {
  6737. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6738. return StmtError();
  6739. }
  6740. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6741. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6742. CancelRegion);
  6743. }
  6744. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6745. ArrayRef<OMPClause *> Clauses) {
  6746. const OMPClause *PrevClause = nullptr;
  6747. bool ErrorFound = false;
  6748. for (const OMPClause *C : Clauses) {
  6749. if (C->getClauseKind() == OMPC_grainsize ||
  6750. C->getClauseKind() == OMPC_num_tasks) {
  6751. if (!PrevClause)
  6752. PrevClause = C;
  6753. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6754. S.Diag(C->getBeginLoc(),
  6755. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6756. << getOpenMPClauseName(C->getClauseKind())
  6757. << getOpenMPClauseName(PrevClause->getClauseKind());
  6758. S.Diag(PrevClause->getBeginLoc(),
  6759. diag::note_omp_previous_grainsize_num_tasks)
  6760. << getOpenMPClauseName(PrevClause->getClauseKind());
  6761. ErrorFound = true;
  6762. }
  6763. }
  6764. }
  6765. return ErrorFound;
  6766. }
  6767. static bool checkReductionClauseWithNogroup(Sema &S,
  6768. ArrayRef<OMPClause *> Clauses) {
  6769. const OMPClause *ReductionClause = nullptr;
  6770. const OMPClause *NogroupClause = nullptr;
  6771. for (const OMPClause *C : Clauses) {
  6772. if (C->getClauseKind() == OMPC_reduction) {
  6773. ReductionClause = C;
  6774. if (NogroupClause)
  6775. break;
  6776. continue;
  6777. }
  6778. if (C->getClauseKind() == OMPC_nogroup) {
  6779. NogroupClause = C;
  6780. if (ReductionClause)
  6781. break;
  6782. continue;
  6783. }
  6784. }
  6785. if (ReductionClause && NogroupClause) {
  6786. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  6787. << SourceRange(NogroupClause->getBeginLoc(),
  6788. NogroupClause->getEndLoc());
  6789. return true;
  6790. }
  6791. return false;
  6792. }
  6793. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6794. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6795. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6796. if (!AStmt)
  6797. return StmtError();
  6798. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6799. OMPLoopDirective::HelperExprs B;
  6800. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6801. // define the nested loops number.
  6802. unsigned NestedLoopCount =
  6803. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6804. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6805. VarsWithImplicitDSA, B);
  6806. if (NestedLoopCount == 0)
  6807. return StmtError();
  6808. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6809. "omp for loop exprs were not built");
  6810. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6811. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6812. // not appear on the same taskloop directive.
  6813. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6814. return StmtError();
  6815. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6816. // If a reduction clause is present on the taskloop directive, the nogroup
  6817. // clause must not be specified.
  6818. if (checkReductionClauseWithNogroup(*this, Clauses))
  6819. return StmtError();
  6820. setFunctionHasBranchProtectedScope();
  6821. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6822. NestedLoopCount, Clauses, AStmt, B);
  6823. }
  6824. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6825. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6826. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6827. if (!AStmt)
  6828. return StmtError();
  6829. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6830. OMPLoopDirective::HelperExprs B;
  6831. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6832. // define the nested loops number.
  6833. unsigned NestedLoopCount =
  6834. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6835. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6836. VarsWithImplicitDSA, B);
  6837. if (NestedLoopCount == 0)
  6838. return StmtError();
  6839. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6840. "omp for loop exprs were not built");
  6841. if (!CurContext->isDependentContext()) {
  6842. // Finalize the clauses that need pre-built expressions for CodeGen.
  6843. for (OMPClause *C : Clauses) {
  6844. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6845. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6846. B.NumIterations, *this, CurScope,
  6847. DSAStack))
  6848. return StmtError();
  6849. }
  6850. }
  6851. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6852. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6853. // not appear on the same taskloop directive.
  6854. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6855. return StmtError();
  6856. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6857. // If a reduction clause is present on the taskloop directive, the nogroup
  6858. // clause must not be specified.
  6859. if (checkReductionClauseWithNogroup(*this, Clauses))
  6860. return StmtError();
  6861. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6862. return StmtError();
  6863. setFunctionHasBranchProtectedScope();
  6864. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6865. NestedLoopCount, Clauses, AStmt, B);
  6866. }
  6867. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6868. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6869. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6870. if (!AStmt)
  6871. return StmtError();
  6872. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6873. OMPLoopDirective::HelperExprs B;
  6874. // In presence of clause 'collapse' with number of loops, it will
  6875. // define the nested loops number.
  6876. unsigned NestedLoopCount =
  6877. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6878. nullptr /*ordered not a clause on distribute*/, AStmt,
  6879. *this, *DSAStack, VarsWithImplicitDSA, B);
  6880. if (NestedLoopCount == 0)
  6881. return StmtError();
  6882. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6883. "omp for loop exprs were not built");
  6884. setFunctionHasBranchProtectedScope();
  6885. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6886. NestedLoopCount, Clauses, AStmt, B);
  6887. }
  6888. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6889. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6890. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6891. if (!AStmt)
  6892. return StmtError();
  6893. auto *CS = cast<CapturedStmt>(AStmt);
  6894. // 1.2.2 OpenMP Language Terminology
  6895. // Structured block - An executable statement with a single entry at the
  6896. // top and a single exit at the bottom.
  6897. // The point of exit cannot be a branch out of the structured block.
  6898. // longjmp() and throw() must not violate the entry/exit criteria.
  6899. CS->getCapturedDecl()->setNothrow();
  6900. for (int ThisCaptureLevel =
  6901. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6902. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6903. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6904. // 1.2.2 OpenMP Language Terminology
  6905. // Structured block - An executable statement with a single entry at the
  6906. // top and a single exit at the bottom.
  6907. // The point of exit cannot be a branch out of the structured block.
  6908. // longjmp() and throw() must not violate the entry/exit criteria.
  6909. CS->getCapturedDecl()->setNothrow();
  6910. }
  6911. OMPLoopDirective::HelperExprs B;
  6912. // In presence of clause 'collapse' with number of loops, it will
  6913. // define the nested loops number.
  6914. unsigned NestedLoopCount = checkOpenMPLoop(
  6915. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6916. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6917. VarsWithImplicitDSA, B);
  6918. if (NestedLoopCount == 0)
  6919. return StmtError();
  6920. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6921. "omp for loop exprs were not built");
  6922. setFunctionHasBranchProtectedScope();
  6923. return OMPDistributeParallelForDirective::Create(
  6924. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6925. DSAStack->isCancelRegion());
  6926. }
  6927. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6928. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6929. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6930. if (!AStmt)
  6931. return StmtError();
  6932. auto *CS = cast<CapturedStmt>(AStmt);
  6933. // 1.2.2 OpenMP Language Terminology
  6934. // Structured block - An executable statement with a single entry at the
  6935. // top and a single exit at the bottom.
  6936. // The point of exit cannot be a branch out of the structured block.
  6937. // longjmp() and throw() must not violate the entry/exit criteria.
  6938. CS->getCapturedDecl()->setNothrow();
  6939. for (int ThisCaptureLevel =
  6940. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6941. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6942. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6943. // 1.2.2 OpenMP Language Terminology
  6944. // Structured block - An executable statement with a single entry at the
  6945. // top and a single exit at the bottom.
  6946. // The point of exit cannot be a branch out of the structured block.
  6947. // longjmp() and throw() must not violate the entry/exit criteria.
  6948. CS->getCapturedDecl()->setNothrow();
  6949. }
  6950. OMPLoopDirective::HelperExprs B;
  6951. // In presence of clause 'collapse' with number of loops, it will
  6952. // define the nested loops number.
  6953. unsigned NestedLoopCount = checkOpenMPLoop(
  6954. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6955. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6956. VarsWithImplicitDSA, B);
  6957. if (NestedLoopCount == 0)
  6958. return StmtError();
  6959. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6960. "omp for loop exprs were not built");
  6961. if (!CurContext->isDependentContext()) {
  6962. // Finalize the clauses that need pre-built expressions for CodeGen.
  6963. for (OMPClause *C : Clauses) {
  6964. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6965. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6966. B.NumIterations, *this, CurScope,
  6967. DSAStack))
  6968. return StmtError();
  6969. }
  6970. }
  6971. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6972. return StmtError();
  6973. setFunctionHasBranchProtectedScope();
  6974. return OMPDistributeParallelForSimdDirective::Create(
  6975. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6976. }
  6977. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6978. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6979. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6980. if (!AStmt)
  6981. return StmtError();
  6982. auto *CS = cast<CapturedStmt>(AStmt);
  6983. // 1.2.2 OpenMP Language Terminology
  6984. // Structured block - An executable statement with a single entry at the
  6985. // top and a single exit at the bottom.
  6986. // The point of exit cannot be a branch out of the structured block.
  6987. // longjmp() and throw() must not violate the entry/exit criteria.
  6988. CS->getCapturedDecl()->setNothrow();
  6989. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  6990. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6991. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6992. // 1.2.2 OpenMP Language Terminology
  6993. // Structured block - An executable statement with a single entry at the
  6994. // top and a single exit at the bottom.
  6995. // The point of exit cannot be a branch out of the structured block.
  6996. // longjmp() and throw() must not violate the entry/exit criteria.
  6997. CS->getCapturedDecl()->setNothrow();
  6998. }
  6999. OMPLoopDirective::HelperExprs B;
  7000. // In presence of clause 'collapse' with number of loops, it will
  7001. // define the nested loops number.
  7002. unsigned NestedLoopCount =
  7003. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  7004. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7005. *DSAStack, VarsWithImplicitDSA, B);
  7006. if (NestedLoopCount == 0)
  7007. return StmtError();
  7008. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7009. "omp for loop exprs were not built");
  7010. if (!CurContext->isDependentContext()) {
  7011. // Finalize the clauses that need pre-built expressions for CodeGen.
  7012. for (OMPClause *C : Clauses) {
  7013. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7014. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7015. B.NumIterations, *this, CurScope,
  7016. DSAStack))
  7017. return StmtError();
  7018. }
  7019. }
  7020. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7021. return StmtError();
  7022. setFunctionHasBranchProtectedScope();
  7023. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  7024. NestedLoopCount, Clauses, AStmt, B);
  7025. }
  7026. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  7027. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7028. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7029. if (!AStmt)
  7030. return StmtError();
  7031. auto *CS = cast<CapturedStmt>(AStmt);
  7032. // 1.2.2 OpenMP Language Terminology
  7033. // Structured block - An executable statement with a single entry at the
  7034. // top and a single exit at the bottom.
  7035. // The point of exit cannot be a branch out of the structured block.
  7036. // longjmp() and throw() must not violate the entry/exit criteria.
  7037. CS->getCapturedDecl()->setNothrow();
  7038. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7039. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7040. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7041. // 1.2.2 OpenMP Language Terminology
  7042. // Structured block - An executable statement with a single entry at the
  7043. // top and a single exit at the bottom.
  7044. // The point of exit cannot be a branch out of the structured block.
  7045. // longjmp() and throw() must not violate the entry/exit criteria.
  7046. CS->getCapturedDecl()->setNothrow();
  7047. }
  7048. OMPLoopDirective::HelperExprs B;
  7049. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7050. // define the nested loops number.
  7051. unsigned NestedLoopCount = checkOpenMPLoop(
  7052. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7053. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7054. VarsWithImplicitDSA, B);
  7055. if (NestedLoopCount == 0)
  7056. return StmtError();
  7057. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7058. "omp target parallel for simd loop exprs were not built");
  7059. if (!CurContext->isDependentContext()) {
  7060. // Finalize the clauses that need pre-built expressions for CodeGen.
  7061. for (OMPClause *C : Clauses) {
  7062. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7063. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7064. B.NumIterations, *this, CurScope,
  7065. DSAStack))
  7066. return StmtError();
  7067. }
  7068. }
  7069. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7070. return StmtError();
  7071. setFunctionHasBranchProtectedScope();
  7072. return OMPTargetParallelForSimdDirective::Create(
  7073. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7074. }
  7075. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  7076. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7077. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7078. if (!AStmt)
  7079. return StmtError();
  7080. auto *CS = cast<CapturedStmt>(AStmt);
  7081. // 1.2.2 OpenMP Language Terminology
  7082. // Structured block - An executable statement with a single entry at the
  7083. // top and a single exit at the bottom.
  7084. // The point of exit cannot be a branch out of the structured block.
  7085. // longjmp() and throw() must not violate the entry/exit criteria.
  7086. CS->getCapturedDecl()->setNothrow();
  7087. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  7088. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7089. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7090. // 1.2.2 OpenMP Language Terminology
  7091. // Structured block - An executable statement with a single entry at the
  7092. // top and a single exit at the bottom.
  7093. // The point of exit cannot be a branch out of the structured block.
  7094. // longjmp() and throw() must not violate the entry/exit criteria.
  7095. CS->getCapturedDecl()->setNothrow();
  7096. }
  7097. OMPLoopDirective::HelperExprs B;
  7098. // In presence of clause 'collapse' with number of loops, it will define the
  7099. // nested loops number.
  7100. unsigned NestedLoopCount =
  7101. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  7102. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7103. VarsWithImplicitDSA, B);
  7104. if (NestedLoopCount == 0)
  7105. return StmtError();
  7106. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7107. "omp target simd loop exprs were not built");
  7108. if (!CurContext->isDependentContext()) {
  7109. // Finalize the clauses that need pre-built expressions for CodeGen.
  7110. for (OMPClause *C : Clauses) {
  7111. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7112. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7113. B.NumIterations, *this, CurScope,
  7114. DSAStack))
  7115. return StmtError();
  7116. }
  7117. }
  7118. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7119. return StmtError();
  7120. setFunctionHasBranchProtectedScope();
  7121. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  7122. NestedLoopCount, Clauses, AStmt, B);
  7123. }
  7124. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  7125. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7126. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7127. if (!AStmt)
  7128. return StmtError();
  7129. auto *CS = cast<CapturedStmt>(AStmt);
  7130. // 1.2.2 OpenMP Language Terminology
  7131. // Structured block - An executable statement with a single entry at the
  7132. // top and a single exit at the bottom.
  7133. // The point of exit cannot be a branch out of the structured block.
  7134. // longjmp() and throw() must not violate the entry/exit criteria.
  7135. CS->getCapturedDecl()->setNothrow();
  7136. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  7137. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7138. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7139. // 1.2.2 OpenMP Language Terminology
  7140. // Structured block - An executable statement with a single entry at the
  7141. // top and a single exit at the bottom.
  7142. // The point of exit cannot be a branch out of the structured block.
  7143. // longjmp() and throw() must not violate the entry/exit criteria.
  7144. CS->getCapturedDecl()->setNothrow();
  7145. }
  7146. OMPLoopDirective::HelperExprs B;
  7147. // In presence of clause 'collapse' with number of loops, it will
  7148. // define the nested loops number.
  7149. unsigned NestedLoopCount =
  7150. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  7151. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7152. *DSAStack, VarsWithImplicitDSA, B);
  7153. if (NestedLoopCount == 0)
  7154. return StmtError();
  7155. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7156. "omp teams distribute loop exprs were not built");
  7157. setFunctionHasBranchProtectedScope();
  7158. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7159. return OMPTeamsDistributeDirective::Create(
  7160. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7161. }
  7162. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  7163. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7164. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7165. if (!AStmt)
  7166. return StmtError();
  7167. auto *CS = cast<CapturedStmt>(AStmt);
  7168. // 1.2.2 OpenMP Language Terminology
  7169. // Structured block - An executable statement with a single entry at the
  7170. // top and a single exit at the bottom.
  7171. // The point of exit cannot be a branch out of the structured block.
  7172. // longjmp() and throw() must not violate the entry/exit criteria.
  7173. CS->getCapturedDecl()->setNothrow();
  7174. for (int ThisCaptureLevel =
  7175. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  7176. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7177. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7178. // 1.2.2 OpenMP Language Terminology
  7179. // Structured block - An executable statement with a single entry at the
  7180. // top and a single exit at the bottom.
  7181. // The point of exit cannot be a branch out of the structured block.
  7182. // longjmp() and throw() must not violate the entry/exit criteria.
  7183. CS->getCapturedDecl()->setNothrow();
  7184. }
  7185. OMPLoopDirective::HelperExprs B;
  7186. // In presence of clause 'collapse' with number of loops, it will
  7187. // define the nested loops number.
  7188. unsigned NestedLoopCount = checkOpenMPLoop(
  7189. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7190. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7191. VarsWithImplicitDSA, B);
  7192. if (NestedLoopCount == 0)
  7193. return StmtError();
  7194. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7195. "omp teams distribute simd loop exprs were not built");
  7196. if (!CurContext->isDependentContext()) {
  7197. // Finalize the clauses that need pre-built expressions for CodeGen.
  7198. for (OMPClause *C : Clauses) {
  7199. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7200. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7201. B.NumIterations, *this, CurScope,
  7202. DSAStack))
  7203. return StmtError();
  7204. }
  7205. }
  7206. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7207. return StmtError();
  7208. setFunctionHasBranchProtectedScope();
  7209. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7210. return OMPTeamsDistributeSimdDirective::Create(
  7211. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7212. }
  7213. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  7214. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7215. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7216. if (!AStmt)
  7217. return StmtError();
  7218. auto *CS = cast<CapturedStmt>(AStmt);
  7219. // 1.2.2 OpenMP Language Terminology
  7220. // Structured block - An executable statement with a single entry at the
  7221. // top and a single exit at the bottom.
  7222. // The point of exit cannot be a branch out of the structured block.
  7223. // longjmp() and throw() must not violate the entry/exit criteria.
  7224. CS->getCapturedDecl()->setNothrow();
  7225. for (int ThisCaptureLevel =
  7226. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  7227. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7228. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7229. // 1.2.2 OpenMP Language Terminology
  7230. // Structured block - An executable statement with a single entry at the
  7231. // top and a single exit at the bottom.
  7232. // The point of exit cannot be a branch out of the structured block.
  7233. // longjmp() and throw() must not violate the entry/exit criteria.
  7234. CS->getCapturedDecl()->setNothrow();
  7235. }
  7236. OMPLoopDirective::HelperExprs B;
  7237. // In presence of clause 'collapse' with number of loops, it will
  7238. // define the nested loops number.
  7239. unsigned NestedLoopCount = checkOpenMPLoop(
  7240. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7241. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7242. VarsWithImplicitDSA, B);
  7243. if (NestedLoopCount == 0)
  7244. return StmtError();
  7245. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7246. "omp for loop exprs were not built");
  7247. if (!CurContext->isDependentContext()) {
  7248. // Finalize the clauses that need pre-built expressions for CodeGen.
  7249. for (OMPClause *C : Clauses) {
  7250. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7251. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7252. B.NumIterations, *this, CurScope,
  7253. DSAStack))
  7254. return StmtError();
  7255. }
  7256. }
  7257. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7258. return StmtError();
  7259. setFunctionHasBranchProtectedScope();
  7260. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7261. return OMPTeamsDistributeParallelForSimdDirective::Create(
  7262. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7263. }
  7264. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  7265. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7266. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7267. if (!AStmt)
  7268. return StmtError();
  7269. auto *CS = cast<CapturedStmt>(AStmt);
  7270. // 1.2.2 OpenMP Language Terminology
  7271. // Structured block - An executable statement with a single entry at the
  7272. // top and a single exit at the bottom.
  7273. // The point of exit cannot be a branch out of the structured block.
  7274. // longjmp() and throw() must not violate the entry/exit criteria.
  7275. CS->getCapturedDecl()->setNothrow();
  7276. for (int ThisCaptureLevel =
  7277. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  7278. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7279. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7280. // 1.2.2 OpenMP Language Terminology
  7281. // Structured block - An executable statement with a single entry at the
  7282. // top and a single exit at the bottom.
  7283. // The point of exit cannot be a branch out of the structured block.
  7284. // longjmp() and throw() must not violate the entry/exit criteria.
  7285. CS->getCapturedDecl()->setNothrow();
  7286. }
  7287. OMPLoopDirective::HelperExprs B;
  7288. // In presence of clause 'collapse' with number of loops, it will
  7289. // define the nested loops number.
  7290. unsigned NestedLoopCount = checkOpenMPLoop(
  7291. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7292. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7293. VarsWithImplicitDSA, B);
  7294. if (NestedLoopCount == 0)
  7295. return StmtError();
  7296. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7297. "omp for loop exprs were not built");
  7298. setFunctionHasBranchProtectedScope();
  7299. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7300. return OMPTeamsDistributeParallelForDirective::Create(
  7301. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7302. DSAStack->isCancelRegion());
  7303. }
  7304. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7305. Stmt *AStmt,
  7306. SourceLocation StartLoc,
  7307. SourceLocation EndLoc) {
  7308. if (!AStmt)
  7309. return StmtError();
  7310. auto *CS = cast<CapturedStmt>(AStmt);
  7311. // 1.2.2 OpenMP Language Terminology
  7312. // Structured block - An executable statement with a single entry at the
  7313. // top and a single exit at the bottom.
  7314. // The point of exit cannot be a branch out of the structured block.
  7315. // longjmp() and throw() must not violate the entry/exit criteria.
  7316. CS->getCapturedDecl()->setNothrow();
  7317. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  7318. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7319. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7320. // 1.2.2 OpenMP Language Terminology
  7321. // Structured block - An executable statement with a single entry at the
  7322. // top and a single exit at the bottom.
  7323. // The point of exit cannot be a branch out of the structured block.
  7324. // longjmp() and throw() must not violate the entry/exit criteria.
  7325. CS->getCapturedDecl()->setNothrow();
  7326. }
  7327. setFunctionHasBranchProtectedScope();
  7328. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7329. AStmt);
  7330. }
  7331. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7332. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7333. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7334. if (!AStmt)
  7335. return StmtError();
  7336. auto *CS = cast<CapturedStmt>(AStmt);
  7337. // 1.2.2 OpenMP Language Terminology
  7338. // Structured block - An executable statement with a single entry at the
  7339. // top and a single exit at the bottom.
  7340. // The point of exit cannot be a branch out of the structured block.
  7341. // longjmp() and throw() must not violate the entry/exit criteria.
  7342. CS->getCapturedDecl()->setNothrow();
  7343. for (int ThisCaptureLevel =
  7344. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7345. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7346. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7347. // 1.2.2 OpenMP Language Terminology
  7348. // Structured block - An executable statement with a single entry at the
  7349. // top and a single exit at the bottom.
  7350. // The point of exit cannot be a branch out of the structured block.
  7351. // longjmp() and throw() must not violate the entry/exit criteria.
  7352. CS->getCapturedDecl()->setNothrow();
  7353. }
  7354. OMPLoopDirective::HelperExprs B;
  7355. // In presence of clause 'collapse' with number of loops, it will
  7356. // define the nested loops number.
  7357. unsigned NestedLoopCount = checkOpenMPLoop(
  7358. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7359. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7360. VarsWithImplicitDSA, B);
  7361. if (NestedLoopCount == 0)
  7362. return StmtError();
  7363. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7364. "omp target teams distribute loop exprs were not built");
  7365. setFunctionHasBranchProtectedScope();
  7366. return OMPTargetTeamsDistributeDirective::Create(
  7367. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7368. }
  7369. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  7370. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7371. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7372. if (!AStmt)
  7373. return StmtError();
  7374. auto *CS = cast<CapturedStmt>(AStmt);
  7375. // 1.2.2 OpenMP Language Terminology
  7376. // Structured block - An executable statement with a single entry at the
  7377. // top and a single exit at the bottom.
  7378. // The point of exit cannot be a branch out of the structured block.
  7379. // longjmp() and throw() must not violate the entry/exit criteria.
  7380. CS->getCapturedDecl()->setNothrow();
  7381. for (int ThisCaptureLevel =
  7382. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  7383. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7384. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7385. // 1.2.2 OpenMP Language Terminology
  7386. // Structured block - An executable statement with a single entry at the
  7387. // top and a single exit at the bottom.
  7388. // The point of exit cannot be a branch out of the structured block.
  7389. // longjmp() and throw() must not violate the entry/exit criteria.
  7390. CS->getCapturedDecl()->setNothrow();
  7391. }
  7392. OMPLoopDirective::HelperExprs B;
  7393. // In presence of clause 'collapse' with number of loops, it will
  7394. // define the nested loops number.
  7395. unsigned NestedLoopCount = checkOpenMPLoop(
  7396. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7397. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7398. VarsWithImplicitDSA, B);
  7399. if (NestedLoopCount == 0)
  7400. return StmtError();
  7401. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7402. "omp target teams distribute parallel for loop exprs were not built");
  7403. if (!CurContext->isDependentContext()) {
  7404. // Finalize the clauses that need pre-built expressions for CodeGen.
  7405. for (OMPClause *C : Clauses) {
  7406. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7407. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7408. B.NumIterations, *this, CurScope,
  7409. DSAStack))
  7410. return StmtError();
  7411. }
  7412. }
  7413. setFunctionHasBranchProtectedScope();
  7414. return OMPTargetTeamsDistributeParallelForDirective::Create(
  7415. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7416. DSAStack->isCancelRegion());
  7417. }
  7418. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  7419. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7420. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7421. if (!AStmt)
  7422. return StmtError();
  7423. auto *CS = cast<CapturedStmt>(AStmt);
  7424. // 1.2.2 OpenMP Language Terminology
  7425. // Structured block - An executable statement with a single entry at the
  7426. // top and a single exit at the bottom.
  7427. // The point of exit cannot be a branch out of the structured block.
  7428. // longjmp() and throw() must not violate the entry/exit criteria.
  7429. CS->getCapturedDecl()->setNothrow();
  7430. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  7431. OMPD_target_teams_distribute_parallel_for_simd);
  7432. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7433. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7434. // 1.2.2 OpenMP Language Terminology
  7435. // Structured block - An executable statement with a single entry at the
  7436. // top and a single exit at the bottom.
  7437. // The point of exit cannot be a branch out of the structured block.
  7438. // longjmp() and throw() must not violate the entry/exit criteria.
  7439. CS->getCapturedDecl()->setNothrow();
  7440. }
  7441. OMPLoopDirective::HelperExprs B;
  7442. // In presence of clause 'collapse' with number of loops, it will
  7443. // define the nested loops number.
  7444. unsigned NestedLoopCount =
  7445. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  7446. getCollapseNumberExpr(Clauses),
  7447. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7448. *DSAStack, VarsWithImplicitDSA, B);
  7449. if (NestedLoopCount == 0)
  7450. return StmtError();
  7451. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7452. "omp target teams distribute parallel for simd loop exprs were not "
  7453. "built");
  7454. if (!CurContext->isDependentContext()) {
  7455. // Finalize the clauses that need pre-built expressions for CodeGen.
  7456. for (OMPClause *C : Clauses) {
  7457. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7458. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7459. B.NumIterations, *this, CurScope,
  7460. DSAStack))
  7461. return StmtError();
  7462. }
  7463. }
  7464. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7465. return StmtError();
  7466. setFunctionHasBranchProtectedScope();
  7467. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  7468. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7469. }
  7470. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  7471. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7472. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7473. if (!AStmt)
  7474. return StmtError();
  7475. auto *CS = cast<CapturedStmt>(AStmt);
  7476. // 1.2.2 OpenMP Language Terminology
  7477. // Structured block - An executable statement with a single entry at the
  7478. // top and a single exit at the bottom.
  7479. // The point of exit cannot be a branch out of the structured block.
  7480. // longjmp() and throw() must not violate the entry/exit criteria.
  7481. CS->getCapturedDecl()->setNothrow();
  7482. for (int ThisCaptureLevel =
  7483. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  7484. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7485. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7486. // 1.2.2 OpenMP Language Terminology
  7487. // Structured block - An executable statement with a single entry at the
  7488. // top and a single exit at the bottom.
  7489. // The point of exit cannot be a branch out of the structured block.
  7490. // longjmp() and throw() must not violate the entry/exit criteria.
  7491. CS->getCapturedDecl()->setNothrow();
  7492. }
  7493. OMPLoopDirective::HelperExprs B;
  7494. // In presence of clause 'collapse' with number of loops, it will
  7495. // define the nested loops number.
  7496. unsigned NestedLoopCount = checkOpenMPLoop(
  7497. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7498. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7499. VarsWithImplicitDSA, B);
  7500. if (NestedLoopCount == 0)
  7501. return StmtError();
  7502. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7503. "omp target teams distribute simd loop exprs were not built");
  7504. if (!CurContext->isDependentContext()) {
  7505. // Finalize the clauses that need pre-built expressions for CodeGen.
  7506. for (OMPClause *C : Clauses) {
  7507. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7508. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7509. B.NumIterations, *this, CurScope,
  7510. DSAStack))
  7511. return StmtError();
  7512. }
  7513. }
  7514. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7515. return StmtError();
  7516. setFunctionHasBranchProtectedScope();
  7517. return OMPTargetTeamsDistributeSimdDirective::Create(
  7518. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7519. }
  7520. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  7521. SourceLocation StartLoc,
  7522. SourceLocation LParenLoc,
  7523. SourceLocation EndLoc) {
  7524. OMPClause *Res = nullptr;
  7525. switch (Kind) {
  7526. case OMPC_final:
  7527. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  7528. break;
  7529. case OMPC_num_threads:
  7530. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7531. break;
  7532. case OMPC_safelen:
  7533. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7534. break;
  7535. case OMPC_simdlen:
  7536. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7537. break;
  7538. case OMPC_collapse:
  7539. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  7540. break;
  7541. case OMPC_ordered:
  7542. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  7543. break;
  7544. case OMPC_device:
  7545. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  7546. break;
  7547. case OMPC_num_teams:
  7548. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7549. break;
  7550. case OMPC_thread_limit:
  7551. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  7552. break;
  7553. case OMPC_priority:
  7554. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  7555. break;
  7556. case OMPC_grainsize:
  7557. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  7558. break;
  7559. case OMPC_num_tasks:
  7560. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  7561. break;
  7562. case OMPC_hint:
  7563. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  7564. break;
  7565. case OMPC_if:
  7566. case OMPC_default:
  7567. case OMPC_proc_bind:
  7568. case OMPC_schedule:
  7569. case OMPC_private:
  7570. case OMPC_firstprivate:
  7571. case OMPC_lastprivate:
  7572. case OMPC_shared:
  7573. case OMPC_reduction:
  7574. case OMPC_task_reduction:
  7575. case OMPC_in_reduction:
  7576. case OMPC_linear:
  7577. case OMPC_aligned:
  7578. case OMPC_copyin:
  7579. case OMPC_copyprivate:
  7580. case OMPC_nowait:
  7581. case OMPC_untied:
  7582. case OMPC_mergeable:
  7583. case OMPC_threadprivate:
  7584. case OMPC_flush:
  7585. case OMPC_read:
  7586. case OMPC_write:
  7587. case OMPC_update:
  7588. case OMPC_capture:
  7589. case OMPC_seq_cst:
  7590. case OMPC_depend:
  7591. case OMPC_threads:
  7592. case OMPC_simd:
  7593. case OMPC_map:
  7594. case OMPC_nogroup:
  7595. case OMPC_dist_schedule:
  7596. case OMPC_defaultmap:
  7597. case OMPC_unknown:
  7598. case OMPC_uniform:
  7599. case OMPC_to:
  7600. case OMPC_from:
  7601. case OMPC_use_device_ptr:
  7602. case OMPC_is_device_ptr:
  7603. case OMPC_unified_address:
  7604. case OMPC_unified_shared_memory:
  7605. case OMPC_reverse_offload:
  7606. case OMPC_dynamic_allocators:
  7607. llvm_unreachable("Clause is not allowed.");
  7608. }
  7609. return Res;
  7610. }
  7611. // An OpenMP directive such as 'target parallel' has two captured regions:
  7612. // for the 'target' and 'parallel' respectively. This function returns
  7613. // the region in which to capture expressions associated with a clause.
  7614. // A return value of OMPD_unknown signifies that the expression should not
  7615. // be captured.
  7616. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7617. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7618. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7619. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7620. switch (CKind) {
  7621. case OMPC_if:
  7622. switch (DKind) {
  7623. case OMPD_target_parallel:
  7624. case OMPD_target_parallel_for:
  7625. case OMPD_target_parallel_for_simd:
  7626. // If this clause applies to the nested 'parallel' region, capture within
  7627. // the 'target' region, otherwise do not capture.
  7628. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7629. CaptureRegion = OMPD_target;
  7630. break;
  7631. case OMPD_target_teams_distribute_parallel_for:
  7632. case OMPD_target_teams_distribute_parallel_for_simd:
  7633. // If this clause applies to the nested 'parallel' region, capture within
  7634. // the 'teams' region, otherwise do not capture.
  7635. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7636. CaptureRegion = OMPD_teams;
  7637. break;
  7638. case OMPD_teams_distribute_parallel_for:
  7639. case OMPD_teams_distribute_parallel_for_simd:
  7640. CaptureRegion = OMPD_teams;
  7641. break;
  7642. case OMPD_target_update:
  7643. case OMPD_target_enter_data:
  7644. case OMPD_target_exit_data:
  7645. CaptureRegion = OMPD_task;
  7646. break;
  7647. case OMPD_cancel:
  7648. case OMPD_parallel:
  7649. case OMPD_parallel_sections:
  7650. case OMPD_parallel_for:
  7651. case OMPD_parallel_for_simd:
  7652. case OMPD_target:
  7653. case OMPD_target_simd:
  7654. case OMPD_target_teams:
  7655. case OMPD_target_teams_distribute:
  7656. case OMPD_target_teams_distribute_simd:
  7657. case OMPD_distribute_parallel_for:
  7658. case OMPD_distribute_parallel_for_simd:
  7659. case OMPD_task:
  7660. case OMPD_taskloop:
  7661. case OMPD_taskloop_simd:
  7662. case OMPD_target_data:
  7663. // Do not capture if-clause expressions.
  7664. break;
  7665. case OMPD_threadprivate:
  7666. case OMPD_taskyield:
  7667. case OMPD_barrier:
  7668. case OMPD_taskwait:
  7669. case OMPD_cancellation_point:
  7670. case OMPD_flush:
  7671. case OMPD_declare_reduction:
  7672. case OMPD_declare_simd:
  7673. case OMPD_declare_target:
  7674. case OMPD_end_declare_target:
  7675. case OMPD_teams:
  7676. case OMPD_simd:
  7677. case OMPD_for:
  7678. case OMPD_for_simd:
  7679. case OMPD_sections:
  7680. case OMPD_section:
  7681. case OMPD_single:
  7682. case OMPD_master:
  7683. case OMPD_critical:
  7684. case OMPD_taskgroup:
  7685. case OMPD_distribute:
  7686. case OMPD_ordered:
  7687. case OMPD_atomic:
  7688. case OMPD_distribute_simd:
  7689. case OMPD_teams_distribute:
  7690. case OMPD_teams_distribute_simd:
  7691. case OMPD_requires:
  7692. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7693. case OMPD_unknown:
  7694. llvm_unreachable("Unknown OpenMP directive");
  7695. }
  7696. break;
  7697. case OMPC_num_threads:
  7698. switch (DKind) {
  7699. case OMPD_target_parallel:
  7700. case OMPD_target_parallel_for:
  7701. case OMPD_target_parallel_for_simd:
  7702. CaptureRegion = OMPD_target;
  7703. break;
  7704. case OMPD_teams_distribute_parallel_for:
  7705. case OMPD_teams_distribute_parallel_for_simd:
  7706. case OMPD_target_teams_distribute_parallel_for:
  7707. case OMPD_target_teams_distribute_parallel_for_simd:
  7708. CaptureRegion = OMPD_teams;
  7709. break;
  7710. case OMPD_parallel:
  7711. case OMPD_parallel_sections:
  7712. case OMPD_parallel_for:
  7713. case OMPD_parallel_for_simd:
  7714. case OMPD_distribute_parallel_for:
  7715. case OMPD_distribute_parallel_for_simd:
  7716. // Do not capture num_threads-clause expressions.
  7717. break;
  7718. case OMPD_target_data:
  7719. case OMPD_target_enter_data:
  7720. case OMPD_target_exit_data:
  7721. case OMPD_target_update:
  7722. case OMPD_target:
  7723. case OMPD_target_simd:
  7724. case OMPD_target_teams:
  7725. case OMPD_target_teams_distribute:
  7726. case OMPD_target_teams_distribute_simd:
  7727. case OMPD_cancel:
  7728. case OMPD_task:
  7729. case OMPD_taskloop:
  7730. case OMPD_taskloop_simd:
  7731. case OMPD_threadprivate:
  7732. case OMPD_taskyield:
  7733. case OMPD_barrier:
  7734. case OMPD_taskwait:
  7735. case OMPD_cancellation_point:
  7736. case OMPD_flush:
  7737. case OMPD_declare_reduction:
  7738. case OMPD_declare_simd:
  7739. case OMPD_declare_target:
  7740. case OMPD_end_declare_target:
  7741. case OMPD_teams:
  7742. case OMPD_simd:
  7743. case OMPD_for:
  7744. case OMPD_for_simd:
  7745. case OMPD_sections:
  7746. case OMPD_section:
  7747. case OMPD_single:
  7748. case OMPD_master:
  7749. case OMPD_critical:
  7750. case OMPD_taskgroup:
  7751. case OMPD_distribute:
  7752. case OMPD_ordered:
  7753. case OMPD_atomic:
  7754. case OMPD_distribute_simd:
  7755. case OMPD_teams_distribute:
  7756. case OMPD_teams_distribute_simd:
  7757. case OMPD_requires:
  7758. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7759. case OMPD_unknown:
  7760. llvm_unreachable("Unknown OpenMP directive");
  7761. }
  7762. break;
  7763. case OMPC_num_teams:
  7764. switch (DKind) {
  7765. case OMPD_target_teams:
  7766. case OMPD_target_teams_distribute:
  7767. case OMPD_target_teams_distribute_simd:
  7768. case OMPD_target_teams_distribute_parallel_for:
  7769. case OMPD_target_teams_distribute_parallel_for_simd:
  7770. CaptureRegion = OMPD_target;
  7771. break;
  7772. case OMPD_teams_distribute_parallel_for:
  7773. case OMPD_teams_distribute_parallel_for_simd:
  7774. case OMPD_teams:
  7775. case OMPD_teams_distribute:
  7776. case OMPD_teams_distribute_simd:
  7777. // Do not capture num_teams-clause expressions.
  7778. break;
  7779. case OMPD_distribute_parallel_for:
  7780. case OMPD_distribute_parallel_for_simd:
  7781. case OMPD_task:
  7782. case OMPD_taskloop:
  7783. case OMPD_taskloop_simd:
  7784. case OMPD_target_data:
  7785. case OMPD_target_enter_data:
  7786. case OMPD_target_exit_data:
  7787. case OMPD_target_update:
  7788. case OMPD_cancel:
  7789. case OMPD_parallel:
  7790. case OMPD_parallel_sections:
  7791. case OMPD_parallel_for:
  7792. case OMPD_parallel_for_simd:
  7793. case OMPD_target:
  7794. case OMPD_target_simd:
  7795. case OMPD_target_parallel:
  7796. case OMPD_target_parallel_for:
  7797. case OMPD_target_parallel_for_simd:
  7798. case OMPD_threadprivate:
  7799. case OMPD_taskyield:
  7800. case OMPD_barrier:
  7801. case OMPD_taskwait:
  7802. case OMPD_cancellation_point:
  7803. case OMPD_flush:
  7804. case OMPD_declare_reduction:
  7805. case OMPD_declare_simd:
  7806. case OMPD_declare_target:
  7807. case OMPD_end_declare_target:
  7808. case OMPD_simd:
  7809. case OMPD_for:
  7810. case OMPD_for_simd:
  7811. case OMPD_sections:
  7812. case OMPD_section:
  7813. case OMPD_single:
  7814. case OMPD_master:
  7815. case OMPD_critical:
  7816. case OMPD_taskgroup:
  7817. case OMPD_distribute:
  7818. case OMPD_ordered:
  7819. case OMPD_atomic:
  7820. case OMPD_distribute_simd:
  7821. case OMPD_requires:
  7822. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7823. case OMPD_unknown:
  7824. llvm_unreachable("Unknown OpenMP directive");
  7825. }
  7826. break;
  7827. case OMPC_thread_limit:
  7828. switch (DKind) {
  7829. case OMPD_target_teams:
  7830. case OMPD_target_teams_distribute:
  7831. case OMPD_target_teams_distribute_simd:
  7832. case OMPD_target_teams_distribute_parallel_for:
  7833. case OMPD_target_teams_distribute_parallel_for_simd:
  7834. CaptureRegion = OMPD_target;
  7835. break;
  7836. case OMPD_teams_distribute_parallel_for:
  7837. case OMPD_teams_distribute_parallel_for_simd:
  7838. case OMPD_teams:
  7839. case OMPD_teams_distribute:
  7840. case OMPD_teams_distribute_simd:
  7841. // Do not capture thread_limit-clause expressions.
  7842. break;
  7843. case OMPD_distribute_parallel_for:
  7844. case OMPD_distribute_parallel_for_simd:
  7845. case OMPD_task:
  7846. case OMPD_taskloop:
  7847. case OMPD_taskloop_simd:
  7848. case OMPD_target_data:
  7849. case OMPD_target_enter_data:
  7850. case OMPD_target_exit_data:
  7851. case OMPD_target_update:
  7852. case OMPD_cancel:
  7853. case OMPD_parallel:
  7854. case OMPD_parallel_sections:
  7855. case OMPD_parallel_for:
  7856. case OMPD_parallel_for_simd:
  7857. case OMPD_target:
  7858. case OMPD_target_simd:
  7859. case OMPD_target_parallel:
  7860. case OMPD_target_parallel_for:
  7861. case OMPD_target_parallel_for_simd:
  7862. case OMPD_threadprivate:
  7863. case OMPD_taskyield:
  7864. case OMPD_barrier:
  7865. case OMPD_taskwait:
  7866. case OMPD_cancellation_point:
  7867. case OMPD_flush:
  7868. case OMPD_declare_reduction:
  7869. case OMPD_declare_simd:
  7870. case OMPD_declare_target:
  7871. case OMPD_end_declare_target:
  7872. case OMPD_simd:
  7873. case OMPD_for:
  7874. case OMPD_for_simd:
  7875. case OMPD_sections:
  7876. case OMPD_section:
  7877. case OMPD_single:
  7878. case OMPD_master:
  7879. case OMPD_critical:
  7880. case OMPD_taskgroup:
  7881. case OMPD_distribute:
  7882. case OMPD_ordered:
  7883. case OMPD_atomic:
  7884. case OMPD_distribute_simd:
  7885. case OMPD_requires:
  7886. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7887. case OMPD_unknown:
  7888. llvm_unreachable("Unknown OpenMP directive");
  7889. }
  7890. break;
  7891. case OMPC_schedule:
  7892. switch (DKind) {
  7893. case OMPD_parallel_for:
  7894. case OMPD_parallel_for_simd:
  7895. case OMPD_distribute_parallel_for:
  7896. case OMPD_distribute_parallel_for_simd:
  7897. case OMPD_teams_distribute_parallel_for:
  7898. case OMPD_teams_distribute_parallel_for_simd:
  7899. case OMPD_target_parallel_for:
  7900. case OMPD_target_parallel_for_simd:
  7901. case OMPD_target_teams_distribute_parallel_for:
  7902. case OMPD_target_teams_distribute_parallel_for_simd:
  7903. CaptureRegion = OMPD_parallel;
  7904. break;
  7905. case OMPD_for:
  7906. case OMPD_for_simd:
  7907. // Do not capture schedule-clause expressions.
  7908. break;
  7909. case OMPD_task:
  7910. case OMPD_taskloop:
  7911. case OMPD_taskloop_simd:
  7912. case OMPD_target_data:
  7913. case OMPD_target_enter_data:
  7914. case OMPD_target_exit_data:
  7915. case OMPD_target_update:
  7916. case OMPD_teams:
  7917. case OMPD_teams_distribute:
  7918. case OMPD_teams_distribute_simd:
  7919. case OMPD_target_teams_distribute:
  7920. case OMPD_target_teams_distribute_simd:
  7921. case OMPD_target:
  7922. case OMPD_target_simd:
  7923. case OMPD_target_parallel:
  7924. case OMPD_cancel:
  7925. case OMPD_parallel:
  7926. case OMPD_parallel_sections:
  7927. case OMPD_threadprivate:
  7928. case OMPD_taskyield:
  7929. case OMPD_barrier:
  7930. case OMPD_taskwait:
  7931. case OMPD_cancellation_point:
  7932. case OMPD_flush:
  7933. case OMPD_declare_reduction:
  7934. case OMPD_declare_simd:
  7935. case OMPD_declare_target:
  7936. case OMPD_end_declare_target:
  7937. case OMPD_simd:
  7938. case OMPD_sections:
  7939. case OMPD_section:
  7940. case OMPD_single:
  7941. case OMPD_master:
  7942. case OMPD_critical:
  7943. case OMPD_taskgroup:
  7944. case OMPD_distribute:
  7945. case OMPD_ordered:
  7946. case OMPD_atomic:
  7947. case OMPD_distribute_simd:
  7948. case OMPD_target_teams:
  7949. case OMPD_requires:
  7950. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7951. case OMPD_unknown:
  7952. llvm_unreachable("Unknown OpenMP directive");
  7953. }
  7954. break;
  7955. case OMPC_dist_schedule:
  7956. switch (DKind) {
  7957. case OMPD_teams_distribute_parallel_for:
  7958. case OMPD_teams_distribute_parallel_for_simd:
  7959. case OMPD_teams_distribute:
  7960. case OMPD_teams_distribute_simd:
  7961. case OMPD_target_teams_distribute_parallel_for:
  7962. case OMPD_target_teams_distribute_parallel_for_simd:
  7963. case OMPD_target_teams_distribute:
  7964. case OMPD_target_teams_distribute_simd:
  7965. CaptureRegion = OMPD_teams;
  7966. break;
  7967. case OMPD_distribute_parallel_for:
  7968. case OMPD_distribute_parallel_for_simd:
  7969. case OMPD_distribute:
  7970. case OMPD_distribute_simd:
  7971. // Do not capture thread_limit-clause expressions.
  7972. break;
  7973. case OMPD_parallel_for:
  7974. case OMPD_parallel_for_simd:
  7975. case OMPD_target_parallel_for_simd:
  7976. case OMPD_target_parallel_for:
  7977. case OMPD_task:
  7978. case OMPD_taskloop:
  7979. case OMPD_taskloop_simd:
  7980. case OMPD_target_data:
  7981. case OMPD_target_enter_data:
  7982. case OMPD_target_exit_data:
  7983. case OMPD_target_update:
  7984. case OMPD_teams:
  7985. case OMPD_target:
  7986. case OMPD_target_simd:
  7987. case OMPD_target_parallel:
  7988. case OMPD_cancel:
  7989. case OMPD_parallel:
  7990. case OMPD_parallel_sections:
  7991. case OMPD_threadprivate:
  7992. case OMPD_taskyield:
  7993. case OMPD_barrier:
  7994. case OMPD_taskwait:
  7995. case OMPD_cancellation_point:
  7996. case OMPD_flush:
  7997. case OMPD_declare_reduction:
  7998. case OMPD_declare_simd:
  7999. case OMPD_declare_target:
  8000. case OMPD_end_declare_target:
  8001. case OMPD_simd:
  8002. case OMPD_for:
  8003. case OMPD_for_simd:
  8004. case OMPD_sections:
  8005. case OMPD_section:
  8006. case OMPD_single:
  8007. case OMPD_master:
  8008. case OMPD_critical:
  8009. case OMPD_taskgroup:
  8010. case OMPD_ordered:
  8011. case OMPD_atomic:
  8012. case OMPD_target_teams:
  8013. case OMPD_requires:
  8014. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8015. case OMPD_unknown:
  8016. llvm_unreachable("Unknown OpenMP directive");
  8017. }
  8018. break;
  8019. case OMPC_device:
  8020. switch (DKind) {
  8021. case OMPD_target_update:
  8022. case OMPD_target_enter_data:
  8023. case OMPD_target_exit_data:
  8024. case OMPD_target:
  8025. case OMPD_target_simd:
  8026. case OMPD_target_teams:
  8027. case OMPD_target_parallel:
  8028. case OMPD_target_teams_distribute:
  8029. case OMPD_target_teams_distribute_simd:
  8030. case OMPD_target_parallel_for:
  8031. case OMPD_target_parallel_for_simd:
  8032. case OMPD_target_teams_distribute_parallel_for:
  8033. case OMPD_target_teams_distribute_parallel_for_simd:
  8034. CaptureRegion = OMPD_task;
  8035. break;
  8036. case OMPD_target_data:
  8037. // Do not capture device-clause expressions.
  8038. break;
  8039. case OMPD_teams_distribute_parallel_for:
  8040. case OMPD_teams_distribute_parallel_for_simd:
  8041. case OMPD_teams:
  8042. case OMPD_teams_distribute:
  8043. case OMPD_teams_distribute_simd:
  8044. case OMPD_distribute_parallel_for:
  8045. case OMPD_distribute_parallel_for_simd:
  8046. case OMPD_task:
  8047. case OMPD_taskloop:
  8048. case OMPD_taskloop_simd:
  8049. case OMPD_cancel:
  8050. case OMPD_parallel:
  8051. case OMPD_parallel_sections:
  8052. case OMPD_parallel_for:
  8053. case OMPD_parallel_for_simd:
  8054. case OMPD_threadprivate:
  8055. case OMPD_taskyield:
  8056. case OMPD_barrier:
  8057. case OMPD_taskwait:
  8058. case OMPD_cancellation_point:
  8059. case OMPD_flush:
  8060. case OMPD_declare_reduction:
  8061. case OMPD_declare_simd:
  8062. case OMPD_declare_target:
  8063. case OMPD_end_declare_target:
  8064. case OMPD_simd:
  8065. case OMPD_for:
  8066. case OMPD_for_simd:
  8067. case OMPD_sections:
  8068. case OMPD_section:
  8069. case OMPD_single:
  8070. case OMPD_master:
  8071. case OMPD_critical:
  8072. case OMPD_taskgroup:
  8073. case OMPD_distribute:
  8074. case OMPD_ordered:
  8075. case OMPD_atomic:
  8076. case OMPD_distribute_simd:
  8077. case OMPD_requires:
  8078. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8079. case OMPD_unknown:
  8080. llvm_unreachable("Unknown OpenMP directive");
  8081. }
  8082. break;
  8083. case OMPC_firstprivate:
  8084. case OMPC_lastprivate:
  8085. case OMPC_reduction:
  8086. case OMPC_task_reduction:
  8087. case OMPC_in_reduction:
  8088. case OMPC_linear:
  8089. case OMPC_default:
  8090. case OMPC_proc_bind:
  8091. case OMPC_final:
  8092. case OMPC_safelen:
  8093. case OMPC_simdlen:
  8094. case OMPC_collapse:
  8095. case OMPC_private:
  8096. case OMPC_shared:
  8097. case OMPC_aligned:
  8098. case OMPC_copyin:
  8099. case OMPC_copyprivate:
  8100. case OMPC_ordered:
  8101. case OMPC_nowait:
  8102. case OMPC_untied:
  8103. case OMPC_mergeable:
  8104. case OMPC_threadprivate:
  8105. case OMPC_flush:
  8106. case OMPC_read:
  8107. case OMPC_write:
  8108. case OMPC_update:
  8109. case OMPC_capture:
  8110. case OMPC_seq_cst:
  8111. case OMPC_depend:
  8112. case OMPC_threads:
  8113. case OMPC_simd:
  8114. case OMPC_map:
  8115. case OMPC_priority:
  8116. case OMPC_grainsize:
  8117. case OMPC_nogroup:
  8118. case OMPC_num_tasks:
  8119. case OMPC_hint:
  8120. case OMPC_defaultmap:
  8121. case OMPC_unknown:
  8122. case OMPC_uniform:
  8123. case OMPC_to:
  8124. case OMPC_from:
  8125. case OMPC_use_device_ptr:
  8126. case OMPC_is_device_ptr:
  8127. case OMPC_unified_address:
  8128. case OMPC_unified_shared_memory:
  8129. case OMPC_reverse_offload:
  8130. case OMPC_dynamic_allocators:
  8131. llvm_unreachable("Unexpected OpenMP clause.");
  8132. }
  8133. return CaptureRegion;
  8134. }
  8135. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  8136. Expr *Condition, SourceLocation StartLoc,
  8137. SourceLocation LParenLoc,
  8138. SourceLocation NameModifierLoc,
  8139. SourceLocation ColonLoc,
  8140. SourceLocation EndLoc) {
  8141. Expr *ValExpr = Condition;
  8142. Stmt *HelperValStmt = nullptr;
  8143. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8144. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8145. !Condition->isInstantiationDependent() &&
  8146. !Condition->containsUnexpandedParameterPack()) {
  8147. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8148. if (Val.isInvalid())
  8149. return nullptr;
  8150. ValExpr = Val.get();
  8151. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8152. CaptureRegion =
  8153. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  8154. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8155. ValExpr = MakeFullExpr(ValExpr).get();
  8156. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8157. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8158. HelperValStmt = buildPreInits(Context, Captures);
  8159. }
  8160. }
  8161. return new (Context)
  8162. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  8163. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  8164. }
  8165. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  8166. SourceLocation StartLoc,
  8167. SourceLocation LParenLoc,
  8168. SourceLocation EndLoc) {
  8169. Expr *ValExpr = Condition;
  8170. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8171. !Condition->isInstantiationDependent() &&
  8172. !Condition->containsUnexpandedParameterPack()) {
  8173. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8174. if (Val.isInvalid())
  8175. return nullptr;
  8176. ValExpr = MakeFullExpr(Val.get()).get();
  8177. }
  8178. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8179. }
  8180. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  8181. Expr *Op) {
  8182. if (!Op)
  8183. return ExprError();
  8184. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  8185. public:
  8186. IntConvertDiagnoser()
  8187. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  8188. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8189. QualType T) override {
  8190. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  8191. }
  8192. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  8193. QualType T) override {
  8194. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  8195. }
  8196. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  8197. QualType T,
  8198. QualType ConvTy) override {
  8199. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  8200. }
  8201. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  8202. QualType ConvTy) override {
  8203. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8204. << ConvTy->isEnumeralType() << ConvTy;
  8205. }
  8206. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8207. QualType T) override {
  8208. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  8209. }
  8210. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  8211. QualType ConvTy) override {
  8212. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8213. << ConvTy->isEnumeralType() << ConvTy;
  8214. }
  8215. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  8216. QualType) override {
  8217. llvm_unreachable("conversion functions are permitted");
  8218. }
  8219. } ConvertDiagnoser;
  8220. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  8221. }
  8222. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  8223. OpenMPClauseKind CKind,
  8224. bool StrictlyPositive) {
  8225. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  8226. !ValExpr->isInstantiationDependent()) {
  8227. SourceLocation Loc = ValExpr->getExprLoc();
  8228. ExprResult Value =
  8229. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  8230. if (Value.isInvalid())
  8231. return false;
  8232. ValExpr = Value.get();
  8233. // The expression must evaluate to a non-negative integer value.
  8234. llvm::APSInt Result;
  8235. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  8236. Result.isSigned() &&
  8237. !((!StrictlyPositive && Result.isNonNegative()) ||
  8238. (StrictlyPositive && Result.isStrictlyPositive()))) {
  8239. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  8240. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8241. << ValExpr->getSourceRange();
  8242. return false;
  8243. }
  8244. }
  8245. return true;
  8246. }
  8247. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  8248. SourceLocation StartLoc,
  8249. SourceLocation LParenLoc,
  8250. SourceLocation EndLoc) {
  8251. Expr *ValExpr = NumThreads;
  8252. Stmt *HelperValStmt = nullptr;
  8253. // OpenMP [2.5, Restrictions]
  8254. // The num_threads expression must evaluate to a positive integer value.
  8255. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  8256. /*StrictlyPositive=*/true))
  8257. return nullptr;
  8258. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8259. OpenMPDirectiveKind CaptureRegion =
  8260. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  8261. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8262. ValExpr = MakeFullExpr(ValExpr).get();
  8263. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8264. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8265. HelperValStmt = buildPreInits(Context, Captures);
  8266. }
  8267. return new (Context) OMPNumThreadsClause(
  8268. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  8269. }
  8270. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  8271. OpenMPClauseKind CKind,
  8272. bool StrictlyPositive) {
  8273. if (!E)
  8274. return ExprError();
  8275. if (E->isValueDependent() || E->isTypeDependent() ||
  8276. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  8277. return E;
  8278. llvm::APSInt Result;
  8279. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  8280. if (ICE.isInvalid())
  8281. return ExprError();
  8282. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  8283. (!StrictlyPositive && !Result.isNonNegative())) {
  8284. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  8285. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8286. << E->getSourceRange();
  8287. return ExprError();
  8288. }
  8289. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  8290. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  8291. << E->getSourceRange();
  8292. return ExprError();
  8293. }
  8294. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  8295. DSAStack->setAssociatedLoops(Result.getExtValue());
  8296. else if (CKind == OMPC_ordered)
  8297. DSAStack->setAssociatedLoops(Result.getExtValue());
  8298. return ICE;
  8299. }
  8300. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  8301. SourceLocation LParenLoc,
  8302. SourceLocation EndLoc) {
  8303. // OpenMP [2.8.1, simd construct, Description]
  8304. // The parameter of the safelen clause must be a constant
  8305. // positive integer expression.
  8306. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  8307. if (Safelen.isInvalid())
  8308. return nullptr;
  8309. return new (Context)
  8310. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  8311. }
  8312. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8313. SourceLocation LParenLoc,
  8314. SourceLocation EndLoc) {
  8315. // OpenMP [2.8.1, simd construct, Description]
  8316. // The parameter of the simdlen clause must be a constant
  8317. // positive integer expression.
  8318. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8319. if (Simdlen.isInvalid())
  8320. return nullptr;
  8321. return new (Context)
  8322. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8323. }
  8324. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  8325. SourceLocation StartLoc,
  8326. SourceLocation LParenLoc,
  8327. SourceLocation EndLoc) {
  8328. // OpenMP [2.7.1, loop construct, Description]
  8329. // OpenMP [2.8.1, simd construct, Description]
  8330. // OpenMP [2.9.6, distribute construct, Description]
  8331. // The parameter of the collapse clause must be a constant
  8332. // positive integer expression.
  8333. ExprResult NumForLoopsResult =
  8334. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  8335. if (NumForLoopsResult.isInvalid())
  8336. return nullptr;
  8337. return new (Context)
  8338. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  8339. }
  8340. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  8341. SourceLocation EndLoc,
  8342. SourceLocation LParenLoc,
  8343. Expr *NumForLoops) {
  8344. // OpenMP [2.7.1, loop construct, Description]
  8345. // OpenMP [2.8.1, simd construct, Description]
  8346. // OpenMP [2.9.6, distribute construct, Description]
  8347. // The parameter of the ordered clause must be a constant
  8348. // positive integer expression if any.
  8349. if (NumForLoops && LParenLoc.isValid()) {
  8350. ExprResult NumForLoopsResult =
  8351. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  8352. if (NumForLoopsResult.isInvalid())
  8353. return nullptr;
  8354. NumForLoops = NumForLoopsResult.get();
  8355. } else {
  8356. NumForLoops = nullptr;
  8357. }
  8358. auto *Clause = OMPOrderedClause::Create(
  8359. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  8360. StartLoc, LParenLoc, EndLoc);
  8361. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  8362. return Clause;
  8363. }
  8364. OMPClause *Sema::ActOnOpenMPSimpleClause(
  8365. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  8366. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8367. OMPClause *Res = nullptr;
  8368. switch (Kind) {
  8369. case OMPC_default:
  8370. Res =
  8371. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  8372. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8373. break;
  8374. case OMPC_proc_bind:
  8375. Res = ActOnOpenMPProcBindClause(
  8376. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  8377. LParenLoc, EndLoc);
  8378. break;
  8379. case OMPC_if:
  8380. case OMPC_final:
  8381. case OMPC_num_threads:
  8382. case OMPC_safelen:
  8383. case OMPC_simdlen:
  8384. case OMPC_collapse:
  8385. case OMPC_schedule:
  8386. case OMPC_private:
  8387. case OMPC_firstprivate:
  8388. case OMPC_lastprivate:
  8389. case OMPC_shared:
  8390. case OMPC_reduction:
  8391. case OMPC_task_reduction:
  8392. case OMPC_in_reduction:
  8393. case OMPC_linear:
  8394. case OMPC_aligned:
  8395. case OMPC_copyin:
  8396. case OMPC_copyprivate:
  8397. case OMPC_ordered:
  8398. case OMPC_nowait:
  8399. case OMPC_untied:
  8400. case OMPC_mergeable:
  8401. case OMPC_threadprivate:
  8402. case OMPC_flush:
  8403. case OMPC_read:
  8404. case OMPC_write:
  8405. case OMPC_update:
  8406. case OMPC_capture:
  8407. case OMPC_seq_cst:
  8408. case OMPC_depend:
  8409. case OMPC_device:
  8410. case OMPC_threads:
  8411. case OMPC_simd:
  8412. case OMPC_map:
  8413. case OMPC_num_teams:
  8414. case OMPC_thread_limit:
  8415. case OMPC_priority:
  8416. case OMPC_grainsize:
  8417. case OMPC_nogroup:
  8418. case OMPC_num_tasks:
  8419. case OMPC_hint:
  8420. case OMPC_dist_schedule:
  8421. case OMPC_defaultmap:
  8422. case OMPC_unknown:
  8423. case OMPC_uniform:
  8424. case OMPC_to:
  8425. case OMPC_from:
  8426. case OMPC_use_device_ptr:
  8427. case OMPC_is_device_ptr:
  8428. case OMPC_unified_address:
  8429. case OMPC_unified_shared_memory:
  8430. case OMPC_reverse_offload:
  8431. case OMPC_dynamic_allocators:
  8432. llvm_unreachable("Clause is not allowed.");
  8433. }
  8434. return Res;
  8435. }
  8436. static std::string
  8437. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  8438. ArrayRef<unsigned> Exclude = llvm::None) {
  8439. SmallString<256> Buffer;
  8440. llvm::raw_svector_ostream Out(Buffer);
  8441. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  8442. unsigned Skipped = Exclude.size();
  8443. auto S = Exclude.begin(), E = Exclude.end();
  8444. for (unsigned I = First; I < Last; ++I) {
  8445. if (std::find(S, E, I) != E) {
  8446. --Skipped;
  8447. continue;
  8448. }
  8449. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  8450. if (I == Bound - Skipped)
  8451. Out << " or ";
  8452. else if (I != Bound + 1 - Skipped)
  8453. Out << ", ";
  8454. }
  8455. return Out.str();
  8456. }
  8457. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  8458. SourceLocation KindKwLoc,
  8459. SourceLocation StartLoc,
  8460. SourceLocation LParenLoc,
  8461. SourceLocation EndLoc) {
  8462. if (Kind == OMPC_DEFAULT_unknown) {
  8463. static_assert(OMPC_DEFAULT_unknown > 0,
  8464. "OMPC_DEFAULT_unknown not greater than 0");
  8465. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8466. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  8467. /*Last=*/OMPC_DEFAULT_unknown)
  8468. << getOpenMPClauseName(OMPC_default);
  8469. return nullptr;
  8470. }
  8471. switch (Kind) {
  8472. case OMPC_DEFAULT_none:
  8473. DSAStack->setDefaultDSANone(KindKwLoc);
  8474. break;
  8475. case OMPC_DEFAULT_shared:
  8476. DSAStack->setDefaultDSAShared(KindKwLoc);
  8477. break;
  8478. case OMPC_DEFAULT_unknown:
  8479. llvm_unreachable("Clause kind is not allowed.");
  8480. break;
  8481. }
  8482. return new (Context)
  8483. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8484. }
  8485. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  8486. SourceLocation KindKwLoc,
  8487. SourceLocation StartLoc,
  8488. SourceLocation LParenLoc,
  8489. SourceLocation EndLoc) {
  8490. if (Kind == OMPC_PROC_BIND_unknown) {
  8491. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8492. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  8493. /*Last=*/OMPC_PROC_BIND_unknown)
  8494. << getOpenMPClauseName(OMPC_proc_bind);
  8495. return nullptr;
  8496. }
  8497. return new (Context)
  8498. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8499. }
  8500. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  8501. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  8502. SourceLocation StartLoc, SourceLocation LParenLoc,
  8503. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  8504. SourceLocation EndLoc) {
  8505. OMPClause *Res = nullptr;
  8506. switch (Kind) {
  8507. case OMPC_schedule:
  8508. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  8509. assert(Argument.size() == NumberOfElements &&
  8510. ArgumentLoc.size() == NumberOfElements);
  8511. Res = ActOnOpenMPScheduleClause(
  8512. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  8513. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  8514. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  8515. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  8516. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  8517. break;
  8518. case OMPC_if:
  8519. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  8520. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  8521. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  8522. DelimLoc, EndLoc);
  8523. break;
  8524. case OMPC_dist_schedule:
  8525. Res = ActOnOpenMPDistScheduleClause(
  8526. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  8527. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  8528. break;
  8529. case OMPC_defaultmap:
  8530. enum { Modifier, DefaultmapKind };
  8531. Res = ActOnOpenMPDefaultmapClause(
  8532. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  8533. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  8534. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  8535. EndLoc);
  8536. break;
  8537. case OMPC_final:
  8538. case OMPC_num_threads:
  8539. case OMPC_safelen:
  8540. case OMPC_simdlen:
  8541. case OMPC_collapse:
  8542. case OMPC_default:
  8543. case OMPC_proc_bind:
  8544. case OMPC_private:
  8545. case OMPC_firstprivate:
  8546. case OMPC_lastprivate:
  8547. case OMPC_shared:
  8548. case OMPC_reduction:
  8549. case OMPC_task_reduction:
  8550. case OMPC_in_reduction:
  8551. case OMPC_linear:
  8552. case OMPC_aligned:
  8553. case OMPC_copyin:
  8554. case OMPC_copyprivate:
  8555. case OMPC_ordered:
  8556. case OMPC_nowait:
  8557. case OMPC_untied:
  8558. case OMPC_mergeable:
  8559. case OMPC_threadprivate:
  8560. case OMPC_flush:
  8561. case OMPC_read:
  8562. case OMPC_write:
  8563. case OMPC_update:
  8564. case OMPC_capture:
  8565. case OMPC_seq_cst:
  8566. case OMPC_depend:
  8567. case OMPC_device:
  8568. case OMPC_threads:
  8569. case OMPC_simd:
  8570. case OMPC_map:
  8571. case OMPC_num_teams:
  8572. case OMPC_thread_limit:
  8573. case OMPC_priority:
  8574. case OMPC_grainsize:
  8575. case OMPC_nogroup:
  8576. case OMPC_num_tasks:
  8577. case OMPC_hint:
  8578. case OMPC_unknown:
  8579. case OMPC_uniform:
  8580. case OMPC_to:
  8581. case OMPC_from:
  8582. case OMPC_use_device_ptr:
  8583. case OMPC_is_device_ptr:
  8584. case OMPC_unified_address:
  8585. case OMPC_unified_shared_memory:
  8586. case OMPC_reverse_offload:
  8587. case OMPC_dynamic_allocators:
  8588. llvm_unreachable("Clause is not allowed.");
  8589. }
  8590. return Res;
  8591. }
  8592. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8593. OpenMPScheduleClauseModifier M2,
  8594. SourceLocation M1Loc, SourceLocation M2Loc) {
  8595. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8596. SmallVector<unsigned, 2> Excluded;
  8597. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8598. Excluded.push_back(M2);
  8599. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8600. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8601. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8602. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8603. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8604. << getListOfPossibleValues(OMPC_schedule,
  8605. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8606. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8607. Excluded)
  8608. << getOpenMPClauseName(OMPC_schedule);
  8609. return true;
  8610. }
  8611. return false;
  8612. }
  8613. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8614. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8615. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8616. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8617. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8618. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8619. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8620. return nullptr;
  8621. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8622. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8623. // but not both.
  8624. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8625. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8626. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8627. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8628. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8629. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8630. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8631. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8632. return nullptr;
  8633. }
  8634. if (Kind == OMPC_SCHEDULE_unknown) {
  8635. std::string Values;
  8636. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8637. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8638. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8639. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8640. Exclude);
  8641. } else {
  8642. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8643. /*Last=*/OMPC_SCHEDULE_unknown);
  8644. }
  8645. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8646. << Values << getOpenMPClauseName(OMPC_schedule);
  8647. return nullptr;
  8648. }
  8649. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8650. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8651. // schedule(guided).
  8652. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8653. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8654. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8655. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8656. diag::err_omp_schedule_nonmonotonic_static);
  8657. return nullptr;
  8658. }
  8659. Expr *ValExpr = ChunkSize;
  8660. Stmt *HelperValStmt = nullptr;
  8661. if (ChunkSize) {
  8662. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8663. !ChunkSize->isInstantiationDependent() &&
  8664. !ChunkSize->containsUnexpandedParameterPack()) {
  8665. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  8666. ExprResult Val =
  8667. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8668. if (Val.isInvalid())
  8669. return nullptr;
  8670. ValExpr = Val.get();
  8671. // OpenMP [2.7.1, Restrictions]
  8672. // chunk_size must be a loop invariant integer expression with a positive
  8673. // value.
  8674. llvm::APSInt Result;
  8675. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8676. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8677. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8678. << "schedule" << 1 << ChunkSize->getSourceRange();
  8679. return nullptr;
  8680. }
  8681. } else if (getOpenMPCaptureRegionForClause(
  8682. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8683. OMPD_unknown &&
  8684. !CurContext->isDependentContext()) {
  8685. ValExpr = MakeFullExpr(ValExpr).get();
  8686. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8687. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8688. HelperValStmt = buildPreInits(Context, Captures);
  8689. }
  8690. }
  8691. }
  8692. return new (Context)
  8693. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8694. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8695. }
  8696. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8697. SourceLocation StartLoc,
  8698. SourceLocation EndLoc) {
  8699. OMPClause *Res = nullptr;
  8700. switch (Kind) {
  8701. case OMPC_ordered:
  8702. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8703. break;
  8704. case OMPC_nowait:
  8705. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8706. break;
  8707. case OMPC_untied:
  8708. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8709. break;
  8710. case OMPC_mergeable:
  8711. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8712. break;
  8713. case OMPC_read:
  8714. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8715. break;
  8716. case OMPC_write:
  8717. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8718. break;
  8719. case OMPC_update:
  8720. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8721. break;
  8722. case OMPC_capture:
  8723. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8724. break;
  8725. case OMPC_seq_cst:
  8726. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8727. break;
  8728. case OMPC_threads:
  8729. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8730. break;
  8731. case OMPC_simd:
  8732. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8733. break;
  8734. case OMPC_nogroup:
  8735. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8736. break;
  8737. case OMPC_unified_address:
  8738. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  8739. break;
  8740. case OMPC_unified_shared_memory:
  8741. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8742. break;
  8743. case OMPC_reverse_offload:
  8744. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  8745. break;
  8746. case OMPC_dynamic_allocators:
  8747. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8748. break;
  8749. case OMPC_if:
  8750. case OMPC_final:
  8751. case OMPC_num_threads:
  8752. case OMPC_safelen:
  8753. case OMPC_simdlen:
  8754. case OMPC_collapse:
  8755. case OMPC_schedule:
  8756. case OMPC_private:
  8757. case OMPC_firstprivate:
  8758. case OMPC_lastprivate:
  8759. case OMPC_shared:
  8760. case OMPC_reduction:
  8761. case OMPC_task_reduction:
  8762. case OMPC_in_reduction:
  8763. case OMPC_linear:
  8764. case OMPC_aligned:
  8765. case OMPC_copyin:
  8766. case OMPC_copyprivate:
  8767. case OMPC_default:
  8768. case OMPC_proc_bind:
  8769. case OMPC_threadprivate:
  8770. case OMPC_flush:
  8771. case OMPC_depend:
  8772. case OMPC_device:
  8773. case OMPC_map:
  8774. case OMPC_num_teams:
  8775. case OMPC_thread_limit:
  8776. case OMPC_priority:
  8777. case OMPC_grainsize:
  8778. case OMPC_num_tasks:
  8779. case OMPC_hint:
  8780. case OMPC_dist_schedule:
  8781. case OMPC_defaultmap:
  8782. case OMPC_unknown:
  8783. case OMPC_uniform:
  8784. case OMPC_to:
  8785. case OMPC_from:
  8786. case OMPC_use_device_ptr:
  8787. case OMPC_is_device_ptr:
  8788. llvm_unreachable("Clause is not allowed.");
  8789. }
  8790. return Res;
  8791. }
  8792. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8793. SourceLocation EndLoc) {
  8794. DSAStack->setNowaitRegion();
  8795. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8796. }
  8797. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8798. SourceLocation EndLoc) {
  8799. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8800. }
  8801. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8802. SourceLocation EndLoc) {
  8803. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8804. }
  8805. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8806. SourceLocation EndLoc) {
  8807. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8808. }
  8809. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8810. SourceLocation EndLoc) {
  8811. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8812. }
  8813. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8814. SourceLocation EndLoc) {
  8815. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8816. }
  8817. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8818. SourceLocation EndLoc) {
  8819. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8820. }
  8821. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8822. SourceLocation EndLoc) {
  8823. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8824. }
  8825. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8826. SourceLocation EndLoc) {
  8827. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8828. }
  8829. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8830. SourceLocation EndLoc) {
  8831. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8832. }
  8833. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8834. SourceLocation EndLoc) {
  8835. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8836. }
  8837. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  8838. SourceLocation EndLoc) {
  8839. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  8840. }
  8841. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  8842. SourceLocation EndLoc) {
  8843. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8844. }
  8845. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  8846. SourceLocation EndLoc) {
  8847. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  8848. }
  8849. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  8850. SourceLocation EndLoc) {
  8851. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8852. }
  8853. OMPClause *Sema::ActOnOpenMPVarListClause(
  8854. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8855. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8856. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8857. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8858. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8859. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8860. SourceLocation DepLinMapLoc) {
  8861. OMPClause *Res = nullptr;
  8862. switch (Kind) {
  8863. case OMPC_private:
  8864. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8865. break;
  8866. case OMPC_firstprivate:
  8867. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8868. break;
  8869. case OMPC_lastprivate:
  8870. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8871. break;
  8872. case OMPC_shared:
  8873. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8874. break;
  8875. case OMPC_reduction:
  8876. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8877. EndLoc, ReductionIdScopeSpec, ReductionId);
  8878. break;
  8879. case OMPC_task_reduction:
  8880. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8881. EndLoc, ReductionIdScopeSpec,
  8882. ReductionId);
  8883. break;
  8884. case OMPC_in_reduction:
  8885. Res =
  8886. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8887. EndLoc, ReductionIdScopeSpec, ReductionId);
  8888. break;
  8889. case OMPC_linear:
  8890. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8891. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8892. break;
  8893. case OMPC_aligned:
  8894. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8895. ColonLoc, EndLoc);
  8896. break;
  8897. case OMPC_copyin:
  8898. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8899. break;
  8900. case OMPC_copyprivate:
  8901. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8902. break;
  8903. case OMPC_flush:
  8904. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8905. break;
  8906. case OMPC_depend:
  8907. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8908. StartLoc, LParenLoc, EndLoc);
  8909. break;
  8910. case OMPC_map:
  8911. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8912. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8913. LParenLoc, EndLoc);
  8914. break;
  8915. case OMPC_to:
  8916. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8917. break;
  8918. case OMPC_from:
  8919. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8920. break;
  8921. case OMPC_use_device_ptr:
  8922. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8923. break;
  8924. case OMPC_is_device_ptr:
  8925. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8926. break;
  8927. case OMPC_if:
  8928. case OMPC_final:
  8929. case OMPC_num_threads:
  8930. case OMPC_safelen:
  8931. case OMPC_simdlen:
  8932. case OMPC_collapse:
  8933. case OMPC_default:
  8934. case OMPC_proc_bind:
  8935. case OMPC_schedule:
  8936. case OMPC_ordered:
  8937. case OMPC_nowait:
  8938. case OMPC_untied:
  8939. case OMPC_mergeable:
  8940. case OMPC_threadprivate:
  8941. case OMPC_read:
  8942. case OMPC_write:
  8943. case OMPC_update:
  8944. case OMPC_capture:
  8945. case OMPC_seq_cst:
  8946. case OMPC_device:
  8947. case OMPC_threads:
  8948. case OMPC_simd:
  8949. case OMPC_num_teams:
  8950. case OMPC_thread_limit:
  8951. case OMPC_priority:
  8952. case OMPC_grainsize:
  8953. case OMPC_nogroup:
  8954. case OMPC_num_tasks:
  8955. case OMPC_hint:
  8956. case OMPC_dist_schedule:
  8957. case OMPC_defaultmap:
  8958. case OMPC_unknown:
  8959. case OMPC_uniform:
  8960. case OMPC_unified_address:
  8961. case OMPC_unified_shared_memory:
  8962. case OMPC_reverse_offload:
  8963. case OMPC_dynamic_allocators:
  8964. llvm_unreachable("Clause is not allowed.");
  8965. }
  8966. return Res;
  8967. }
  8968. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  8969. ExprObjectKind OK, SourceLocation Loc) {
  8970. ExprResult Res = BuildDeclRefExpr(
  8971. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  8972. if (!Res.isUsable())
  8973. return ExprError();
  8974. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  8975. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  8976. if (!Res.isUsable())
  8977. return ExprError();
  8978. }
  8979. if (VK != VK_LValue && Res.get()->isGLValue()) {
  8980. Res = DefaultLvalueConversion(Res.get());
  8981. if (!Res.isUsable())
  8982. return ExprError();
  8983. }
  8984. return Res;
  8985. }
  8986. static std::pair<ValueDecl *, bool>
  8987. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  8988. SourceRange &ERange, bool AllowArraySection = false) {
  8989. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  8990. RefExpr->containsUnexpandedParameterPack())
  8991. return std::make_pair(nullptr, true);
  8992. // OpenMP [3.1, C/C++]
  8993. // A list item is a variable name.
  8994. // OpenMP [2.9.3.3, Restrictions, p.1]
  8995. // A variable that is part of another variable (as an array or
  8996. // structure element) cannot appear in a private clause.
  8997. RefExpr = RefExpr->IgnoreParens();
  8998. enum {
  8999. NoArrayExpr = -1,
  9000. ArraySubscript = 0,
  9001. OMPArraySection = 1
  9002. } IsArrayExpr = NoArrayExpr;
  9003. if (AllowArraySection) {
  9004. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  9005. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  9006. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9007. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9008. RefExpr = Base;
  9009. IsArrayExpr = ArraySubscript;
  9010. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  9011. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9012. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  9013. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9014. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9015. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9016. RefExpr = Base;
  9017. IsArrayExpr = OMPArraySection;
  9018. }
  9019. }
  9020. ELoc = RefExpr->getExprLoc();
  9021. ERange = RefExpr->getSourceRange();
  9022. RefExpr = RefExpr->IgnoreParenImpCasts();
  9023. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  9024. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  9025. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  9026. (S.getCurrentThisType().isNull() || !ME ||
  9027. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  9028. !isa<FieldDecl>(ME->getMemberDecl()))) {
  9029. if (IsArrayExpr != NoArrayExpr) {
  9030. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  9031. << ERange;
  9032. } else {
  9033. S.Diag(ELoc,
  9034. AllowArraySection
  9035. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  9036. : diag::err_omp_expected_var_name_member_expr)
  9037. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  9038. }
  9039. return std::make_pair(nullptr, false);
  9040. }
  9041. return std::make_pair(
  9042. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  9043. }
  9044. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  9045. SourceLocation StartLoc,
  9046. SourceLocation LParenLoc,
  9047. SourceLocation EndLoc) {
  9048. SmallVector<Expr *, 8> Vars;
  9049. SmallVector<Expr *, 8> PrivateCopies;
  9050. for (Expr *RefExpr : VarList) {
  9051. assert(RefExpr && "NULL expr in OpenMP private clause.");
  9052. SourceLocation ELoc;
  9053. SourceRange ERange;
  9054. Expr *SimpleRefExpr = RefExpr;
  9055. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9056. if (Res.second) {
  9057. // It will be analyzed later.
  9058. Vars.push_back(RefExpr);
  9059. PrivateCopies.push_back(nullptr);
  9060. }
  9061. ValueDecl *D = Res.first;
  9062. if (!D)
  9063. continue;
  9064. QualType Type = D->getType();
  9065. auto *VD = dyn_cast<VarDecl>(D);
  9066. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9067. // A variable that appears in a private clause must not have an incomplete
  9068. // type or a reference type.
  9069. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  9070. continue;
  9071. Type = Type.getNonReferenceType();
  9072. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9073. // in a Construct]
  9074. // Variables with the predetermined data-sharing attributes may not be
  9075. // listed in data-sharing attributes clauses, except for the cases
  9076. // listed below. For these exceptions only, listing a predetermined
  9077. // variable in a data-sharing attribute clause is allowed and overrides
  9078. // the variable's predetermined data-sharing attributes.
  9079. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9080. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  9081. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9082. << getOpenMPClauseName(OMPC_private);
  9083. reportOriginalDsa(*this, DSAStack, D, DVar);
  9084. continue;
  9085. }
  9086. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9087. // Variably modified types are not supported for tasks.
  9088. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9089. isOpenMPTaskingDirective(CurrDir)) {
  9090. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9091. << getOpenMPClauseName(OMPC_private) << Type
  9092. << getOpenMPDirectiveName(CurrDir);
  9093. bool IsDecl =
  9094. !VD ||
  9095. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9096. Diag(D->getLocation(),
  9097. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9098. << D;
  9099. continue;
  9100. }
  9101. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9102. // A list item cannot appear in both a map clause and a data-sharing
  9103. // attribute clause on the same construct
  9104. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9105. OpenMPClauseKind ConflictKind;
  9106. if (DSAStack->checkMappableExprComponentListsForDecl(
  9107. VD, /*CurrentRegionOnly=*/true,
  9108. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9109. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  9110. ConflictKind = WhereFoundClauseKind;
  9111. return true;
  9112. })) {
  9113. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9114. << getOpenMPClauseName(OMPC_private)
  9115. << getOpenMPClauseName(ConflictKind)
  9116. << getOpenMPDirectiveName(CurrDir);
  9117. reportOriginalDsa(*this, DSAStack, D, DVar);
  9118. continue;
  9119. }
  9120. }
  9121. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  9122. // A variable of class type (or array thereof) that appears in a private
  9123. // clause requires an accessible, unambiguous default constructor for the
  9124. // class type.
  9125. // Generate helper private variable and initialize it with the default
  9126. // value. The address of the original variable is replaced by the address of
  9127. // the new private variable in CodeGen. This new variable is not added to
  9128. // IdResolver, so the code in the OpenMP region uses original variable for
  9129. // proper diagnostics.
  9130. Type = Type.getUnqualifiedType();
  9131. VarDecl *VDPrivate =
  9132. buildVarDecl(*this, ELoc, Type, D->getName(),
  9133. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9134. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9135. ActOnUninitializedDecl(VDPrivate);
  9136. if (VDPrivate->isInvalidDecl())
  9137. continue;
  9138. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9139. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  9140. DeclRefExpr *Ref = nullptr;
  9141. if (!VD && !CurContext->isDependentContext())
  9142. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9143. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  9144. Vars.push_back((VD || CurContext->isDependentContext())
  9145. ? RefExpr->IgnoreParens()
  9146. : Ref);
  9147. PrivateCopies.push_back(VDPrivateRefExpr);
  9148. }
  9149. if (Vars.empty())
  9150. return nullptr;
  9151. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9152. PrivateCopies);
  9153. }
  9154. namespace {
  9155. class DiagsUninitializedSeveretyRAII {
  9156. private:
  9157. DiagnosticsEngine &Diags;
  9158. SourceLocation SavedLoc;
  9159. bool IsIgnored = false;
  9160. public:
  9161. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  9162. bool IsIgnored)
  9163. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  9164. if (!IsIgnored) {
  9165. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  9166. /*Map*/ diag::Severity::Ignored, Loc);
  9167. }
  9168. }
  9169. ~DiagsUninitializedSeveretyRAII() {
  9170. if (!IsIgnored)
  9171. Diags.popMappings(SavedLoc);
  9172. }
  9173. };
  9174. }
  9175. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  9176. SourceLocation StartLoc,
  9177. SourceLocation LParenLoc,
  9178. SourceLocation EndLoc) {
  9179. SmallVector<Expr *, 8> Vars;
  9180. SmallVector<Expr *, 8> PrivateCopies;
  9181. SmallVector<Expr *, 8> Inits;
  9182. SmallVector<Decl *, 4> ExprCaptures;
  9183. bool IsImplicitClause =
  9184. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  9185. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  9186. for (Expr *RefExpr : VarList) {
  9187. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  9188. SourceLocation ELoc;
  9189. SourceRange ERange;
  9190. Expr *SimpleRefExpr = RefExpr;
  9191. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9192. if (Res.second) {
  9193. // It will be analyzed later.
  9194. Vars.push_back(RefExpr);
  9195. PrivateCopies.push_back(nullptr);
  9196. Inits.push_back(nullptr);
  9197. }
  9198. ValueDecl *D = Res.first;
  9199. if (!D)
  9200. continue;
  9201. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  9202. QualType Type = D->getType();
  9203. auto *VD = dyn_cast<VarDecl>(D);
  9204. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9205. // A variable that appears in a private clause must not have an incomplete
  9206. // type or a reference type.
  9207. if (RequireCompleteType(ELoc, Type,
  9208. diag::err_omp_firstprivate_incomplete_type))
  9209. continue;
  9210. Type = Type.getNonReferenceType();
  9211. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  9212. // A variable of class type (or array thereof) that appears in a private
  9213. // clause requires an accessible, unambiguous copy constructor for the
  9214. // class type.
  9215. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9216. // If an implicit firstprivate variable found it was checked already.
  9217. DSAStackTy::DSAVarData TopDVar;
  9218. if (!IsImplicitClause) {
  9219. DSAStackTy::DSAVarData DVar =
  9220. DSAStack->getTopDSA(D, /*FromParent=*/false);
  9221. TopDVar = DVar;
  9222. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9223. bool IsConstant = ElemType.isConstant(Context);
  9224. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  9225. // A list item that specifies a given variable may not appear in more
  9226. // than one clause on the same directive, except that a variable may be
  9227. // specified in both firstprivate and lastprivate clauses.
  9228. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9229. // A list item may appear in a firstprivate or lastprivate clause but not
  9230. // both.
  9231. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  9232. (isOpenMPDistributeDirective(CurrDir) ||
  9233. DVar.CKind != OMPC_lastprivate) &&
  9234. DVar.RefExpr) {
  9235. Diag(ELoc, diag::err_omp_wrong_dsa)
  9236. << getOpenMPClauseName(DVar.CKind)
  9237. << getOpenMPClauseName(OMPC_firstprivate);
  9238. reportOriginalDsa(*this, DSAStack, D, DVar);
  9239. continue;
  9240. }
  9241. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9242. // in a Construct]
  9243. // Variables with the predetermined data-sharing attributes may not be
  9244. // listed in data-sharing attributes clauses, except for the cases
  9245. // listed below. For these exceptions only, listing a predetermined
  9246. // variable in a data-sharing attribute clause is allowed and overrides
  9247. // the variable's predetermined data-sharing attributes.
  9248. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9249. // in a Construct, C/C++, p.2]
  9250. // Variables with const-qualified type having no mutable member may be
  9251. // listed in a firstprivate clause, even if they are static data members.
  9252. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  9253. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  9254. Diag(ELoc, diag::err_omp_wrong_dsa)
  9255. << getOpenMPClauseName(DVar.CKind)
  9256. << getOpenMPClauseName(OMPC_firstprivate);
  9257. reportOriginalDsa(*this, DSAStack, D, DVar);
  9258. continue;
  9259. }
  9260. // OpenMP [2.9.3.4, Restrictions, p.2]
  9261. // A list item that is private within a parallel region must not appear
  9262. // in a firstprivate clause on a worksharing construct if any of the
  9263. // worksharing regions arising from the worksharing construct ever bind
  9264. // to any of the parallel regions arising from the parallel construct.
  9265. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9266. // A list item that is private within a teams region must not appear in a
  9267. // firstprivate clause on a distribute construct if any of the distribute
  9268. // regions arising from the distribute construct ever bind to any of the
  9269. // teams regions arising from the teams construct.
  9270. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9271. // A list item that appears in a reduction clause of a teams construct
  9272. // must not appear in a firstprivate clause on a distribute construct if
  9273. // any of the distribute regions arising from the distribute construct
  9274. // ever bind to any of the teams regions arising from the teams construct.
  9275. if ((isOpenMPWorksharingDirective(CurrDir) ||
  9276. isOpenMPDistributeDirective(CurrDir)) &&
  9277. !isOpenMPParallelDirective(CurrDir) &&
  9278. !isOpenMPTeamsDirective(CurrDir)) {
  9279. DVar = DSAStack->getImplicitDSA(D, true);
  9280. if (DVar.CKind != OMPC_shared &&
  9281. (isOpenMPParallelDirective(DVar.DKind) ||
  9282. isOpenMPTeamsDirective(DVar.DKind) ||
  9283. DVar.DKind == OMPD_unknown)) {
  9284. Diag(ELoc, diag::err_omp_required_access)
  9285. << getOpenMPClauseName(OMPC_firstprivate)
  9286. << getOpenMPClauseName(OMPC_shared);
  9287. reportOriginalDsa(*this, DSAStack, D, DVar);
  9288. continue;
  9289. }
  9290. }
  9291. // OpenMP [2.9.3.4, Restrictions, p.3]
  9292. // A list item that appears in a reduction clause of a parallel construct
  9293. // must not appear in a firstprivate clause on a worksharing or task
  9294. // construct if any of the worksharing or task regions arising from the
  9295. // worksharing or task construct ever bind to any of the parallel regions
  9296. // arising from the parallel construct.
  9297. // OpenMP [2.9.3.4, Restrictions, p.4]
  9298. // A list item that appears in a reduction clause in worksharing
  9299. // construct must not appear in a firstprivate clause in a task construct
  9300. // encountered during execution of any of the worksharing regions arising
  9301. // from the worksharing construct.
  9302. if (isOpenMPTaskingDirective(CurrDir)) {
  9303. DVar = DSAStack->hasInnermostDSA(
  9304. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  9305. [](OpenMPDirectiveKind K) {
  9306. return isOpenMPParallelDirective(K) ||
  9307. isOpenMPWorksharingDirective(K) ||
  9308. isOpenMPTeamsDirective(K);
  9309. },
  9310. /*FromParent=*/true);
  9311. if (DVar.CKind == OMPC_reduction &&
  9312. (isOpenMPParallelDirective(DVar.DKind) ||
  9313. isOpenMPWorksharingDirective(DVar.DKind) ||
  9314. isOpenMPTeamsDirective(DVar.DKind))) {
  9315. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  9316. << getOpenMPDirectiveName(DVar.DKind);
  9317. reportOriginalDsa(*this, DSAStack, D, DVar);
  9318. continue;
  9319. }
  9320. }
  9321. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9322. // A list item cannot appear in both a map clause and a data-sharing
  9323. // attribute clause on the same construct
  9324. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9325. OpenMPClauseKind ConflictKind;
  9326. if (DSAStack->checkMappableExprComponentListsForDecl(
  9327. VD, /*CurrentRegionOnly=*/true,
  9328. [&ConflictKind](
  9329. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9330. OpenMPClauseKind WhereFoundClauseKind) {
  9331. ConflictKind = WhereFoundClauseKind;
  9332. return true;
  9333. })) {
  9334. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9335. << getOpenMPClauseName(OMPC_firstprivate)
  9336. << getOpenMPClauseName(ConflictKind)
  9337. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9338. reportOriginalDsa(*this, DSAStack, D, DVar);
  9339. continue;
  9340. }
  9341. }
  9342. }
  9343. // Variably modified types are not supported for tasks.
  9344. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9345. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  9346. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9347. << getOpenMPClauseName(OMPC_firstprivate) << Type
  9348. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9349. bool IsDecl =
  9350. !VD ||
  9351. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9352. Diag(D->getLocation(),
  9353. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9354. << D;
  9355. continue;
  9356. }
  9357. Type = Type.getUnqualifiedType();
  9358. VarDecl *VDPrivate =
  9359. buildVarDecl(*this, ELoc, Type, D->getName(),
  9360. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9361. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9362. // Generate helper private variable and initialize it with the value of the
  9363. // original variable. The address of the original variable is replaced by
  9364. // the address of the new private variable in the CodeGen. This new variable
  9365. // is not added to IdResolver, so the code in the OpenMP region uses
  9366. // original variable for proper diagnostics and variable capturing.
  9367. Expr *VDInitRefExpr = nullptr;
  9368. // For arrays generate initializer for single element and replace it by the
  9369. // original array element in CodeGen.
  9370. if (Type->isArrayType()) {
  9371. VarDecl *VDInit =
  9372. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  9373. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  9374. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  9375. ElemType = ElemType.getUnqualifiedType();
  9376. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  9377. ".firstprivate.temp");
  9378. InitializedEntity Entity =
  9379. InitializedEntity::InitializeVariable(VDInitTemp);
  9380. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  9381. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  9382. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  9383. if (Result.isInvalid())
  9384. VDPrivate->setInvalidDecl();
  9385. else
  9386. VDPrivate->setInit(Result.getAs<Expr>());
  9387. // Remove temp variable declaration.
  9388. Context.Deallocate(VDInitTemp);
  9389. } else {
  9390. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  9391. ".firstprivate.temp");
  9392. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  9393. RefExpr->getExprLoc());
  9394. AddInitializerToDecl(VDPrivate,
  9395. DefaultLvalueConversion(VDInitRefExpr).get(),
  9396. /*DirectInit=*/false);
  9397. }
  9398. if (VDPrivate->isInvalidDecl()) {
  9399. if (IsImplicitClause) {
  9400. Diag(RefExpr->getExprLoc(),
  9401. diag::note_omp_task_predetermined_firstprivate_here);
  9402. }
  9403. continue;
  9404. }
  9405. CurContext->addDecl(VDPrivate);
  9406. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9407. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  9408. RefExpr->getExprLoc());
  9409. DeclRefExpr *Ref = nullptr;
  9410. if (!VD && !CurContext->isDependentContext()) {
  9411. if (TopDVar.CKind == OMPC_lastprivate) {
  9412. Ref = TopDVar.PrivateCopy;
  9413. } else {
  9414. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9415. if (!isOpenMPCapturedDecl(D))
  9416. ExprCaptures.push_back(Ref->getDecl());
  9417. }
  9418. }
  9419. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  9420. Vars.push_back((VD || CurContext->isDependentContext())
  9421. ? RefExpr->IgnoreParens()
  9422. : Ref);
  9423. PrivateCopies.push_back(VDPrivateRefExpr);
  9424. Inits.push_back(VDInitRefExpr);
  9425. }
  9426. if (Vars.empty())
  9427. return nullptr;
  9428. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9429. Vars, PrivateCopies, Inits,
  9430. buildPreInits(Context, ExprCaptures));
  9431. }
  9432. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  9433. SourceLocation StartLoc,
  9434. SourceLocation LParenLoc,
  9435. SourceLocation EndLoc) {
  9436. SmallVector<Expr *, 8> Vars;
  9437. SmallVector<Expr *, 8> SrcExprs;
  9438. SmallVector<Expr *, 8> DstExprs;
  9439. SmallVector<Expr *, 8> AssignmentOps;
  9440. SmallVector<Decl *, 4> ExprCaptures;
  9441. SmallVector<Expr *, 4> ExprPostUpdates;
  9442. for (Expr *RefExpr : VarList) {
  9443. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9444. SourceLocation ELoc;
  9445. SourceRange ERange;
  9446. Expr *SimpleRefExpr = RefExpr;
  9447. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9448. if (Res.second) {
  9449. // It will be analyzed later.
  9450. Vars.push_back(RefExpr);
  9451. SrcExprs.push_back(nullptr);
  9452. DstExprs.push_back(nullptr);
  9453. AssignmentOps.push_back(nullptr);
  9454. }
  9455. ValueDecl *D = Res.first;
  9456. if (!D)
  9457. continue;
  9458. QualType Type = D->getType();
  9459. auto *VD = dyn_cast<VarDecl>(D);
  9460. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  9461. // A variable that appears in a lastprivate clause must not have an
  9462. // incomplete type or a reference type.
  9463. if (RequireCompleteType(ELoc, Type,
  9464. diag::err_omp_lastprivate_incomplete_type))
  9465. continue;
  9466. Type = Type.getNonReferenceType();
  9467. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9468. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9469. // in a Construct]
  9470. // Variables with the predetermined data-sharing attributes may not be
  9471. // listed in data-sharing attributes clauses, except for the cases
  9472. // listed below.
  9473. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9474. // A list item may appear in a firstprivate or lastprivate clause but not
  9475. // both.
  9476. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9477. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  9478. (isOpenMPDistributeDirective(CurrDir) ||
  9479. DVar.CKind != OMPC_firstprivate) &&
  9480. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  9481. Diag(ELoc, diag::err_omp_wrong_dsa)
  9482. << getOpenMPClauseName(DVar.CKind)
  9483. << getOpenMPClauseName(OMPC_lastprivate);
  9484. reportOriginalDsa(*this, DSAStack, D, DVar);
  9485. continue;
  9486. }
  9487. // OpenMP [2.14.3.5, Restrictions, p.2]
  9488. // A list item that is private within a parallel region, or that appears in
  9489. // the reduction clause of a parallel construct, must not appear in a
  9490. // lastprivate clause on a worksharing construct if any of the corresponding
  9491. // worksharing regions ever binds to any of the corresponding parallel
  9492. // regions.
  9493. DSAStackTy::DSAVarData TopDVar = DVar;
  9494. if (isOpenMPWorksharingDirective(CurrDir) &&
  9495. !isOpenMPParallelDirective(CurrDir) &&
  9496. !isOpenMPTeamsDirective(CurrDir)) {
  9497. DVar = DSAStack->getImplicitDSA(D, true);
  9498. if (DVar.CKind != OMPC_shared) {
  9499. Diag(ELoc, diag::err_omp_required_access)
  9500. << getOpenMPClauseName(OMPC_lastprivate)
  9501. << getOpenMPClauseName(OMPC_shared);
  9502. reportOriginalDsa(*this, DSAStack, D, DVar);
  9503. continue;
  9504. }
  9505. }
  9506. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  9507. // A variable of class type (or array thereof) that appears in a
  9508. // lastprivate clause requires an accessible, unambiguous default
  9509. // constructor for the class type, unless the list item is also specified
  9510. // in a firstprivate clause.
  9511. // A variable of class type (or array thereof) that appears in a
  9512. // lastprivate clause requires an accessible, unambiguous copy assignment
  9513. // operator for the class type.
  9514. Type = Context.getBaseElementType(Type).getNonReferenceType();
  9515. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  9516. Type.getUnqualifiedType(), ".lastprivate.src",
  9517. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9518. DeclRefExpr *PseudoSrcExpr =
  9519. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  9520. VarDecl *DstVD =
  9521. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  9522. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9523. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9524. // For arrays generate assignment operation for single element and replace
  9525. // it by the original array element in CodeGen.
  9526. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  9527. PseudoDstExpr, PseudoSrcExpr);
  9528. if (AssignmentOp.isInvalid())
  9529. continue;
  9530. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  9531. /*DiscardedValue=*/true);
  9532. if (AssignmentOp.isInvalid())
  9533. continue;
  9534. DeclRefExpr *Ref = nullptr;
  9535. if (!VD && !CurContext->isDependentContext()) {
  9536. if (TopDVar.CKind == OMPC_firstprivate) {
  9537. Ref = TopDVar.PrivateCopy;
  9538. } else {
  9539. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9540. if (!isOpenMPCapturedDecl(D))
  9541. ExprCaptures.push_back(Ref->getDecl());
  9542. }
  9543. if (TopDVar.CKind == OMPC_firstprivate ||
  9544. (!isOpenMPCapturedDecl(D) &&
  9545. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  9546. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9547. if (!RefRes.isUsable())
  9548. continue;
  9549. ExprResult PostUpdateRes =
  9550. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9551. RefRes.get());
  9552. if (!PostUpdateRes.isUsable())
  9553. continue;
  9554. ExprPostUpdates.push_back(
  9555. IgnoredValueConversions(PostUpdateRes.get()).get());
  9556. }
  9557. }
  9558. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  9559. Vars.push_back((VD || CurContext->isDependentContext())
  9560. ? RefExpr->IgnoreParens()
  9561. : Ref);
  9562. SrcExprs.push_back(PseudoSrcExpr);
  9563. DstExprs.push_back(PseudoDstExpr);
  9564. AssignmentOps.push_back(AssignmentOp.get());
  9565. }
  9566. if (Vars.empty())
  9567. return nullptr;
  9568. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9569. Vars, SrcExprs, DstExprs, AssignmentOps,
  9570. buildPreInits(Context, ExprCaptures),
  9571. buildPostUpdate(*this, ExprPostUpdates));
  9572. }
  9573. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  9574. SourceLocation StartLoc,
  9575. SourceLocation LParenLoc,
  9576. SourceLocation EndLoc) {
  9577. SmallVector<Expr *, 8> Vars;
  9578. for (Expr *RefExpr : VarList) {
  9579. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9580. SourceLocation ELoc;
  9581. SourceRange ERange;
  9582. Expr *SimpleRefExpr = RefExpr;
  9583. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9584. if (Res.second) {
  9585. // It will be analyzed later.
  9586. Vars.push_back(RefExpr);
  9587. }
  9588. ValueDecl *D = Res.first;
  9589. if (!D)
  9590. continue;
  9591. auto *VD = dyn_cast<VarDecl>(D);
  9592. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9593. // in a Construct]
  9594. // Variables with the predetermined data-sharing attributes may not be
  9595. // listed in data-sharing attributes clauses, except for the cases
  9596. // listed below. For these exceptions only, listing a predetermined
  9597. // variable in a data-sharing attribute clause is allowed and overrides
  9598. // the variable's predetermined data-sharing attributes.
  9599. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9600. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  9601. DVar.RefExpr) {
  9602. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9603. << getOpenMPClauseName(OMPC_shared);
  9604. reportOriginalDsa(*this, DSAStack, D, DVar);
  9605. continue;
  9606. }
  9607. DeclRefExpr *Ref = nullptr;
  9608. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  9609. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9610. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  9611. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  9612. ? RefExpr->IgnoreParens()
  9613. : Ref);
  9614. }
  9615. if (Vars.empty())
  9616. return nullptr;
  9617. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  9618. }
  9619. namespace {
  9620. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  9621. DSAStackTy *Stack;
  9622. public:
  9623. bool VisitDeclRefExpr(DeclRefExpr *E) {
  9624. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9625. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  9626. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9627. return false;
  9628. if (DVar.CKind != OMPC_unknown)
  9629. return true;
  9630. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9631. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  9632. /*FromParent=*/true);
  9633. return DVarPrivate.CKind != OMPC_unknown;
  9634. }
  9635. return false;
  9636. }
  9637. bool VisitStmt(Stmt *S) {
  9638. for (Stmt *Child : S->children()) {
  9639. if (Child && Visit(Child))
  9640. return true;
  9641. }
  9642. return false;
  9643. }
  9644. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9645. };
  9646. } // namespace
  9647. namespace {
  9648. // Transform MemberExpression for specified FieldDecl of current class to
  9649. // DeclRefExpr to specified OMPCapturedExprDecl.
  9650. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9651. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9652. ValueDecl *Field = nullptr;
  9653. DeclRefExpr *CapturedExpr = nullptr;
  9654. public:
  9655. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9656. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9657. ExprResult TransformMemberExpr(MemberExpr *E) {
  9658. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9659. E->getMemberDecl() == Field) {
  9660. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9661. return CapturedExpr;
  9662. }
  9663. return BaseTransform::TransformMemberExpr(E);
  9664. }
  9665. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9666. };
  9667. } // namespace
  9668. template <typename T, typename U>
  9669. static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
  9670. const llvm::function_ref<T(ValueDecl *)> Gen) {
  9671. for (U &Set : Lookups) {
  9672. for (auto *D : Set) {
  9673. if (T Res = Gen(cast<ValueDecl>(D)))
  9674. return Res;
  9675. }
  9676. }
  9677. return T();
  9678. }
  9679. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  9680. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  9681. for (auto RD : D->redecls()) {
  9682. // Don't bother with extra checks if we already know this one isn't visible.
  9683. if (RD == D)
  9684. continue;
  9685. auto ND = cast<NamedDecl>(RD);
  9686. if (LookupResult::isVisible(SemaRef, ND))
  9687. return ND;
  9688. }
  9689. return nullptr;
  9690. }
  9691. static void
  9692. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
  9693. SourceLocation Loc, QualType Ty,
  9694. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  9695. // Find all of the associated namespaces and classes based on the
  9696. // arguments we have.
  9697. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9698. Sema::AssociatedClassSet AssociatedClasses;
  9699. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  9700. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  9701. AssociatedClasses);
  9702. // C++ [basic.lookup.argdep]p3:
  9703. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9704. // and let Y be the lookup set produced by argument dependent
  9705. // lookup (defined as follows). If X contains [...] then Y is
  9706. // empty. Otherwise Y is the set of declarations found in the
  9707. // namespaces associated with the argument types as described
  9708. // below. The set of declarations found by the lookup of the name
  9709. // is the union of X and Y.
  9710. //
  9711. // Here, we compute Y and add its members to the overloaded
  9712. // candidate set.
  9713. for (auto *NS : AssociatedNamespaces) {
  9714. // When considering an associated namespace, the lookup is the
  9715. // same as the lookup performed when the associated namespace is
  9716. // used as a qualifier (3.4.3.2) except that:
  9717. //
  9718. // -- Any using-directives in the associated namespace are
  9719. // ignored.
  9720. //
  9721. // -- Any namespace-scope friend functions declared in
  9722. // associated classes are visible within their respective
  9723. // namespaces even if they are not visible during an ordinary
  9724. // lookup (11.4).
  9725. DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
  9726. for (auto *D : R) {
  9727. auto *Underlying = D;
  9728. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  9729. Underlying = USD->getTargetDecl();
  9730. if (!isa<OMPDeclareReductionDecl>(Underlying))
  9731. continue;
  9732. if (!SemaRef.isVisible(D)) {
  9733. D = findAcceptableDecl(SemaRef, D);
  9734. if (!D)
  9735. continue;
  9736. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  9737. Underlying = USD->getTargetDecl();
  9738. }
  9739. Lookups.emplace_back();
  9740. Lookups.back().addDecl(Underlying);
  9741. }
  9742. }
  9743. }
  9744. static ExprResult
  9745. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9746. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9747. const DeclarationNameInfo &ReductionId, QualType Ty,
  9748. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9749. if (ReductionIdScopeSpec.isInvalid())
  9750. return ExprError();
  9751. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9752. if (S) {
  9753. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9754. Lookup.suppressDiagnostics();
  9755. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9756. NamedDecl *D = Lookup.getRepresentativeDecl();
  9757. do {
  9758. S = S->getParent();
  9759. } while (S && !S->isDeclScope(D));
  9760. if (S)
  9761. S = S->getParent();
  9762. Lookups.emplace_back();
  9763. Lookups.back().append(Lookup.begin(), Lookup.end());
  9764. Lookup.clear();
  9765. }
  9766. } else if (auto *ULE =
  9767. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9768. Lookups.push_back(UnresolvedSet<8>());
  9769. Decl *PrevD = nullptr;
  9770. for (NamedDecl *D : ULE->decls()) {
  9771. if (D == PrevD)
  9772. Lookups.push_back(UnresolvedSet<8>());
  9773. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9774. Lookups.back().addDecl(DRD);
  9775. PrevD = D;
  9776. }
  9777. }
  9778. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9779. Ty->isInstantiationDependentType() ||
  9780. Ty->containsUnexpandedParameterPack() ||
  9781. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
  9782. return !D->isInvalidDecl() &&
  9783. (D->getType()->isDependentType() ||
  9784. D->getType()->isInstantiationDependentType() ||
  9785. D->getType()->containsUnexpandedParameterPack());
  9786. })) {
  9787. UnresolvedSet<8> ResSet;
  9788. for (const UnresolvedSet<8> &Set : Lookups) {
  9789. if (Set.empty())
  9790. continue;
  9791. ResSet.append(Set.begin(), Set.end());
  9792. // The last item marks the end of all declarations at the specified scope.
  9793. ResSet.addDecl(Set[Set.size() - 1]);
  9794. }
  9795. return UnresolvedLookupExpr::Create(
  9796. SemaRef.Context, /*NamingClass=*/nullptr,
  9797. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9798. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9799. }
  9800. // Lookup inside the classes.
  9801. // C++ [over.match.oper]p3:
  9802. // For a unary operator @ with an operand of a type whose
  9803. // cv-unqualified version is T1, and for a binary operator @ with
  9804. // a left operand of a type whose cv-unqualified version is T1 and
  9805. // a right operand of a type whose cv-unqualified version is T2,
  9806. // three sets of candidate functions, designated member
  9807. // candidates, non-member candidates and built-in candidates, are
  9808. // constructed as follows:
  9809. // -- If T1 is a complete class type or a class currently being
  9810. // defined, the set of member candidates is the result of the
  9811. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  9812. // the set of member candidates is empty.
  9813. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9814. Lookup.suppressDiagnostics();
  9815. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  9816. // Complete the type if it can be completed.
  9817. // If the type is neither complete nor being defined, bail out now.
  9818. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  9819. TyRec->getDecl()->getDefinition()) {
  9820. Lookup.clear();
  9821. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  9822. if (Lookup.empty()) {
  9823. Lookups.emplace_back();
  9824. Lookups.back().append(Lookup.begin(), Lookup.end());
  9825. }
  9826. }
  9827. }
  9828. // Perform ADL.
  9829. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  9830. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9831. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9832. if (!D->isInvalidDecl() &&
  9833. SemaRef.Context.hasSameType(D->getType(), Ty))
  9834. return D;
  9835. return nullptr;
  9836. }))
  9837. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9838. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9839. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9840. if (!D->isInvalidDecl() &&
  9841. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9842. !Ty.isMoreQualifiedThan(D->getType()))
  9843. return D;
  9844. return nullptr;
  9845. })) {
  9846. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9847. /*DetectVirtual=*/false);
  9848. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9849. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9850. VD->getType().getUnqualifiedType()))) {
  9851. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9852. /*DiagID=*/0) !=
  9853. Sema::AR_inaccessible) {
  9854. SemaRef.BuildBasePathArray(Paths, BasePath);
  9855. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9856. }
  9857. }
  9858. }
  9859. }
  9860. if (ReductionIdScopeSpec.isSet()) {
  9861. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9862. return ExprError();
  9863. }
  9864. return ExprEmpty();
  9865. }
  9866. namespace {
  9867. /// Data for the reduction-based clauses.
  9868. struct ReductionData {
  9869. /// List of original reduction items.
  9870. SmallVector<Expr *, 8> Vars;
  9871. /// List of private copies of the reduction items.
  9872. SmallVector<Expr *, 8> Privates;
  9873. /// LHS expressions for the reduction_op expressions.
  9874. SmallVector<Expr *, 8> LHSs;
  9875. /// RHS expressions for the reduction_op expressions.
  9876. SmallVector<Expr *, 8> RHSs;
  9877. /// Reduction operation expression.
  9878. SmallVector<Expr *, 8> ReductionOps;
  9879. /// Taskgroup descriptors for the corresponding reduction items in
  9880. /// in_reduction clauses.
  9881. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9882. /// List of captures for clause.
  9883. SmallVector<Decl *, 4> ExprCaptures;
  9884. /// List of postupdate expressions.
  9885. SmallVector<Expr *, 4> ExprPostUpdates;
  9886. ReductionData() = delete;
  9887. /// Reserves required memory for the reduction data.
  9888. ReductionData(unsigned Size) {
  9889. Vars.reserve(Size);
  9890. Privates.reserve(Size);
  9891. LHSs.reserve(Size);
  9892. RHSs.reserve(Size);
  9893. ReductionOps.reserve(Size);
  9894. TaskgroupDescriptors.reserve(Size);
  9895. ExprCaptures.reserve(Size);
  9896. ExprPostUpdates.reserve(Size);
  9897. }
  9898. /// Stores reduction item and reduction operation only (required for dependent
  9899. /// reduction item).
  9900. void push(Expr *Item, Expr *ReductionOp) {
  9901. Vars.emplace_back(Item);
  9902. Privates.emplace_back(nullptr);
  9903. LHSs.emplace_back(nullptr);
  9904. RHSs.emplace_back(nullptr);
  9905. ReductionOps.emplace_back(ReductionOp);
  9906. TaskgroupDescriptors.emplace_back(nullptr);
  9907. }
  9908. /// Stores reduction data.
  9909. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9910. Expr *TaskgroupDescriptor) {
  9911. Vars.emplace_back(Item);
  9912. Privates.emplace_back(Private);
  9913. LHSs.emplace_back(LHS);
  9914. RHSs.emplace_back(RHS);
  9915. ReductionOps.emplace_back(ReductionOp);
  9916. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9917. }
  9918. };
  9919. } // namespace
  9920. static bool checkOMPArraySectionConstantForReduction(
  9921. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9922. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9923. const Expr *Length = OASE->getLength();
  9924. if (Length == nullptr) {
  9925. // For array sections of the form [1:] or [:], we would need to analyze
  9926. // the lower bound...
  9927. if (OASE->getColonLoc().isValid())
  9928. return false;
  9929. // This is an array subscript which has implicit length 1!
  9930. SingleElement = true;
  9931. ArraySizes.push_back(llvm::APSInt::get(1));
  9932. } else {
  9933. llvm::APSInt ConstantLengthValue;
  9934. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9935. return false;
  9936. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9937. ArraySizes.push_back(ConstantLengthValue);
  9938. }
  9939. // Get the base of this array section and walk up from there.
  9940. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9941. // We require length = 1 for all array sections except the right-most to
  9942. // guarantee that the memory region is contiguous and has no holes in it.
  9943. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  9944. Length = TempOASE->getLength();
  9945. if (Length == nullptr) {
  9946. // For array sections of the form [1:] or [:], we would need to analyze
  9947. // the lower bound...
  9948. if (OASE->getColonLoc().isValid())
  9949. return false;
  9950. // This is an array subscript which has implicit length 1!
  9951. ArraySizes.push_back(llvm::APSInt::get(1));
  9952. } else {
  9953. llvm::APSInt ConstantLengthValue;
  9954. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  9955. ConstantLengthValue.getSExtValue() != 1)
  9956. return false;
  9957. ArraySizes.push_back(ConstantLengthValue);
  9958. }
  9959. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9960. }
  9961. // If we have a single element, we don't need to add the implicit lengths.
  9962. if (!SingleElement) {
  9963. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  9964. // Has implicit length 1!
  9965. ArraySizes.push_back(llvm::APSInt::get(1));
  9966. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9967. }
  9968. }
  9969. // This array section can be privatized as a single value or as a constant
  9970. // sized array.
  9971. return true;
  9972. }
  9973. static bool actOnOMPReductionKindClause(
  9974. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  9975. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9976. SourceLocation ColonLoc, SourceLocation EndLoc,
  9977. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9978. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  9979. DeclarationName DN = ReductionId.getName();
  9980. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  9981. BinaryOperatorKind BOK = BO_Comma;
  9982. ASTContext &Context = S.Context;
  9983. // OpenMP [2.14.3.6, reduction clause]
  9984. // C
  9985. // reduction-identifier is either an identifier or one of the following
  9986. // operators: +, -, *, &, |, ^, && and ||
  9987. // C++
  9988. // reduction-identifier is either an id-expression or one of the following
  9989. // operators: +, -, *, &, |, ^, && and ||
  9990. switch (OOK) {
  9991. case OO_Plus:
  9992. case OO_Minus:
  9993. BOK = BO_Add;
  9994. break;
  9995. case OO_Star:
  9996. BOK = BO_Mul;
  9997. break;
  9998. case OO_Amp:
  9999. BOK = BO_And;
  10000. break;
  10001. case OO_Pipe:
  10002. BOK = BO_Or;
  10003. break;
  10004. case OO_Caret:
  10005. BOK = BO_Xor;
  10006. break;
  10007. case OO_AmpAmp:
  10008. BOK = BO_LAnd;
  10009. break;
  10010. case OO_PipePipe:
  10011. BOK = BO_LOr;
  10012. break;
  10013. case OO_New:
  10014. case OO_Delete:
  10015. case OO_Array_New:
  10016. case OO_Array_Delete:
  10017. case OO_Slash:
  10018. case OO_Percent:
  10019. case OO_Tilde:
  10020. case OO_Exclaim:
  10021. case OO_Equal:
  10022. case OO_Less:
  10023. case OO_Greater:
  10024. case OO_LessEqual:
  10025. case OO_GreaterEqual:
  10026. case OO_PlusEqual:
  10027. case OO_MinusEqual:
  10028. case OO_StarEqual:
  10029. case OO_SlashEqual:
  10030. case OO_PercentEqual:
  10031. case OO_CaretEqual:
  10032. case OO_AmpEqual:
  10033. case OO_PipeEqual:
  10034. case OO_LessLess:
  10035. case OO_GreaterGreater:
  10036. case OO_LessLessEqual:
  10037. case OO_GreaterGreaterEqual:
  10038. case OO_EqualEqual:
  10039. case OO_ExclaimEqual:
  10040. case OO_Spaceship:
  10041. case OO_PlusPlus:
  10042. case OO_MinusMinus:
  10043. case OO_Comma:
  10044. case OO_ArrowStar:
  10045. case OO_Arrow:
  10046. case OO_Call:
  10047. case OO_Subscript:
  10048. case OO_Conditional:
  10049. case OO_Coawait:
  10050. case NUM_OVERLOADED_OPERATORS:
  10051. llvm_unreachable("Unexpected reduction identifier");
  10052. case OO_None:
  10053. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  10054. if (II->isStr("max"))
  10055. BOK = BO_GT;
  10056. else if (II->isStr("min"))
  10057. BOK = BO_LT;
  10058. }
  10059. break;
  10060. }
  10061. SourceRange ReductionIdRange;
  10062. if (ReductionIdScopeSpec.isValid())
  10063. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  10064. else
  10065. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  10066. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  10067. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  10068. bool FirstIter = true;
  10069. for (Expr *RefExpr : VarList) {
  10070. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  10071. // OpenMP [2.1, C/C++]
  10072. // A list item is a variable or array section, subject to the restrictions
  10073. // specified in Section 2.4 on page 42 and in each of the sections
  10074. // describing clauses and directives for which a list appears.
  10075. // OpenMP [2.14.3.3, Restrictions, p.1]
  10076. // A variable that is part of another variable (as an array or
  10077. // structure element) cannot appear in a private clause.
  10078. if (!FirstIter && IR != ER)
  10079. ++IR;
  10080. FirstIter = false;
  10081. SourceLocation ELoc;
  10082. SourceRange ERange;
  10083. Expr *SimpleRefExpr = RefExpr;
  10084. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  10085. /*AllowArraySection=*/true);
  10086. if (Res.second) {
  10087. // Try to find 'declare reduction' corresponding construct before using
  10088. // builtin/overloaded operators.
  10089. QualType Type = Context.DependentTy;
  10090. CXXCastPath BasePath;
  10091. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10092. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10093. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10094. Expr *ReductionOp = nullptr;
  10095. if (S.CurContext->isDependentContext() &&
  10096. (DeclareReductionRef.isUnset() ||
  10097. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  10098. ReductionOp = DeclareReductionRef.get();
  10099. // It will be analyzed later.
  10100. RD.push(RefExpr, ReductionOp);
  10101. }
  10102. ValueDecl *D = Res.first;
  10103. if (!D)
  10104. continue;
  10105. Expr *TaskgroupDescriptor = nullptr;
  10106. QualType Type;
  10107. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  10108. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  10109. if (ASE) {
  10110. Type = ASE->getType().getNonReferenceType();
  10111. } else if (OASE) {
  10112. QualType BaseType =
  10113. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  10114. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  10115. Type = ATy->getElementType();
  10116. else
  10117. Type = BaseType->getPointeeType();
  10118. Type = Type.getNonReferenceType();
  10119. } else {
  10120. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  10121. }
  10122. auto *VD = dyn_cast<VarDecl>(D);
  10123. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10124. // A variable that appears in a private clause must not have an incomplete
  10125. // type or a reference type.
  10126. if (S.RequireCompleteType(ELoc, D->getType(),
  10127. diag::err_omp_reduction_incomplete_type))
  10128. continue;
  10129. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10130. // A list item that appears in a reduction clause must not be
  10131. // const-qualified.
  10132. if (Type.getNonReferenceType().isConstant(Context)) {
  10133. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  10134. if (!ASE && !OASE) {
  10135. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10136. VarDecl::DeclarationOnly;
  10137. S.Diag(D->getLocation(),
  10138. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10139. << D;
  10140. }
  10141. continue;
  10142. }
  10143. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  10144. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  10145. // If a list-item is a reference type then it must bind to the same object
  10146. // for all threads of the team.
  10147. if (!ASE && !OASE) {
  10148. if (VD) {
  10149. VarDecl *VDDef = VD->getDefinition();
  10150. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  10151. DSARefChecker Check(Stack);
  10152. if (Check.Visit(VDDef->getInit())) {
  10153. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  10154. << getOpenMPClauseName(ClauseKind) << ERange;
  10155. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  10156. continue;
  10157. }
  10158. }
  10159. }
  10160. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10161. // in a Construct]
  10162. // Variables with the predetermined data-sharing attributes may not be
  10163. // listed in data-sharing attributes clauses, except for the cases
  10164. // listed below. For these exceptions only, listing a predetermined
  10165. // variable in a data-sharing attribute clause is allowed and overrides
  10166. // the variable's predetermined data-sharing attributes.
  10167. // OpenMP [2.14.3.6, Restrictions, p.3]
  10168. // Any number of reduction clauses can be specified on the directive,
  10169. // but a list item can appear only once in the reduction clauses for that
  10170. // directive.
  10171. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  10172. if (DVar.CKind == OMPC_reduction) {
  10173. S.Diag(ELoc, diag::err_omp_once_referenced)
  10174. << getOpenMPClauseName(ClauseKind);
  10175. if (DVar.RefExpr)
  10176. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  10177. continue;
  10178. }
  10179. if (DVar.CKind != OMPC_unknown) {
  10180. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  10181. << getOpenMPClauseName(DVar.CKind)
  10182. << getOpenMPClauseName(OMPC_reduction);
  10183. reportOriginalDsa(S, Stack, D, DVar);
  10184. continue;
  10185. }
  10186. // OpenMP [2.14.3.6, Restrictions, p.1]
  10187. // A list item that appears in a reduction clause of a worksharing
  10188. // construct must be shared in the parallel regions to which any of the
  10189. // worksharing regions arising from the worksharing construct bind.
  10190. if (isOpenMPWorksharingDirective(CurrDir) &&
  10191. !isOpenMPParallelDirective(CurrDir) &&
  10192. !isOpenMPTeamsDirective(CurrDir)) {
  10193. DVar = Stack->getImplicitDSA(D, true);
  10194. if (DVar.CKind != OMPC_shared) {
  10195. S.Diag(ELoc, diag::err_omp_required_access)
  10196. << getOpenMPClauseName(OMPC_reduction)
  10197. << getOpenMPClauseName(OMPC_shared);
  10198. reportOriginalDsa(S, Stack, D, DVar);
  10199. continue;
  10200. }
  10201. }
  10202. }
  10203. // Try to find 'declare reduction' corresponding construct before using
  10204. // builtin/overloaded operators.
  10205. CXXCastPath BasePath;
  10206. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10207. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10208. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10209. if (DeclareReductionRef.isInvalid())
  10210. continue;
  10211. if (S.CurContext->isDependentContext() &&
  10212. (DeclareReductionRef.isUnset() ||
  10213. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  10214. RD.push(RefExpr, DeclareReductionRef.get());
  10215. continue;
  10216. }
  10217. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  10218. // Not allowed reduction identifier is found.
  10219. S.Diag(ReductionId.getBeginLoc(),
  10220. diag::err_omp_unknown_reduction_identifier)
  10221. << Type << ReductionIdRange;
  10222. continue;
  10223. }
  10224. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10225. // The type of a list item that appears in a reduction clause must be valid
  10226. // for the reduction-identifier. For a max or min reduction in C, the type
  10227. // of the list item must be an allowed arithmetic data type: char, int,
  10228. // float, double, or _Bool, possibly modified with long, short, signed, or
  10229. // unsigned. For a max or min reduction in C++, the type of the list item
  10230. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  10231. // double, or bool, possibly modified with long, short, signed, or unsigned.
  10232. if (DeclareReductionRef.isUnset()) {
  10233. if ((BOK == BO_GT || BOK == BO_LT) &&
  10234. !(Type->isScalarType() ||
  10235. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  10236. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  10237. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  10238. if (!ASE && !OASE) {
  10239. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10240. VarDecl::DeclarationOnly;
  10241. S.Diag(D->getLocation(),
  10242. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10243. << D;
  10244. }
  10245. continue;
  10246. }
  10247. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  10248. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  10249. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  10250. << getOpenMPClauseName(ClauseKind);
  10251. if (!ASE && !OASE) {
  10252. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10253. VarDecl::DeclarationOnly;
  10254. S.Diag(D->getLocation(),
  10255. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10256. << D;
  10257. }
  10258. continue;
  10259. }
  10260. }
  10261. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  10262. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  10263. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10264. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  10265. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10266. QualType PrivateTy = Type;
  10267. // Try if we can determine constant lengths for all array sections and avoid
  10268. // the VLA.
  10269. bool ConstantLengthOASE = false;
  10270. if (OASE) {
  10271. bool SingleElement;
  10272. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  10273. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  10274. Context, OASE, SingleElement, ArraySizes);
  10275. // If we don't have a single element, we must emit a constant array type.
  10276. if (ConstantLengthOASE && !SingleElement) {
  10277. for (llvm::APSInt &Size : ArraySizes)
  10278. PrivateTy = Context.getConstantArrayType(
  10279. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  10280. }
  10281. }
  10282. if ((OASE && !ConstantLengthOASE) ||
  10283. (!OASE && !ASE &&
  10284. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  10285. if (!Context.getTargetInfo().isVLASupported() &&
  10286. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  10287. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  10288. S.Diag(ELoc, diag::note_vla_unsupported);
  10289. continue;
  10290. }
  10291. // For arrays/array sections only:
  10292. // Create pseudo array type for private copy. The size for this array will
  10293. // be generated during codegen.
  10294. // For array subscripts or single variables Private Ty is the same as Type
  10295. // (type of the variable or single array element).
  10296. PrivateTy = Context.getVariableArrayType(
  10297. Type,
  10298. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  10299. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  10300. } else if (!ASE && !OASE &&
  10301. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  10302. PrivateTy = D->getType().getNonReferenceType();
  10303. }
  10304. // Private copy.
  10305. VarDecl *PrivateVD =
  10306. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  10307. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10308. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10309. // Add initializer for private variable.
  10310. Expr *Init = nullptr;
  10311. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  10312. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  10313. if (DeclareReductionRef.isUsable()) {
  10314. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  10315. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  10316. if (DRD->getInitializer()) {
  10317. Init = DRDRef;
  10318. RHSVD->setInit(DRDRef);
  10319. RHSVD->setInitStyle(VarDecl::CallInit);
  10320. }
  10321. } else {
  10322. switch (BOK) {
  10323. case BO_Add:
  10324. case BO_Xor:
  10325. case BO_Or:
  10326. case BO_LOr:
  10327. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  10328. if (Type->isScalarType() || Type->isAnyComplexType())
  10329. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  10330. break;
  10331. case BO_Mul:
  10332. case BO_LAnd:
  10333. if (Type->isScalarType() || Type->isAnyComplexType()) {
  10334. // '*' and '&&' reduction ops - initializer is '1'.
  10335. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  10336. }
  10337. break;
  10338. case BO_And: {
  10339. // '&' reduction op - initializer is '~0'.
  10340. QualType OrigType = Type;
  10341. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  10342. Type = ComplexTy->getElementType();
  10343. if (Type->isRealFloatingType()) {
  10344. llvm::APFloat InitValue =
  10345. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  10346. /*isIEEE=*/true);
  10347. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10348. Type, ELoc);
  10349. } else if (Type->isScalarType()) {
  10350. uint64_t Size = Context.getTypeSize(Type);
  10351. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  10352. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  10353. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10354. }
  10355. if (Init && OrigType->isAnyComplexType()) {
  10356. // Init = 0xFFFF + 0xFFFFi;
  10357. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  10358. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  10359. }
  10360. Type = OrigType;
  10361. break;
  10362. }
  10363. case BO_LT:
  10364. case BO_GT: {
  10365. // 'min' reduction op - initializer is 'Largest representable number in
  10366. // the reduction list item type'.
  10367. // 'max' reduction op - initializer is 'Least representable number in
  10368. // the reduction list item type'.
  10369. if (Type->isIntegerType() || Type->isPointerType()) {
  10370. bool IsSigned = Type->hasSignedIntegerRepresentation();
  10371. uint64_t Size = Context.getTypeSize(Type);
  10372. QualType IntTy =
  10373. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  10374. llvm::APInt InitValue =
  10375. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  10376. : llvm::APInt::getMinValue(Size)
  10377. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  10378. : llvm::APInt::getMaxValue(Size);
  10379. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10380. if (Type->isPointerType()) {
  10381. // Cast to pointer type.
  10382. ExprResult CastExpr = S.BuildCStyleCastExpr(
  10383. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  10384. if (CastExpr.isInvalid())
  10385. continue;
  10386. Init = CastExpr.get();
  10387. }
  10388. } else if (Type->isRealFloatingType()) {
  10389. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  10390. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  10391. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10392. Type, ELoc);
  10393. }
  10394. break;
  10395. }
  10396. case BO_PtrMemD:
  10397. case BO_PtrMemI:
  10398. case BO_MulAssign:
  10399. case BO_Div:
  10400. case BO_Rem:
  10401. case BO_Sub:
  10402. case BO_Shl:
  10403. case BO_Shr:
  10404. case BO_LE:
  10405. case BO_GE:
  10406. case BO_EQ:
  10407. case BO_NE:
  10408. case BO_Cmp:
  10409. case BO_AndAssign:
  10410. case BO_XorAssign:
  10411. case BO_OrAssign:
  10412. case BO_Assign:
  10413. case BO_AddAssign:
  10414. case BO_SubAssign:
  10415. case BO_DivAssign:
  10416. case BO_RemAssign:
  10417. case BO_ShlAssign:
  10418. case BO_ShrAssign:
  10419. case BO_Comma:
  10420. llvm_unreachable("Unexpected reduction operation");
  10421. }
  10422. }
  10423. if (Init && DeclareReductionRef.isUnset())
  10424. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  10425. else if (!Init)
  10426. S.ActOnUninitializedDecl(RHSVD);
  10427. if (RHSVD->isInvalidDecl())
  10428. continue;
  10429. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  10430. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  10431. << Type << ReductionIdRange;
  10432. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10433. VarDecl::DeclarationOnly;
  10434. S.Diag(D->getLocation(),
  10435. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10436. << D;
  10437. continue;
  10438. }
  10439. // Store initializer for single element in private copy. Will be used during
  10440. // codegen.
  10441. PrivateVD->setInit(RHSVD->getInit());
  10442. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  10443. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  10444. ExprResult ReductionOp;
  10445. if (DeclareReductionRef.isUsable()) {
  10446. QualType RedTy = DeclareReductionRef.get()->getType();
  10447. QualType PtrRedTy = Context.getPointerType(RedTy);
  10448. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  10449. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  10450. if (!BasePath.empty()) {
  10451. LHS = S.DefaultLvalueConversion(LHS.get());
  10452. RHS = S.DefaultLvalueConversion(RHS.get());
  10453. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10454. CK_UncheckedDerivedToBase, LHS.get(),
  10455. &BasePath, LHS.get()->getValueKind());
  10456. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10457. CK_UncheckedDerivedToBase, RHS.get(),
  10458. &BasePath, RHS.get()->getValueKind());
  10459. }
  10460. FunctionProtoType::ExtProtoInfo EPI;
  10461. QualType Params[] = {PtrRedTy, PtrRedTy};
  10462. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  10463. auto *OVE = new (Context) OpaqueValueExpr(
  10464. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  10465. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  10466. Expr *Args[] = {LHS.get(), RHS.get()};
  10467. ReductionOp = new (Context)
  10468. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  10469. } else {
  10470. ReductionOp = S.BuildBinOp(
  10471. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  10472. if (ReductionOp.isUsable()) {
  10473. if (BOK != BO_LT && BOK != BO_GT) {
  10474. ReductionOp =
  10475. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10476. BO_Assign, LHSDRE, ReductionOp.get());
  10477. } else {
  10478. auto *ConditionalOp = new (Context)
  10479. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  10480. Type, VK_LValue, OK_Ordinary);
  10481. ReductionOp =
  10482. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10483. BO_Assign, LHSDRE, ConditionalOp);
  10484. }
  10485. if (ReductionOp.isUsable())
  10486. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  10487. }
  10488. if (!ReductionOp.isUsable())
  10489. continue;
  10490. }
  10491. // OpenMP [2.15.4.6, Restrictions, p.2]
  10492. // A list item that appears in an in_reduction clause of a task construct
  10493. // must appear in a task_reduction clause of a construct associated with a
  10494. // taskgroup region that includes the participating task in its taskgroup
  10495. // set. The construct associated with the innermost region that meets this
  10496. // condition must specify the same reduction-identifier as the in_reduction
  10497. // clause.
  10498. if (ClauseKind == OMPC_in_reduction) {
  10499. SourceRange ParentSR;
  10500. BinaryOperatorKind ParentBOK;
  10501. const Expr *ParentReductionOp;
  10502. Expr *ParentBOKTD, *ParentReductionOpTD;
  10503. DSAStackTy::DSAVarData ParentBOKDSA =
  10504. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  10505. ParentBOKTD);
  10506. DSAStackTy::DSAVarData ParentReductionOpDSA =
  10507. Stack->getTopMostTaskgroupReductionData(
  10508. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  10509. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  10510. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  10511. if (!IsParentBOK && !IsParentReductionOp) {
  10512. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  10513. continue;
  10514. }
  10515. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  10516. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  10517. IsParentReductionOp) {
  10518. bool EmitError = true;
  10519. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  10520. llvm::FoldingSetNodeID RedId, ParentRedId;
  10521. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  10522. DeclareReductionRef.get()->Profile(RedId, Context,
  10523. /*Canonical=*/true);
  10524. EmitError = RedId != ParentRedId;
  10525. }
  10526. if (EmitError) {
  10527. S.Diag(ReductionId.getBeginLoc(),
  10528. diag::err_omp_reduction_identifier_mismatch)
  10529. << ReductionIdRange << RefExpr->getSourceRange();
  10530. S.Diag(ParentSR.getBegin(),
  10531. diag::note_omp_previous_reduction_identifier)
  10532. << ParentSR
  10533. << (IsParentBOK ? ParentBOKDSA.RefExpr
  10534. : ParentReductionOpDSA.RefExpr)
  10535. ->getSourceRange();
  10536. continue;
  10537. }
  10538. }
  10539. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  10540. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  10541. }
  10542. DeclRefExpr *Ref = nullptr;
  10543. Expr *VarsExpr = RefExpr->IgnoreParens();
  10544. if (!VD && !S.CurContext->isDependentContext()) {
  10545. if (ASE || OASE) {
  10546. TransformExprToCaptures RebuildToCapture(S, D);
  10547. VarsExpr =
  10548. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  10549. Ref = RebuildToCapture.getCapturedExpr();
  10550. } else {
  10551. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  10552. }
  10553. if (!S.isOpenMPCapturedDecl(D)) {
  10554. RD.ExprCaptures.emplace_back(Ref->getDecl());
  10555. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10556. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  10557. if (!RefRes.isUsable())
  10558. continue;
  10559. ExprResult PostUpdateRes =
  10560. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10561. RefRes.get());
  10562. if (!PostUpdateRes.isUsable())
  10563. continue;
  10564. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  10565. Stack->getCurrentDirective() == OMPD_taskgroup) {
  10566. S.Diag(RefExpr->getExprLoc(),
  10567. diag::err_omp_reduction_non_addressable_expression)
  10568. << RefExpr->getSourceRange();
  10569. continue;
  10570. }
  10571. RD.ExprPostUpdates.emplace_back(
  10572. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  10573. }
  10574. }
  10575. }
  10576. // All reduction items are still marked as reduction (to do not increase
  10577. // code base size).
  10578. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  10579. if (CurrDir == OMPD_taskgroup) {
  10580. if (DeclareReductionRef.isUsable())
  10581. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  10582. DeclareReductionRef.get());
  10583. else
  10584. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  10585. }
  10586. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  10587. TaskgroupDescriptor);
  10588. }
  10589. return RD.Vars.empty();
  10590. }
  10591. OMPClause *Sema::ActOnOpenMPReductionClause(
  10592. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10593. SourceLocation ColonLoc, SourceLocation EndLoc,
  10594. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10595. ArrayRef<Expr *> UnresolvedReductions) {
  10596. ReductionData RD(VarList.size());
  10597. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  10598. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10599. ReductionIdScopeSpec, ReductionId,
  10600. UnresolvedReductions, RD))
  10601. return nullptr;
  10602. return OMPReductionClause::Create(
  10603. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10604. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10605. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10606. buildPreInits(Context, RD.ExprCaptures),
  10607. buildPostUpdate(*this, RD.ExprPostUpdates));
  10608. }
  10609. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  10610. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10611. SourceLocation ColonLoc, SourceLocation EndLoc,
  10612. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10613. ArrayRef<Expr *> UnresolvedReductions) {
  10614. ReductionData RD(VarList.size());
  10615. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  10616. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10617. ReductionIdScopeSpec, ReductionId,
  10618. UnresolvedReductions, RD))
  10619. return nullptr;
  10620. return OMPTaskReductionClause::Create(
  10621. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10622. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10623. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10624. buildPreInits(Context, RD.ExprCaptures),
  10625. buildPostUpdate(*this, RD.ExprPostUpdates));
  10626. }
  10627. OMPClause *Sema::ActOnOpenMPInReductionClause(
  10628. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10629. SourceLocation ColonLoc, SourceLocation EndLoc,
  10630. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10631. ArrayRef<Expr *> UnresolvedReductions) {
  10632. ReductionData RD(VarList.size());
  10633. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  10634. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10635. ReductionIdScopeSpec, ReductionId,
  10636. UnresolvedReductions, RD))
  10637. return nullptr;
  10638. return OMPInReductionClause::Create(
  10639. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10640. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10641. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  10642. buildPreInits(Context, RD.ExprCaptures),
  10643. buildPostUpdate(*this, RD.ExprPostUpdates));
  10644. }
  10645. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  10646. SourceLocation LinLoc) {
  10647. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  10648. LinKind == OMPC_LINEAR_unknown) {
  10649. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  10650. return true;
  10651. }
  10652. return false;
  10653. }
  10654. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  10655. OpenMPLinearClauseKind LinKind,
  10656. QualType Type) {
  10657. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  10658. // A variable must not have an incomplete type or a reference type.
  10659. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  10660. return true;
  10661. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  10662. !Type->isReferenceType()) {
  10663. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  10664. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  10665. return true;
  10666. }
  10667. Type = Type.getNonReferenceType();
  10668. // A list item must not be const-qualified.
  10669. if (Type.isConstant(Context)) {
  10670. Diag(ELoc, diag::err_omp_const_variable)
  10671. << getOpenMPClauseName(OMPC_linear);
  10672. if (D) {
  10673. bool IsDecl =
  10674. !VD ||
  10675. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10676. Diag(D->getLocation(),
  10677. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10678. << D;
  10679. }
  10680. return true;
  10681. }
  10682. // A list item must be of integral or pointer type.
  10683. Type = Type.getUnqualifiedType().getCanonicalType();
  10684. const auto *Ty = Type.getTypePtrOrNull();
  10685. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  10686. !Ty->isPointerType())) {
  10687. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  10688. if (D) {
  10689. bool IsDecl =
  10690. !VD ||
  10691. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10692. Diag(D->getLocation(),
  10693. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10694. << D;
  10695. }
  10696. return true;
  10697. }
  10698. return false;
  10699. }
  10700. OMPClause *Sema::ActOnOpenMPLinearClause(
  10701. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  10702. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  10703. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10704. SmallVector<Expr *, 8> Vars;
  10705. SmallVector<Expr *, 8> Privates;
  10706. SmallVector<Expr *, 8> Inits;
  10707. SmallVector<Decl *, 4> ExprCaptures;
  10708. SmallVector<Expr *, 4> ExprPostUpdates;
  10709. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  10710. LinKind = OMPC_LINEAR_val;
  10711. for (Expr *RefExpr : VarList) {
  10712. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10713. SourceLocation ELoc;
  10714. SourceRange ERange;
  10715. Expr *SimpleRefExpr = RefExpr;
  10716. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10717. if (Res.second) {
  10718. // It will be analyzed later.
  10719. Vars.push_back(RefExpr);
  10720. Privates.push_back(nullptr);
  10721. Inits.push_back(nullptr);
  10722. }
  10723. ValueDecl *D = Res.first;
  10724. if (!D)
  10725. continue;
  10726. QualType Type = D->getType();
  10727. auto *VD = dyn_cast<VarDecl>(D);
  10728. // OpenMP [2.14.3.7, linear clause]
  10729. // A list-item cannot appear in more than one linear clause.
  10730. // A list-item that appears in a linear clause cannot appear in any
  10731. // other data-sharing attribute clause.
  10732. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10733. if (DVar.RefExpr) {
  10734. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10735. << getOpenMPClauseName(OMPC_linear);
  10736. reportOriginalDsa(*this, DSAStack, D, DVar);
  10737. continue;
  10738. }
  10739. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  10740. continue;
  10741. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10742. // Build private copy of original var.
  10743. VarDecl *Private =
  10744. buildVarDecl(*this, ELoc, Type, D->getName(),
  10745. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10746. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10747. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10748. // Build var to save initial value.
  10749. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10750. Expr *InitExpr;
  10751. DeclRefExpr *Ref = nullptr;
  10752. if (!VD && !CurContext->isDependentContext()) {
  10753. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10754. if (!isOpenMPCapturedDecl(D)) {
  10755. ExprCaptures.push_back(Ref->getDecl());
  10756. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10757. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10758. if (!RefRes.isUsable())
  10759. continue;
  10760. ExprResult PostUpdateRes =
  10761. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10762. SimpleRefExpr, RefRes.get());
  10763. if (!PostUpdateRes.isUsable())
  10764. continue;
  10765. ExprPostUpdates.push_back(
  10766. IgnoredValueConversions(PostUpdateRes.get()).get());
  10767. }
  10768. }
  10769. }
  10770. if (LinKind == OMPC_LINEAR_uval)
  10771. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10772. else
  10773. InitExpr = VD ? SimpleRefExpr : Ref;
  10774. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10775. /*DirectInit=*/false);
  10776. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10777. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10778. Vars.push_back((VD || CurContext->isDependentContext())
  10779. ? RefExpr->IgnoreParens()
  10780. : Ref);
  10781. Privates.push_back(PrivateRef);
  10782. Inits.push_back(InitRef);
  10783. }
  10784. if (Vars.empty())
  10785. return nullptr;
  10786. Expr *StepExpr = Step;
  10787. Expr *CalcStepExpr = nullptr;
  10788. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10789. !Step->isInstantiationDependent() &&
  10790. !Step->containsUnexpandedParameterPack()) {
  10791. SourceLocation StepLoc = Step->getBeginLoc();
  10792. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10793. if (Val.isInvalid())
  10794. return nullptr;
  10795. StepExpr = Val.get();
  10796. // Build var to save the step value.
  10797. VarDecl *SaveVar =
  10798. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10799. ExprResult SaveRef =
  10800. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10801. ExprResult CalcStep =
  10802. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10803. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10804. // Warn about zero linear step (it would be probably better specified as
  10805. // making corresponding variables 'const').
  10806. llvm::APSInt Result;
  10807. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10808. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10809. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10810. << (Vars.size() > 1);
  10811. if (!IsConstant && CalcStep.isUsable()) {
  10812. // Calculate the step beforehand instead of doing this on each iteration.
  10813. // (This is not used if the number of iterations may be kfold-ed).
  10814. CalcStepExpr = CalcStep.get();
  10815. }
  10816. }
  10817. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10818. ColonLoc, EndLoc, Vars, Privates, Inits,
  10819. StepExpr, CalcStepExpr,
  10820. buildPreInits(Context, ExprCaptures),
  10821. buildPostUpdate(*this, ExprPostUpdates));
  10822. }
  10823. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10824. Expr *NumIterations, Sema &SemaRef,
  10825. Scope *S, DSAStackTy *Stack) {
  10826. // Walk the vars and build update/final expressions for the CodeGen.
  10827. SmallVector<Expr *, 8> Updates;
  10828. SmallVector<Expr *, 8> Finals;
  10829. Expr *Step = Clause.getStep();
  10830. Expr *CalcStep = Clause.getCalcStep();
  10831. // OpenMP [2.14.3.7, linear clause]
  10832. // If linear-step is not specified it is assumed to be 1.
  10833. if (!Step)
  10834. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10835. else if (CalcStep)
  10836. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10837. bool HasErrors = false;
  10838. auto CurInit = Clause.inits().begin();
  10839. auto CurPrivate = Clause.privates().begin();
  10840. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  10841. for (Expr *RefExpr : Clause.varlists()) {
  10842. SourceLocation ELoc;
  10843. SourceRange ERange;
  10844. Expr *SimpleRefExpr = RefExpr;
  10845. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  10846. ValueDecl *D = Res.first;
  10847. if (Res.second || !D) {
  10848. Updates.push_back(nullptr);
  10849. Finals.push_back(nullptr);
  10850. HasErrors = true;
  10851. continue;
  10852. }
  10853. auto &&Info = Stack->isLoopControlVariable(D);
  10854. // OpenMP [2.15.11, distribute simd Construct]
  10855. // A list item may not appear in a linear clause, unless it is the loop
  10856. // iteration variable.
  10857. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10858. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10859. SemaRef.Diag(ELoc,
  10860. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10861. Updates.push_back(nullptr);
  10862. Finals.push_back(nullptr);
  10863. HasErrors = true;
  10864. continue;
  10865. }
  10866. Expr *InitExpr = *CurInit;
  10867. // Build privatized reference to the current linear var.
  10868. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10869. Expr *CapturedRef;
  10870. if (LinKind == OMPC_LINEAR_uval)
  10871. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10872. else
  10873. CapturedRef =
  10874. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10875. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10876. /*RefersToCapture=*/true);
  10877. // Build update: Var = InitExpr + IV * Step
  10878. ExprResult Update;
  10879. if (!Info.first)
  10880. Update =
  10881. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10882. InitExpr, IV, Step, /* Subtract */ false);
  10883. else
  10884. Update = *CurPrivate;
  10885. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  10886. /*DiscardedValue=*/true);
  10887. // Build final: Var = InitExpr + NumIterations * Step
  10888. ExprResult Final;
  10889. if (!Info.first)
  10890. Final =
  10891. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10892. InitExpr, NumIterations, Step, /*Subtract=*/false);
  10893. else
  10894. Final = *CurPrivate;
  10895. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  10896. /*DiscardedValue=*/true);
  10897. if (!Update.isUsable() || !Final.isUsable()) {
  10898. Updates.push_back(nullptr);
  10899. Finals.push_back(nullptr);
  10900. HasErrors = true;
  10901. } else {
  10902. Updates.push_back(Update.get());
  10903. Finals.push_back(Final.get());
  10904. }
  10905. ++CurInit;
  10906. ++CurPrivate;
  10907. }
  10908. Clause.setUpdates(Updates);
  10909. Clause.setFinals(Finals);
  10910. return HasErrors;
  10911. }
  10912. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10913. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10914. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10915. SmallVector<Expr *, 8> Vars;
  10916. for (Expr *RefExpr : VarList) {
  10917. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10918. SourceLocation ELoc;
  10919. SourceRange ERange;
  10920. Expr *SimpleRefExpr = RefExpr;
  10921. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10922. if (Res.second) {
  10923. // It will be analyzed later.
  10924. Vars.push_back(RefExpr);
  10925. }
  10926. ValueDecl *D = Res.first;
  10927. if (!D)
  10928. continue;
  10929. QualType QType = D->getType();
  10930. auto *VD = dyn_cast<VarDecl>(D);
  10931. // OpenMP [2.8.1, simd construct, Restrictions]
  10932. // The type of list items appearing in the aligned clause must be
  10933. // array, pointer, reference to array, or reference to pointer.
  10934. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10935. const Type *Ty = QType.getTypePtrOrNull();
  10936. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10937. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10938. << QType << getLangOpts().CPlusPlus << ERange;
  10939. bool IsDecl =
  10940. !VD ||
  10941. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10942. Diag(D->getLocation(),
  10943. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10944. << D;
  10945. continue;
  10946. }
  10947. // OpenMP [2.8.1, simd construct, Restrictions]
  10948. // A list-item cannot appear in more than one aligned clause.
  10949. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  10950. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  10951. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  10952. << getOpenMPClauseName(OMPC_aligned);
  10953. continue;
  10954. }
  10955. DeclRefExpr *Ref = nullptr;
  10956. if (!VD && isOpenMPCapturedDecl(D))
  10957. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10958. Vars.push_back(DefaultFunctionArrayConversion(
  10959. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  10960. .get());
  10961. }
  10962. // OpenMP [2.8.1, simd construct, Description]
  10963. // The parameter of the aligned clause, alignment, must be a constant
  10964. // positive integer expression.
  10965. // If no optional parameter is specified, implementation-defined default
  10966. // alignments for SIMD instructions on the target platforms are assumed.
  10967. if (Alignment != nullptr) {
  10968. ExprResult AlignResult =
  10969. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  10970. if (AlignResult.isInvalid())
  10971. return nullptr;
  10972. Alignment = AlignResult.get();
  10973. }
  10974. if (Vars.empty())
  10975. return nullptr;
  10976. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  10977. EndLoc, Vars, Alignment);
  10978. }
  10979. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  10980. SourceLocation StartLoc,
  10981. SourceLocation LParenLoc,
  10982. SourceLocation EndLoc) {
  10983. SmallVector<Expr *, 8> Vars;
  10984. SmallVector<Expr *, 8> SrcExprs;
  10985. SmallVector<Expr *, 8> DstExprs;
  10986. SmallVector<Expr *, 8> AssignmentOps;
  10987. for (Expr *RefExpr : VarList) {
  10988. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  10989. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10990. // It will be analyzed later.
  10991. Vars.push_back(RefExpr);
  10992. SrcExprs.push_back(nullptr);
  10993. DstExprs.push_back(nullptr);
  10994. AssignmentOps.push_back(nullptr);
  10995. continue;
  10996. }
  10997. SourceLocation ELoc = RefExpr->getExprLoc();
  10998. // OpenMP [2.1, C/C++]
  10999. // A list item is a variable name.
  11000. // OpenMP [2.14.4.1, Restrictions, p.1]
  11001. // A list item that appears in a copyin clause must be threadprivate.
  11002. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  11003. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  11004. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  11005. << 0 << RefExpr->getSourceRange();
  11006. continue;
  11007. }
  11008. Decl *D = DE->getDecl();
  11009. auto *VD = cast<VarDecl>(D);
  11010. QualType Type = VD->getType();
  11011. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  11012. // It will be analyzed later.
  11013. Vars.push_back(DE);
  11014. SrcExprs.push_back(nullptr);
  11015. DstExprs.push_back(nullptr);
  11016. AssignmentOps.push_back(nullptr);
  11017. continue;
  11018. }
  11019. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  11020. // A list item that appears in a copyin clause must be threadprivate.
  11021. if (!DSAStack->isThreadPrivate(VD)) {
  11022. Diag(ELoc, diag::err_omp_required_access)
  11023. << getOpenMPClauseName(OMPC_copyin)
  11024. << getOpenMPDirectiveName(OMPD_threadprivate);
  11025. continue;
  11026. }
  11027. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11028. // A variable of class type (or array thereof) that appears in a
  11029. // copyin clause requires an accessible, unambiguous copy assignment
  11030. // operator for the class type.
  11031. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11032. VarDecl *SrcVD =
  11033. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  11034. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11035. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  11036. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  11037. VarDecl *DstVD =
  11038. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  11039. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11040. DeclRefExpr *PseudoDstExpr =
  11041. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  11042. // For arrays generate assignment operation for single element and replace
  11043. // it by the original array element in CodeGen.
  11044. ExprResult AssignmentOp =
  11045. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  11046. PseudoSrcExpr);
  11047. if (AssignmentOp.isInvalid())
  11048. continue;
  11049. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  11050. /*DiscardedValue=*/true);
  11051. if (AssignmentOp.isInvalid())
  11052. continue;
  11053. DSAStack->addDSA(VD, DE, OMPC_copyin);
  11054. Vars.push_back(DE);
  11055. SrcExprs.push_back(PseudoSrcExpr);
  11056. DstExprs.push_back(PseudoDstExpr);
  11057. AssignmentOps.push_back(AssignmentOp.get());
  11058. }
  11059. if (Vars.empty())
  11060. return nullptr;
  11061. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11062. SrcExprs, DstExprs, AssignmentOps);
  11063. }
  11064. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  11065. SourceLocation StartLoc,
  11066. SourceLocation LParenLoc,
  11067. SourceLocation EndLoc) {
  11068. SmallVector<Expr *, 8> Vars;
  11069. SmallVector<Expr *, 8> SrcExprs;
  11070. SmallVector<Expr *, 8> DstExprs;
  11071. SmallVector<Expr *, 8> AssignmentOps;
  11072. for (Expr *RefExpr : VarList) {
  11073. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11074. SourceLocation ELoc;
  11075. SourceRange ERange;
  11076. Expr *SimpleRefExpr = RefExpr;
  11077. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11078. if (Res.second) {
  11079. // It will be analyzed later.
  11080. Vars.push_back(RefExpr);
  11081. SrcExprs.push_back(nullptr);
  11082. DstExprs.push_back(nullptr);
  11083. AssignmentOps.push_back(nullptr);
  11084. }
  11085. ValueDecl *D = Res.first;
  11086. if (!D)
  11087. continue;
  11088. QualType Type = D->getType();
  11089. auto *VD = dyn_cast<VarDecl>(D);
  11090. // OpenMP [2.14.4.2, Restrictions, p.2]
  11091. // A list item that appears in a copyprivate clause may not appear in a
  11092. // private or firstprivate clause on the single construct.
  11093. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  11094. DSAStackTy::DSAVarData DVar =
  11095. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11096. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  11097. DVar.RefExpr) {
  11098. Diag(ELoc, diag::err_omp_wrong_dsa)
  11099. << getOpenMPClauseName(DVar.CKind)
  11100. << getOpenMPClauseName(OMPC_copyprivate);
  11101. reportOriginalDsa(*this, DSAStack, D, DVar);
  11102. continue;
  11103. }
  11104. // OpenMP [2.11.4.2, Restrictions, p.1]
  11105. // All list items that appear in a copyprivate clause must be either
  11106. // threadprivate or private in the enclosing context.
  11107. if (DVar.CKind == OMPC_unknown) {
  11108. DVar = DSAStack->getImplicitDSA(D, false);
  11109. if (DVar.CKind == OMPC_shared) {
  11110. Diag(ELoc, diag::err_omp_required_access)
  11111. << getOpenMPClauseName(OMPC_copyprivate)
  11112. << "threadprivate or private in the enclosing context";
  11113. reportOriginalDsa(*this, DSAStack, D, DVar);
  11114. continue;
  11115. }
  11116. }
  11117. }
  11118. // Variably modified types are not supported.
  11119. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  11120. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11121. << getOpenMPClauseName(OMPC_copyprivate) << Type
  11122. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11123. bool IsDecl =
  11124. !VD ||
  11125. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11126. Diag(D->getLocation(),
  11127. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11128. << D;
  11129. continue;
  11130. }
  11131. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11132. // A variable of class type (or array thereof) that appears in a
  11133. // copyin clause requires an accessible, unambiguous copy assignment
  11134. // operator for the class type.
  11135. Type = Context.getBaseElementType(Type.getNonReferenceType())
  11136. .getUnqualifiedType();
  11137. VarDecl *SrcVD =
  11138. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  11139. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11140. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  11141. VarDecl *DstVD =
  11142. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  11143. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11144. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11145. ExprResult AssignmentOp = BuildBinOp(
  11146. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  11147. if (AssignmentOp.isInvalid())
  11148. continue;
  11149. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  11150. /*DiscardedValue=*/true);
  11151. if (AssignmentOp.isInvalid())
  11152. continue;
  11153. // No need to mark vars as copyprivate, they are already threadprivate or
  11154. // implicitly private.
  11155. assert(VD || isOpenMPCapturedDecl(D));
  11156. Vars.push_back(
  11157. VD ? RefExpr->IgnoreParens()
  11158. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  11159. SrcExprs.push_back(PseudoSrcExpr);
  11160. DstExprs.push_back(PseudoDstExpr);
  11161. AssignmentOps.push_back(AssignmentOp.get());
  11162. }
  11163. if (Vars.empty())
  11164. return nullptr;
  11165. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11166. Vars, SrcExprs, DstExprs, AssignmentOps);
  11167. }
  11168. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  11169. SourceLocation StartLoc,
  11170. SourceLocation LParenLoc,
  11171. SourceLocation EndLoc) {
  11172. if (VarList.empty())
  11173. return nullptr;
  11174. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  11175. }
  11176. OMPClause *
  11177. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  11178. SourceLocation DepLoc, SourceLocation ColonLoc,
  11179. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11180. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11181. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  11182. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  11183. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11184. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  11185. return nullptr;
  11186. }
  11187. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  11188. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  11189. DepKind == OMPC_DEPEND_sink)) {
  11190. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  11191. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11192. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  11193. /*Last=*/OMPC_DEPEND_unknown, Except)
  11194. << getOpenMPClauseName(OMPC_depend);
  11195. return nullptr;
  11196. }
  11197. SmallVector<Expr *, 8> Vars;
  11198. DSAStackTy::OperatorOffsetTy OpsOffs;
  11199. llvm::APSInt DepCounter(/*BitWidth=*/32);
  11200. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  11201. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  11202. if (const Expr *OrderedCountExpr =
  11203. DSAStack->getParentOrderedRegionParam().first) {
  11204. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  11205. TotalDepCount.setIsUnsigned(/*Val=*/true);
  11206. }
  11207. }
  11208. for (Expr *RefExpr : VarList) {
  11209. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  11210. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11211. // It will be analyzed later.
  11212. Vars.push_back(RefExpr);
  11213. continue;
  11214. }
  11215. SourceLocation ELoc = RefExpr->getExprLoc();
  11216. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  11217. if (DepKind == OMPC_DEPEND_sink) {
  11218. if (DSAStack->getParentOrderedRegionParam().first &&
  11219. DepCounter >= TotalDepCount) {
  11220. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  11221. continue;
  11222. }
  11223. ++DepCounter;
  11224. // OpenMP [2.13.9, Summary]
  11225. // depend(dependence-type : vec), where dependence-type is:
  11226. // 'sink' and where vec is the iteration vector, which has the form:
  11227. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  11228. // where n is the value specified by the ordered clause in the loop
  11229. // directive, xi denotes the loop iteration variable of the i-th nested
  11230. // loop associated with the loop directive, and di is a constant
  11231. // non-negative integer.
  11232. if (CurContext->isDependentContext()) {
  11233. // It will be analyzed later.
  11234. Vars.push_back(RefExpr);
  11235. continue;
  11236. }
  11237. SimpleExpr = SimpleExpr->IgnoreImplicit();
  11238. OverloadedOperatorKind OOK = OO_None;
  11239. SourceLocation OOLoc;
  11240. Expr *LHS = SimpleExpr;
  11241. Expr *RHS = nullptr;
  11242. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  11243. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  11244. OOLoc = BO->getOperatorLoc();
  11245. LHS = BO->getLHS()->IgnoreParenImpCasts();
  11246. RHS = BO->getRHS()->IgnoreParenImpCasts();
  11247. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  11248. OOK = OCE->getOperator();
  11249. OOLoc = OCE->getOperatorLoc();
  11250. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11251. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  11252. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  11253. OOK = MCE->getMethodDecl()
  11254. ->getNameInfo()
  11255. .getName()
  11256. .getCXXOverloadedOperator();
  11257. OOLoc = MCE->getCallee()->getExprLoc();
  11258. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  11259. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11260. }
  11261. SourceLocation ELoc;
  11262. SourceRange ERange;
  11263. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  11264. if (Res.second) {
  11265. // It will be analyzed later.
  11266. Vars.push_back(RefExpr);
  11267. }
  11268. ValueDecl *D = Res.first;
  11269. if (!D)
  11270. continue;
  11271. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  11272. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  11273. continue;
  11274. }
  11275. if (RHS) {
  11276. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  11277. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  11278. if (RHSRes.isInvalid())
  11279. continue;
  11280. }
  11281. if (!CurContext->isDependentContext() &&
  11282. DSAStack->getParentOrderedRegionParam().first &&
  11283. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  11284. const ValueDecl *VD =
  11285. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  11286. if (VD)
  11287. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11288. << 1 << VD;
  11289. else
  11290. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  11291. continue;
  11292. }
  11293. OpsOffs.emplace_back(RHS, OOK);
  11294. } else {
  11295. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  11296. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  11297. (ASE &&
  11298. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  11299. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  11300. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11301. << RefExpr->getSourceRange();
  11302. continue;
  11303. }
  11304. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  11305. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  11306. ExprResult Res =
  11307. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  11308. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  11309. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  11310. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11311. << RefExpr->getSourceRange();
  11312. continue;
  11313. }
  11314. }
  11315. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  11316. }
  11317. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  11318. TotalDepCount > VarList.size() &&
  11319. DSAStack->getParentOrderedRegionParam().first &&
  11320. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  11321. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11322. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  11323. }
  11324. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  11325. Vars.empty())
  11326. return nullptr;
  11327. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11328. DepKind, DepLoc, ColonLoc, Vars,
  11329. TotalDepCount.getZExtValue());
  11330. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  11331. DSAStack->isParentOrderedRegion())
  11332. DSAStack->addDoacrossDependClause(C, OpsOffs);
  11333. return C;
  11334. }
  11335. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  11336. SourceLocation LParenLoc,
  11337. SourceLocation EndLoc) {
  11338. Expr *ValExpr = Device;
  11339. Stmt *HelperValStmt = nullptr;
  11340. // OpenMP [2.9.1, Restrictions]
  11341. // The device expression must evaluate to a non-negative integer value.
  11342. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  11343. /*StrictlyPositive=*/false))
  11344. return nullptr;
  11345. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11346. OpenMPDirectiveKind CaptureRegion =
  11347. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  11348. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11349. ValExpr = MakeFullExpr(ValExpr).get();
  11350. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11351. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11352. HelperValStmt = buildPreInits(Context, Captures);
  11353. }
  11354. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  11355. StartLoc, LParenLoc, EndLoc);
  11356. }
  11357. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  11358. DSAStackTy *Stack, QualType QTy,
  11359. bool FullCheck = true) {
  11360. NamedDecl *ND;
  11361. if (QTy->isIncompleteType(&ND)) {
  11362. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  11363. return false;
  11364. }
  11365. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  11366. !QTy.isTrivialType(SemaRef.Context))
  11367. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  11368. return true;
  11369. }
  11370. /// Return true if it can be proven that the provided array expression
  11371. /// (array section or array subscript) does NOT specify the whole size of the
  11372. /// array whose base type is \a BaseQTy.
  11373. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  11374. const Expr *E,
  11375. QualType BaseQTy) {
  11376. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11377. // If this is an array subscript, it refers to the whole size if the size of
  11378. // the dimension is constant and equals 1. Also, an array section assumes the
  11379. // format of an array subscript if no colon is used.
  11380. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  11381. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11382. return ATy->getSize().getSExtValue() != 1;
  11383. // Size can't be evaluated statically.
  11384. return false;
  11385. }
  11386. assert(OASE && "Expecting array section if not an array subscript.");
  11387. const Expr *LowerBound = OASE->getLowerBound();
  11388. const Expr *Length = OASE->getLength();
  11389. // If there is a lower bound that does not evaluates to zero, we are not
  11390. // covering the whole dimension.
  11391. if (LowerBound) {
  11392. llvm::APSInt ConstLowerBound;
  11393. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  11394. return false; // Can't get the integer value as a constant.
  11395. if (ConstLowerBound.getSExtValue())
  11396. return true;
  11397. }
  11398. // If we don't have a length we covering the whole dimension.
  11399. if (!Length)
  11400. return false;
  11401. // If the base is a pointer, we don't have a way to get the size of the
  11402. // pointee.
  11403. if (BaseQTy->isPointerType())
  11404. return false;
  11405. // We can only check if the length is the same as the size of the dimension
  11406. // if we have a constant array.
  11407. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  11408. if (!CATy)
  11409. return false;
  11410. llvm::APSInt ConstLength;
  11411. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  11412. return false; // Can't get the integer value as a constant.
  11413. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  11414. }
  11415. // Return true if it can be proven that the provided array expression (array
  11416. // section or array subscript) does NOT specify a single element of the array
  11417. // whose base type is \a BaseQTy.
  11418. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  11419. const Expr *E,
  11420. QualType BaseQTy) {
  11421. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11422. // An array subscript always refer to a single element. Also, an array section
  11423. // assumes the format of an array subscript if no colon is used.
  11424. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  11425. return false;
  11426. assert(OASE && "Expecting array section if not an array subscript.");
  11427. const Expr *Length = OASE->getLength();
  11428. // If we don't have a length we have to check if the array has unitary size
  11429. // for this dimension. Also, we should always expect a length if the base type
  11430. // is pointer.
  11431. if (!Length) {
  11432. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11433. return ATy->getSize().getSExtValue() != 1;
  11434. // We cannot assume anything.
  11435. return false;
  11436. }
  11437. // Check if the length evaluates to 1.
  11438. llvm::APSInt ConstLength;
  11439. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  11440. return false; // Can't get the integer value as a constant.
  11441. return ConstLength.getSExtValue() != 1;
  11442. }
  11443. // Return the expression of the base of the mappable expression or null if it
  11444. // cannot be determined and do all the necessary checks to see if the expression
  11445. // is valid as a standalone mappable expression. In the process, record all the
  11446. // components of the expression.
  11447. static const Expr *checkMapClauseExpressionBase(
  11448. Sema &SemaRef, Expr *E,
  11449. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  11450. OpenMPClauseKind CKind, bool NoDiagnose) {
  11451. SourceLocation ELoc = E->getExprLoc();
  11452. SourceRange ERange = E->getSourceRange();
  11453. // The base of elements of list in a map clause have to be either:
  11454. // - a reference to variable or field.
  11455. // - a member expression.
  11456. // - an array expression.
  11457. //
  11458. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  11459. // reference to 'r'.
  11460. //
  11461. // If we have:
  11462. //
  11463. // struct SS {
  11464. // Bla S;
  11465. // foo() {
  11466. // #pragma omp target map (S.Arr[:12]);
  11467. // }
  11468. // }
  11469. //
  11470. // We want to retrieve the member expression 'this->S';
  11471. const Expr *RelevantExpr = nullptr;
  11472. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  11473. // If a list item is an array section, it must specify contiguous storage.
  11474. //
  11475. // For this restriction it is sufficient that we make sure only references
  11476. // to variables or fields and array expressions, and that no array sections
  11477. // exist except in the rightmost expression (unless they cover the whole
  11478. // dimension of the array). E.g. these would be invalid:
  11479. //
  11480. // r.ArrS[3:5].Arr[6:7]
  11481. //
  11482. // r.ArrS[3:5].x
  11483. //
  11484. // but these would be valid:
  11485. // r.ArrS[3].Arr[6:7]
  11486. //
  11487. // r.ArrS[3].x
  11488. bool AllowUnitySizeArraySection = true;
  11489. bool AllowWholeSizeArraySection = true;
  11490. while (!RelevantExpr) {
  11491. E = E->IgnoreParenImpCasts();
  11492. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  11493. if (!isa<VarDecl>(CurE->getDecl()))
  11494. return nullptr;
  11495. RelevantExpr = CurE;
  11496. // If we got a reference to a declaration, we should not expect any array
  11497. // section before that.
  11498. AllowUnitySizeArraySection = false;
  11499. AllowWholeSizeArraySection = false;
  11500. // Record the component.
  11501. CurComponents.emplace_back(CurE, CurE->getDecl());
  11502. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  11503. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  11504. if (isa<CXXThisExpr>(BaseE))
  11505. // We found a base expression: this->Val.
  11506. RelevantExpr = CurE;
  11507. else
  11508. E = BaseE;
  11509. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  11510. if (!NoDiagnose) {
  11511. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  11512. << CurE->getSourceRange();
  11513. return nullptr;
  11514. }
  11515. if (RelevantExpr)
  11516. return nullptr;
  11517. continue;
  11518. }
  11519. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  11520. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  11521. // A bit-field cannot appear in a map clause.
  11522. //
  11523. if (FD->isBitField()) {
  11524. if (!NoDiagnose) {
  11525. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  11526. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  11527. return nullptr;
  11528. }
  11529. if (RelevantExpr)
  11530. return nullptr;
  11531. continue;
  11532. }
  11533. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11534. // If the type of a list item is a reference to a type T then the type
  11535. // will be considered to be T for all purposes of this clause.
  11536. QualType CurType = BaseE->getType().getNonReferenceType();
  11537. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  11538. // A list item cannot be a variable that is a member of a structure with
  11539. // a union type.
  11540. //
  11541. if (CurType->isUnionType()) {
  11542. if (!NoDiagnose) {
  11543. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  11544. << CurE->getSourceRange();
  11545. return nullptr;
  11546. }
  11547. continue;
  11548. }
  11549. // If we got a member expression, we should not expect any array section
  11550. // before that:
  11551. //
  11552. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  11553. // If a list item is an element of a structure, only the rightmost symbol
  11554. // of the variable reference can be an array section.
  11555. //
  11556. AllowUnitySizeArraySection = false;
  11557. AllowWholeSizeArraySection = false;
  11558. // Record the component.
  11559. CurComponents.emplace_back(CurE, FD);
  11560. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  11561. E = CurE->getBase()->IgnoreParenImpCasts();
  11562. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  11563. if (!NoDiagnose) {
  11564. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11565. << 0 << CurE->getSourceRange();
  11566. return nullptr;
  11567. }
  11568. continue;
  11569. }
  11570. // If we got an array subscript that express the whole dimension we
  11571. // can have any array expressions before. If it only expressing part of
  11572. // the dimension, we can only have unitary-size array expressions.
  11573. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  11574. E->getType()))
  11575. AllowWholeSizeArraySection = false;
  11576. // Record the component - we don't have any declaration associated.
  11577. CurComponents.emplace_back(CurE, nullptr);
  11578. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  11579. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  11580. E = CurE->getBase()->IgnoreParenImpCasts();
  11581. QualType CurType =
  11582. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11583. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11584. // If the type of a list item is a reference to a type T then the type
  11585. // will be considered to be T for all purposes of this clause.
  11586. if (CurType->isReferenceType())
  11587. CurType = CurType->getPointeeType();
  11588. bool IsPointer = CurType->isAnyPointerType();
  11589. if (!IsPointer && !CurType->isArrayType()) {
  11590. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11591. << 0 << CurE->getSourceRange();
  11592. return nullptr;
  11593. }
  11594. bool NotWhole =
  11595. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  11596. bool NotUnity =
  11597. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  11598. if (AllowWholeSizeArraySection) {
  11599. // Any array section is currently allowed. Allowing a whole size array
  11600. // section implies allowing a unity array section as well.
  11601. //
  11602. // If this array section refers to the whole dimension we can still
  11603. // accept other array sections before this one, except if the base is a
  11604. // pointer. Otherwise, only unitary sections are accepted.
  11605. if (NotWhole || IsPointer)
  11606. AllowWholeSizeArraySection = false;
  11607. } else if (AllowUnitySizeArraySection && NotUnity) {
  11608. // A unity or whole array section is not allowed and that is not
  11609. // compatible with the properties of the current array section.
  11610. SemaRef.Diag(
  11611. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  11612. << CurE->getSourceRange();
  11613. return nullptr;
  11614. }
  11615. // Record the component - we don't have any declaration associated.
  11616. CurComponents.emplace_back(CurE, nullptr);
  11617. } else {
  11618. if (!NoDiagnose) {
  11619. // If nothing else worked, this is not a valid map clause expression.
  11620. SemaRef.Diag(
  11621. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  11622. << ERange;
  11623. }
  11624. return nullptr;
  11625. }
  11626. }
  11627. return RelevantExpr;
  11628. }
  11629. // Return true if expression E associated with value VD has conflicts with other
  11630. // map information.
  11631. static bool checkMapConflicts(
  11632. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  11633. bool CurrentRegionOnly,
  11634. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  11635. OpenMPClauseKind CKind) {
  11636. assert(VD && E);
  11637. SourceLocation ELoc = E->getExprLoc();
  11638. SourceRange ERange = E->getSourceRange();
  11639. // In order to easily check the conflicts we need to match each component of
  11640. // the expression under test with the components of the expressions that are
  11641. // already in the stack.
  11642. assert(!CurComponents.empty() && "Map clause expression with no components!");
  11643. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  11644. "Map clause expression with unexpected base!");
  11645. // Variables to help detecting enclosing problems in data environment nests.
  11646. bool IsEnclosedByDataEnvironmentExpr = false;
  11647. const Expr *EnclosingExpr = nullptr;
  11648. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  11649. VD, CurrentRegionOnly,
  11650. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  11651. ERange, CKind, &EnclosingExpr,
  11652. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  11653. StackComponents,
  11654. OpenMPClauseKind) {
  11655. assert(!StackComponents.empty() &&
  11656. "Map clause expression with no components!");
  11657. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  11658. "Map clause expression with unexpected base!");
  11659. (void)VD;
  11660. // The whole expression in the stack.
  11661. const Expr *RE = StackComponents.front().getAssociatedExpression();
  11662. // Expressions must start from the same base. Here we detect at which
  11663. // point both expressions diverge from each other and see if we can
  11664. // detect if the memory referred to both expressions is contiguous and
  11665. // do not overlap.
  11666. auto CI = CurComponents.rbegin();
  11667. auto CE = CurComponents.rend();
  11668. auto SI = StackComponents.rbegin();
  11669. auto SE = StackComponents.rend();
  11670. for (; CI != CE && SI != SE; ++CI, ++SI) {
  11671. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  11672. // At most one list item can be an array item derived from a given
  11673. // variable in map clauses of the same construct.
  11674. if (CurrentRegionOnly &&
  11675. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  11676. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  11677. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  11678. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  11679. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  11680. diag::err_omp_multiple_array_items_in_map_clause)
  11681. << CI->getAssociatedExpression()->getSourceRange();
  11682. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  11683. diag::note_used_here)
  11684. << SI->getAssociatedExpression()->getSourceRange();
  11685. return true;
  11686. }
  11687. // Do both expressions have the same kind?
  11688. if (CI->getAssociatedExpression()->getStmtClass() !=
  11689. SI->getAssociatedExpression()->getStmtClass())
  11690. break;
  11691. // Are we dealing with different variables/fields?
  11692. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  11693. break;
  11694. }
  11695. // Check if the extra components of the expressions in the enclosing
  11696. // data environment are redundant for the current base declaration.
  11697. // If they are, the maps completely overlap, which is legal.
  11698. for (; SI != SE; ++SI) {
  11699. QualType Type;
  11700. if (const auto *ASE =
  11701. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  11702. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  11703. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  11704. SI->getAssociatedExpression())) {
  11705. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  11706. Type =
  11707. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11708. }
  11709. if (Type.isNull() || Type->isAnyPointerType() ||
  11710. checkArrayExpressionDoesNotReferToWholeSize(
  11711. SemaRef, SI->getAssociatedExpression(), Type))
  11712. break;
  11713. }
  11714. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11715. // List items of map clauses in the same construct must not share
  11716. // original storage.
  11717. //
  11718. // If the expressions are exactly the same or one is a subset of the
  11719. // other, it means they are sharing storage.
  11720. if (CI == CE && SI == SE) {
  11721. if (CurrentRegionOnly) {
  11722. if (CKind == OMPC_map) {
  11723. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11724. } else {
  11725. assert(CKind == OMPC_to || CKind == OMPC_from);
  11726. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11727. << ERange;
  11728. }
  11729. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11730. << RE->getSourceRange();
  11731. return true;
  11732. }
  11733. // If we find the same expression in the enclosing data environment,
  11734. // that is legal.
  11735. IsEnclosedByDataEnvironmentExpr = true;
  11736. return false;
  11737. }
  11738. QualType DerivedType =
  11739. std::prev(CI)->getAssociatedDeclaration()->getType();
  11740. SourceLocation DerivedLoc =
  11741. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  11742. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11743. // If the type of a list item is a reference to a type T then the type
  11744. // will be considered to be T for all purposes of this clause.
  11745. DerivedType = DerivedType.getNonReferenceType();
  11746. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11747. // A variable for which the type is pointer and an array section
  11748. // derived from that variable must not appear as list items of map
  11749. // clauses of the same construct.
  11750. //
  11751. // Also, cover one of the cases in:
  11752. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11753. // If any part of the original storage of a list item has corresponding
  11754. // storage in the device data environment, all of the original storage
  11755. // must have corresponding storage in the device data environment.
  11756. //
  11757. if (DerivedType->isAnyPointerType()) {
  11758. if (CI == CE || SI == SE) {
  11759. SemaRef.Diag(
  11760. DerivedLoc,
  11761. diag::err_omp_pointer_mapped_along_with_derived_section)
  11762. << DerivedLoc;
  11763. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11764. << RE->getSourceRange();
  11765. return true;
  11766. }
  11767. if (CI->getAssociatedExpression()->getStmtClass() !=
  11768. SI->getAssociatedExpression()->getStmtClass() ||
  11769. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  11770. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  11771. assert(CI != CE && SI != SE);
  11772. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  11773. << DerivedLoc;
  11774. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11775. << RE->getSourceRange();
  11776. return true;
  11777. }
  11778. }
  11779. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11780. // List items of map clauses in the same construct must not share
  11781. // original storage.
  11782. //
  11783. // An expression is a subset of the other.
  11784. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11785. if (CKind == OMPC_map) {
  11786. if (CI != CE || SI != SE) {
  11787. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  11788. // a pointer.
  11789. auto Begin =
  11790. CI != CE ? CurComponents.begin() : StackComponents.begin();
  11791. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  11792. auto It = Begin;
  11793. while (It != End && !It->getAssociatedDeclaration())
  11794. std::advance(It, 1);
  11795. assert(It != End &&
  11796. "Expected at least one component with the declaration.");
  11797. if (It != Begin && It->getAssociatedDeclaration()
  11798. ->getType()
  11799. .getCanonicalType()
  11800. ->isAnyPointerType()) {
  11801. IsEnclosedByDataEnvironmentExpr = false;
  11802. EnclosingExpr = nullptr;
  11803. return false;
  11804. }
  11805. }
  11806. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11807. } else {
  11808. assert(CKind == OMPC_to || CKind == OMPC_from);
  11809. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11810. << ERange;
  11811. }
  11812. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11813. << RE->getSourceRange();
  11814. return true;
  11815. }
  11816. // The current expression uses the same base as other expression in the
  11817. // data environment but does not contain it completely.
  11818. if (!CurrentRegionOnly && SI != SE)
  11819. EnclosingExpr = RE;
  11820. // The current expression is a subset of the expression in the data
  11821. // environment.
  11822. IsEnclosedByDataEnvironmentExpr |=
  11823. (!CurrentRegionOnly && CI != CE && SI == SE);
  11824. return false;
  11825. });
  11826. if (CurrentRegionOnly)
  11827. return FoundError;
  11828. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11829. // If any part of the original storage of a list item has corresponding
  11830. // storage in the device data environment, all of the original storage must
  11831. // have corresponding storage in the device data environment.
  11832. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11833. // If a list item is an element of a structure, and a different element of
  11834. // the structure has a corresponding list item in the device data environment
  11835. // prior to a task encountering the construct associated with the map clause,
  11836. // then the list item must also have a corresponding list item in the device
  11837. // data environment prior to the task encountering the construct.
  11838. //
  11839. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11840. SemaRef.Diag(ELoc,
  11841. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11842. << ERange;
  11843. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11844. << EnclosingExpr->getSourceRange();
  11845. return true;
  11846. }
  11847. return FoundError;
  11848. }
  11849. namespace {
  11850. // Utility struct that gathers all the related lists associated with a mappable
  11851. // expression.
  11852. struct MappableVarListInfo {
  11853. // The list of expressions.
  11854. ArrayRef<Expr *> VarList;
  11855. // The list of processed expressions.
  11856. SmallVector<Expr *, 16> ProcessedVarList;
  11857. // The mappble components for each expression.
  11858. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11859. // The base declaration of the variable.
  11860. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11861. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11862. // We have a list of components and base declarations for each entry in the
  11863. // variable list.
  11864. VarComponents.reserve(VarList.size());
  11865. VarBaseDeclarations.reserve(VarList.size());
  11866. }
  11867. };
  11868. }
  11869. // Check the validity of the provided variable list for the provided clause kind
  11870. // \a CKind. In the check process the valid expressions, and mappable expression
  11871. // components and variables are extracted and used to fill \a Vars,
  11872. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11873. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11874. static void
  11875. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11876. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11877. SourceLocation StartLoc,
  11878. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11879. bool IsMapTypeImplicit = false) {
  11880. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11881. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11882. "Unexpected clause kind with mappable expressions!");
  11883. // Keep track of the mappable components and base declarations in this clause.
  11884. // Each entry in the list is going to have a list of components associated. We
  11885. // record each set of the components so that we can build the clause later on.
  11886. // In the end we should have the same amount of declarations and component
  11887. // lists.
  11888. for (Expr *RE : MVLI.VarList) {
  11889. assert(RE && "Null expr in omp to/from/map clause");
  11890. SourceLocation ELoc = RE->getExprLoc();
  11891. const Expr *VE = RE->IgnoreParenLValueCasts();
  11892. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11893. VE->isInstantiationDependent() ||
  11894. VE->containsUnexpandedParameterPack()) {
  11895. // We can only analyze this information once the missing information is
  11896. // resolved.
  11897. MVLI.ProcessedVarList.push_back(RE);
  11898. continue;
  11899. }
  11900. Expr *SimpleExpr = RE->IgnoreParenCasts();
  11901. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11902. SemaRef.Diag(ELoc,
  11903. diag::err_omp_expected_named_var_member_or_array_expression)
  11904. << RE->getSourceRange();
  11905. continue;
  11906. }
  11907. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11908. ValueDecl *CurDeclaration = nullptr;
  11909. // Obtain the array or member expression bases if required. Also, fill the
  11910. // components array with all the components identified in the process.
  11911. const Expr *BE = checkMapClauseExpressionBase(
  11912. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  11913. if (!BE)
  11914. continue;
  11915. assert(!CurComponents.empty() &&
  11916. "Invalid mappable expression information.");
  11917. // For the following checks, we rely on the base declaration which is
  11918. // expected to be associated with the last component. The declaration is
  11919. // expected to be a variable or a field (if 'this' is being mapped).
  11920. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11921. assert(CurDeclaration && "Null decl on map clause.");
  11922. assert(
  11923. CurDeclaration->isCanonicalDecl() &&
  11924. "Expecting components to have associated only canonical declarations.");
  11925. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11926. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11927. assert((VD || FD) && "Only variables or fields are expected here!");
  11928. (void)FD;
  11929. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11930. // threadprivate variables cannot appear in a map clause.
  11931. // OpenMP 4.5 [2.10.5, target update Construct]
  11932. // threadprivate variables cannot appear in a from clause.
  11933. if (VD && DSAS->isThreadPrivate(VD)) {
  11934. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  11935. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11936. << getOpenMPClauseName(CKind);
  11937. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  11938. continue;
  11939. }
  11940. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11941. // A list item cannot appear in both a map clause and a data-sharing
  11942. // attribute clause on the same construct.
  11943. // Check conflicts with other map clause expressions. We check the conflicts
  11944. // with the current construct separately from the enclosing data
  11945. // environment, because the restrictions are different. We only have to
  11946. // check conflicts across regions for the map clauses.
  11947. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11948. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  11949. break;
  11950. if (CKind == OMPC_map &&
  11951. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11952. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  11953. break;
  11954. // OpenMP 4.5 [2.10.5, target update Construct]
  11955. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11956. // If the type of a list item is a reference to a type T then the type will
  11957. // be considered to be T for all purposes of this clause.
  11958. auto I = llvm::find_if(
  11959. CurComponents,
  11960. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  11961. return MC.getAssociatedDeclaration();
  11962. });
  11963. assert(I != CurComponents.end() && "Null decl on map clause.");
  11964. QualType Type =
  11965. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  11966. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  11967. // A list item in a to or from clause must have a mappable type.
  11968. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11969. // A list item must have a mappable type.
  11970. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  11971. DSAS, Type))
  11972. continue;
  11973. if (CKind == OMPC_map) {
  11974. // target enter data
  11975. // OpenMP [2.10.2, Restrictions, p. 99]
  11976. // A map-type must be specified in all map clauses and must be either
  11977. // to or alloc.
  11978. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  11979. if (DKind == OMPD_target_enter_data &&
  11980. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  11981. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11982. << (IsMapTypeImplicit ? 1 : 0)
  11983. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11984. << getOpenMPDirectiveName(DKind);
  11985. continue;
  11986. }
  11987. // target exit_data
  11988. // OpenMP [2.10.3, Restrictions, p. 102]
  11989. // A map-type must be specified in all map clauses and must be either
  11990. // from, release, or delete.
  11991. if (DKind == OMPD_target_exit_data &&
  11992. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  11993. MapType == OMPC_MAP_delete)) {
  11994. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11995. << (IsMapTypeImplicit ? 1 : 0)
  11996. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11997. << getOpenMPDirectiveName(DKind);
  11998. continue;
  11999. }
  12000. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  12001. // A list item cannot appear in both a map clause and a data-sharing
  12002. // attribute clause on the same construct
  12003. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  12004. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12005. if (isOpenMPPrivate(DVar.CKind)) {
  12006. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12007. << getOpenMPClauseName(DVar.CKind)
  12008. << getOpenMPClauseName(OMPC_map)
  12009. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  12010. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  12011. continue;
  12012. }
  12013. }
  12014. }
  12015. // Save the current expression.
  12016. MVLI.ProcessedVarList.push_back(RE);
  12017. // Store the components in the stack so that they can be used to check
  12018. // against other clauses later on.
  12019. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  12020. /*WhereFoundClauseKind=*/OMPC_map);
  12021. // Save the components and declaration to create the clause. For purposes of
  12022. // the clause creation, any component list that has has base 'this' uses
  12023. // null as base declaration.
  12024. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12025. MVLI.VarComponents.back().append(CurComponents.begin(),
  12026. CurComponents.end());
  12027. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  12028. : CurDeclaration);
  12029. }
  12030. }
  12031. OMPClause *
  12032. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  12033. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  12034. SourceLocation MapLoc, SourceLocation ColonLoc,
  12035. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  12036. SourceLocation LParenLoc, SourceLocation EndLoc) {
  12037. MappableVarListInfo MVLI(VarList);
  12038. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  12039. MapType, IsMapTypeImplicit);
  12040. // We need to produce a map clause even if we don't have variables so that
  12041. // other diagnostics related with non-existing map clauses are accurate.
  12042. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12043. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12044. MVLI.VarComponents, MapTypeModifier, MapType,
  12045. IsMapTypeImplicit, MapLoc);
  12046. }
  12047. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  12048. TypeResult ParsedType) {
  12049. assert(ParsedType.isUsable());
  12050. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  12051. if (ReductionType.isNull())
  12052. return QualType();
  12053. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  12054. // A type name in a declare reduction directive cannot be a function type, an
  12055. // array type, a reference type, or a type qualified with const, volatile or
  12056. // restrict.
  12057. if (ReductionType.hasQualifiers()) {
  12058. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  12059. return QualType();
  12060. }
  12061. if (ReductionType->isFunctionType()) {
  12062. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  12063. return QualType();
  12064. }
  12065. if (ReductionType->isReferenceType()) {
  12066. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  12067. return QualType();
  12068. }
  12069. if (ReductionType->isArrayType()) {
  12070. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  12071. return QualType();
  12072. }
  12073. return ReductionType;
  12074. }
  12075. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  12076. Scope *S, DeclContext *DC, DeclarationName Name,
  12077. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  12078. AccessSpecifier AS, Decl *PrevDeclInScope) {
  12079. SmallVector<Decl *, 8> Decls;
  12080. Decls.reserve(ReductionTypes.size());
  12081. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  12082. forRedeclarationInCurContext());
  12083. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  12084. // A reduction-identifier may not be re-declared in the current scope for the
  12085. // same type or for a type that is compatible according to the base language
  12086. // rules.
  12087. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12088. OMPDeclareReductionDecl *PrevDRD = nullptr;
  12089. bool InCompoundScope = true;
  12090. if (S != nullptr) {
  12091. // Find previous declaration with the same name not referenced in other
  12092. // declarations.
  12093. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12094. InCompoundScope =
  12095. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12096. LookupName(Lookup, S);
  12097. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12098. /*AllowInlineNamespace=*/false);
  12099. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  12100. LookupResult::Filter Filter = Lookup.makeFilter();
  12101. while (Filter.hasNext()) {
  12102. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  12103. if (InCompoundScope) {
  12104. auto I = UsedAsPrevious.find(PrevDecl);
  12105. if (I == UsedAsPrevious.end())
  12106. UsedAsPrevious[PrevDecl] = false;
  12107. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  12108. UsedAsPrevious[D] = true;
  12109. }
  12110. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12111. PrevDecl->getLocation();
  12112. }
  12113. Filter.done();
  12114. if (InCompoundScope) {
  12115. for (const auto &PrevData : UsedAsPrevious) {
  12116. if (!PrevData.second) {
  12117. PrevDRD = PrevData.first;
  12118. break;
  12119. }
  12120. }
  12121. }
  12122. } else if (PrevDeclInScope != nullptr) {
  12123. auto *PrevDRDInScope = PrevDRD =
  12124. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  12125. do {
  12126. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  12127. PrevDRDInScope->getLocation();
  12128. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  12129. } while (PrevDRDInScope != nullptr);
  12130. }
  12131. for (const auto &TyData : ReductionTypes) {
  12132. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  12133. bool Invalid = false;
  12134. if (I != PreviousRedeclTypes.end()) {
  12135. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  12136. << TyData.first;
  12137. Diag(I->second, diag::note_previous_definition);
  12138. Invalid = true;
  12139. }
  12140. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  12141. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  12142. Name, TyData.first, PrevDRD);
  12143. DC->addDecl(DRD);
  12144. DRD->setAccess(AS);
  12145. Decls.push_back(DRD);
  12146. if (Invalid)
  12147. DRD->setInvalidDecl();
  12148. else
  12149. PrevDRD = DRD;
  12150. }
  12151. return DeclGroupPtrTy::make(
  12152. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  12153. }
  12154. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  12155. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12156. // Enter new function scope.
  12157. PushFunctionScope();
  12158. setFunctionHasBranchProtectedScope();
  12159. getCurFunction()->setHasOMPDeclareReductionCombiner();
  12160. if (S != nullptr)
  12161. PushDeclContext(S, DRD);
  12162. else
  12163. CurContext = DRD;
  12164. PushExpressionEvaluationContext(
  12165. ExpressionEvaluationContext::PotentiallyEvaluated);
  12166. QualType ReductionType = DRD->getType();
  12167. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  12168. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  12169. // uses semantics of argument handles by value, but it should be passed by
  12170. // reference. C lang does not support references, so pass all parameters as
  12171. // pointers.
  12172. // Create 'T omp_in;' variable.
  12173. VarDecl *OmpInParm =
  12174. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  12175. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  12176. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  12177. // uses semantics of argument handles by value, but it should be passed by
  12178. // reference. C lang does not support references, so pass all parameters as
  12179. // pointers.
  12180. // Create 'T omp_out;' variable.
  12181. VarDecl *OmpOutParm =
  12182. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  12183. if (S != nullptr) {
  12184. PushOnScopeChains(OmpInParm, S);
  12185. PushOnScopeChains(OmpOutParm, S);
  12186. } else {
  12187. DRD->addDecl(OmpInParm);
  12188. DRD->addDecl(OmpOutParm);
  12189. }
  12190. Expr *InE =
  12191. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  12192. Expr *OutE =
  12193. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  12194. DRD->setCombinerData(InE, OutE);
  12195. }
  12196. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  12197. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12198. DiscardCleanupsInEvaluationContext();
  12199. PopExpressionEvaluationContext();
  12200. PopDeclContext();
  12201. PopFunctionScopeInfo();
  12202. if (Combiner != nullptr)
  12203. DRD->setCombiner(Combiner);
  12204. else
  12205. DRD->setInvalidDecl();
  12206. }
  12207. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  12208. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12209. // Enter new function scope.
  12210. PushFunctionScope();
  12211. setFunctionHasBranchProtectedScope();
  12212. if (S != nullptr)
  12213. PushDeclContext(S, DRD);
  12214. else
  12215. CurContext = DRD;
  12216. PushExpressionEvaluationContext(
  12217. ExpressionEvaluationContext::PotentiallyEvaluated);
  12218. QualType ReductionType = DRD->getType();
  12219. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  12220. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  12221. // uses semantics of argument handles by value, but it should be passed by
  12222. // reference. C lang does not support references, so pass all parameters as
  12223. // pointers.
  12224. // Create 'T omp_priv;' variable.
  12225. VarDecl *OmpPrivParm =
  12226. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  12227. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  12228. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  12229. // uses semantics of argument handles by value, but it should be passed by
  12230. // reference. C lang does not support references, so pass all parameters as
  12231. // pointers.
  12232. // Create 'T omp_orig;' variable.
  12233. VarDecl *OmpOrigParm =
  12234. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  12235. if (S != nullptr) {
  12236. PushOnScopeChains(OmpPrivParm, S);
  12237. PushOnScopeChains(OmpOrigParm, S);
  12238. } else {
  12239. DRD->addDecl(OmpPrivParm);
  12240. DRD->addDecl(OmpOrigParm);
  12241. }
  12242. Expr *OrigE =
  12243. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  12244. Expr *PrivE =
  12245. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  12246. DRD->setInitializerData(OrigE, PrivE);
  12247. return OmpPrivParm;
  12248. }
  12249. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  12250. VarDecl *OmpPrivParm) {
  12251. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12252. DiscardCleanupsInEvaluationContext();
  12253. PopExpressionEvaluationContext();
  12254. PopDeclContext();
  12255. PopFunctionScopeInfo();
  12256. if (Initializer != nullptr) {
  12257. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  12258. } else if (OmpPrivParm->hasInit()) {
  12259. DRD->setInitializer(OmpPrivParm->getInit(),
  12260. OmpPrivParm->isDirectInit()
  12261. ? OMPDeclareReductionDecl::DirectInit
  12262. : OMPDeclareReductionDecl::CopyInit);
  12263. } else {
  12264. DRD->setInvalidDecl();
  12265. }
  12266. }
  12267. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  12268. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  12269. for (Decl *D : DeclReductions.get()) {
  12270. if (IsValid) {
  12271. if (S)
  12272. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  12273. /*AddToContext=*/false);
  12274. } else {
  12275. D->setInvalidDecl();
  12276. }
  12277. }
  12278. return DeclReductions;
  12279. }
  12280. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  12281. SourceLocation StartLoc,
  12282. SourceLocation LParenLoc,
  12283. SourceLocation EndLoc) {
  12284. Expr *ValExpr = NumTeams;
  12285. Stmt *HelperValStmt = nullptr;
  12286. // OpenMP [teams Constrcut, Restrictions]
  12287. // The num_teams expression must evaluate to a positive integer value.
  12288. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  12289. /*StrictlyPositive=*/true))
  12290. return nullptr;
  12291. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12292. OpenMPDirectiveKind CaptureRegion =
  12293. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  12294. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12295. ValExpr = MakeFullExpr(ValExpr).get();
  12296. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12297. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12298. HelperValStmt = buildPreInits(Context, Captures);
  12299. }
  12300. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  12301. StartLoc, LParenLoc, EndLoc);
  12302. }
  12303. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  12304. SourceLocation StartLoc,
  12305. SourceLocation LParenLoc,
  12306. SourceLocation EndLoc) {
  12307. Expr *ValExpr = ThreadLimit;
  12308. Stmt *HelperValStmt = nullptr;
  12309. // OpenMP [teams Constrcut, Restrictions]
  12310. // The thread_limit expression must evaluate to a positive integer value.
  12311. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  12312. /*StrictlyPositive=*/true))
  12313. return nullptr;
  12314. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12315. OpenMPDirectiveKind CaptureRegion =
  12316. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  12317. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12318. ValExpr = MakeFullExpr(ValExpr).get();
  12319. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12320. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12321. HelperValStmt = buildPreInits(Context, Captures);
  12322. }
  12323. return new (Context) OMPThreadLimitClause(
  12324. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  12325. }
  12326. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  12327. SourceLocation StartLoc,
  12328. SourceLocation LParenLoc,
  12329. SourceLocation EndLoc) {
  12330. Expr *ValExpr = Priority;
  12331. // OpenMP [2.9.1, task Constrcut]
  12332. // The priority-value is a non-negative numerical scalar expression.
  12333. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  12334. /*StrictlyPositive=*/false))
  12335. return nullptr;
  12336. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12337. }
  12338. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  12339. SourceLocation StartLoc,
  12340. SourceLocation LParenLoc,
  12341. SourceLocation EndLoc) {
  12342. Expr *ValExpr = Grainsize;
  12343. // OpenMP [2.9.2, taskloop Constrcut]
  12344. // The parameter of the grainsize clause must be a positive integer
  12345. // expression.
  12346. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  12347. /*StrictlyPositive=*/true))
  12348. return nullptr;
  12349. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12350. }
  12351. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  12352. SourceLocation StartLoc,
  12353. SourceLocation LParenLoc,
  12354. SourceLocation EndLoc) {
  12355. Expr *ValExpr = NumTasks;
  12356. // OpenMP [2.9.2, taskloop Constrcut]
  12357. // The parameter of the num_tasks clause must be a positive integer
  12358. // expression.
  12359. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  12360. /*StrictlyPositive=*/true))
  12361. return nullptr;
  12362. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12363. }
  12364. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  12365. SourceLocation LParenLoc,
  12366. SourceLocation EndLoc) {
  12367. // OpenMP [2.13.2, critical construct, Description]
  12368. // ... where hint-expression is an integer constant expression that evaluates
  12369. // to a valid lock hint.
  12370. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  12371. if (HintExpr.isInvalid())
  12372. return nullptr;
  12373. return new (Context)
  12374. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  12375. }
  12376. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  12377. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  12378. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  12379. SourceLocation EndLoc) {
  12380. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  12381. std::string Values;
  12382. Values += "'";
  12383. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  12384. Values += "'";
  12385. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  12386. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  12387. return nullptr;
  12388. }
  12389. Expr *ValExpr = ChunkSize;
  12390. Stmt *HelperValStmt = nullptr;
  12391. if (ChunkSize) {
  12392. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  12393. !ChunkSize->isInstantiationDependent() &&
  12394. !ChunkSize->containsUnexpandedParameterPack()) {
  12395. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  12396. ExprResult Val =
  12397. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  12398. if (Val.isInvalid())
  12399. return nullptr;
  12400. ValExpr = Val.get();
  12401. // OpenMP [2.7.1, Restrictions]
  12402. // chunk_size must be a loop invariant integer expression with a positive
  12403. // value.
  12404. llvm::APSInt Result;
  12405. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  12406. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  12407. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  12408. << "dist_schedule" << ChunkSize->getSourceRange();
  12409. return nullptr;
  12410. }
  12411. } else if (getOpenMPCaptureRegionForClause(
  12412. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  12413. OMPD_unknown &&
  12414. !CurContext->isDependentContext()) {
  12415. ValExpr = MakeFullExpr(ValExpr).get();
  12416. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12417. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12418. HelperValStmt = buildPreInits(Context, Captures);
  12419. }
  12420. }
  12421. }
  12422. return new (Context)
  12423. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  12424. Kind, ValExpr, HelperValStmt);
  12425. }
  12426. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  12427. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  12428. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  12429. SourceLocation KindLoc, SourceLocation EndLoc) {
  12430. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  12431. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  12432. std::string Value;
  12433. SourceLocation Loc;
  12434. Value += "'";
  12435. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  12436. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  12437. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  12438. Loc = MLoc;
  12439. } else {
  12440. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  12441. OMPC_DEFAULTMAP_scalar);
  12442. Loc = KindLoc;
  12443. }
  12444. Value += "'";
  12445. Diag(Loc, diag::err_omp_unexpected_clause_value)
  12446. << Value << getOpenMPClauseName(OMPC_defaultmap);
  12447. return nullptr;
  12448. }
  12449. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  12450. return new (Context)
  12451. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  12452. }
  12453. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  12454. DeclContext *CurLexicalContext = getCurLexicalContext();
  12455. if (!CurLexicalContext->isFileContext() &&
  12456. !CurLexicalContext->isExternCContext() &&
  12457. !CurLexicalContext->isExternCXXContext() &&
  12458. !isa<CXXRecordDecl>(CurLexicalContext) &&
  12459. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  12460. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  12461. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  12462. Diag(Loc, diag::err_omp_region_not_file_context);
  12463. return false;
  12464. }
  12465. ++DeclareTargetNestingLevel;
  12466. return true;
  12467. }
  12468. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  12469. assert(DeclareTargetNestingLevel > 0 &&
  12470. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  12471. --DeclareTargetNestingLevel;
  12472. }
  12473. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  12474. CXXScopeSpec &ScopeSpec,
  12475. const DeclarationNameInfo &Id,
  12476. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  12477. NamedDeclSetType &SameDirectiveDecls) {
  12478. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  12479. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  12480. if (Lookup.isAmbiguous())
  12481. return;
  12482. Lookup.suppressDiagnostics();
  12483. if (!Lookup.isSingleResult()) {
  12484. if (TypoCorrection Corrected =
  12485. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  12486. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  12487. CTK_ErrorRecovery)) {
  12488. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  12489. << Id.getName());
  12490. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  12491. return;
  12492. }
  12493. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  12494. return;
  12495. }
  12496. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  12497. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  12498. isa<FunctionTemplateDecl>(ND)) {
  12499. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  12500. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  12501. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  12502. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  12503. cast<ValueDecl>(ND));
  12504. if (!Res) {
  12505. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  12506. ND->addAttr(A);
  12507. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12508. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  12509. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  12510. } else if (*Res != MT) {
  12511. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  12512. << Id.getName();
  12513. }
  12514. } else {
  12515. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  12516. }
  12517. }
  12518. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  12519. Sema &SemaRef, Decl *D) {
  12520. if (!D || !isa<VarDecl>(D))
  12521. return;
  12522. auto *VD = cast<VarDecl>(D);
  12523. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  12524. return;
  12525. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  12526. SemaRef.Diag(SL, diag::note_used_here) << SR;
  12527. }
  12528. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  12529. Sema &SemaRef, DSAStackTy *Stack,
  12530. ValueDecl *VD) {
  12531. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  12532. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  12533. /*FullCheck=*/false);
  12534. }
  12535. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  12536. SourceLocation IdLoc) {
  12537. if (!D || D->isInvalidDecl())
  12538. return;
  12539. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  12540. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  12541. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12542. // Only global variables can be marked as declare target.
  12543. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  12544. !VD->isStaticDataMember())
  12545. return;
  12546. // 2.10.6: threadprivate variable cannot appear in a declare target
  12547. // directive.
  12548. if (DSAStack->isThreadPrivate(VD)) {
  12549. Diag(SL, diag::err_omp_threadprivate_in_target);
  12550. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  12551. return;
  12552. }
  12553. }
  12554. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  12555. D = FTD->getTemplatedDecl();
  12556. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  12557. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  12558. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  12559. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  12560. assert(IdLoc.isValid() && "Source location is expected");
  12561. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  12562. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  12563. return;
  12564. }
  12565. }
  12566. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  12567. // Problem if any with var declared with incomplete type will be reported
  12568. // as normal, so no need to check it here.
  12569. if ((E || !VD->getType()->isIncompleteType()) &&
  12570. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  12571. return;
  12572. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  12573. // Checking declaration inside declare target region.
  12574. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  12575. isa<FunctionTemplateDecl>(D)) {
  12576. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12577. Context, OMPDeclareTargetDeclAttr::MT_To);
  12578. D->addAttr(A);
  12579. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12580. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12581. }
  12582. return;
  12583. }
  12584. }
  12585. if (!E)
  12586. return;
  12587. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  12588. }
  12589. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  12590. SourceLocation StartLoc,
  12591. SourceLocation LParenLoc,
  12592. SourceLocation EndLoc) {
  12593. MappableVarListInfo MVLI(VarList);
  12594. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  12595. if (MVLI.ProcessedVarList.empty())
  12596. return nullptr;
  12597. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12598. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12599. MVLI.VarComponents);
  12600. }
  12601. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  12602. SourceLocation StartLoc,
  12603. SourceLocation LParenLoc,
  12604. SourceLocation EndLoc) {
  12605. MappableVarListInfo MVLI(VarList);
  12606. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  12607. if (MVLI.ProcessedVarList.empty())
  12608. return nullptr;
  12609. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12610. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12611. MVLI.VarComponents);
  12612. }
  12613. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  12614. SourceLocation StartLoc,
  12615. SourceLocation LParenLoc,
  12616. SourceLocation EndLoc) {
  12617. MappableVarListInfo MVLI(VarList);
  12618. SmallVector<Expr *, 8> PrivateCopies;
  12619. SmallVector<Expr *, 8> Inits;
  12620. for (Expr *RefExpr : VarList) {
  12621. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  12622. SourceLocation ELoc;
  12623. SourceRange ERange;
  12624. Expr *SimpleRefExpr = RefExpr;
  12625. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12626. if (Res.second) {
  12627. // It will be analyzed later.
  12628. MVLI.ProcessedVarList.push_back(RefExpr);
  12629. PrivateCopies.push_back(nullptr);
  12630. Inits.push_back(nullptr);
  12631. }
  12632. ValueDecl *D = Res.first;
  12633. if (!D)
  12634. continue;
  12635. QualType Type = D->getType();
  12636. Type = Type.getNonReferenceType().getUnqualifiedType();
  12637. auto *VD = dyn_cast<VarDecl>(D);
  12638. // Item should be a pointer or reference to pointer.
  12639. if (!Type->isPointerType()) {
  12640. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  12641. << 0 << RefExpr->getSourceRange();
  12642. continue;
  12643. }
  12644. // Build the private variable and the expression that refers to it.
  12645. auto VDPrivate =
  12646. buildVarDecl(*this, ELoc, Type, D->getName(),
  12647. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12648. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12649. if (VDPrivate->isInvalidDecl())
  12650. continue;
  12651. CurContext->addDecl(VDPrivate);
  12652. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  12653. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  12654. // Add temporary variable to initialize the private copy of the pointer.
  12655. VarDecl *VDInit =
  12656. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  12657. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  12658. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  12659. AddInitializerToDecl(VDPrivate,
  12660. DefaultLvalueConversion(VDInitRefExpr).get(),
  12661. /*DirectInit=*/false);
  12662. // If required, build a capture to implement the privatization initialized
  12663. // with the current list item value.
  12664. DeclRefExpr *Ref = nullptr;
  12665. if (!VD)
  12666. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12667. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  12668. PrivateCopies.push_back(VDPrivateRefExpr);
  12669. Inits.push_back(VDInitRefExpr);
  12670. // We need to add a data sharing attribute for this variable to make sure it
  12671. // is correctly captured. A variable that shows up in a use_device_ptr has
  12672. // similar properties of a first private variable.
  12673. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  12674. // Create a mappable component for the list item. List items in this clause
  12675. // only need a component.
  12676. MVLI.VarBaseDeclarations.push_back(D);
  12677. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12678. MVLI.VarComponents.back().push_back(
  12679. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  12680. }
  12681. if (MVLI.ProcessedVarList.empty())
  12682. return nullptr;
  12683. return OMPUseDevicePtrClause::Create(
  12684. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12685. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12686. }
  12687. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  12688. SourceLocation StartLoc,
  12689. SourceLocation LParenLoc,
  12690. SourceLocation EndLoc) {
  12691. MappableVarListInfo MVLI(VarList);
  12692. for (Expr *RefExpr : VarList) {
  12693. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  12694. SourceLocation ELoc;
  12695. SourceRange ERange;
  12696. Expr *SimpleRefExpr = RefExpr;
  12697. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12698. if (Res.second) {
  12699. // It will be analyzed later.
  12700. MVLI.ProcessedVarList.push_back(RefExpr);
  12701. }
  12702. ValueDecl *D = Res.first;
  12703. if (!D)
  12704. continue;
  12705. QualType Type = D->getType();
  12706. // item should be a pointer or array or reference to pointer or array
  12707. if (!Type.getNonReferenceType()->isPointerType() &&
  12708. !Type.getNonReferenceType()->isArrayType()) {
  12709. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  12710. << 0 << RefExpr->getSourceRange();
  12711. continue;
  12712. }
  12713. // Check if the declaration in the clause does not show up in any data
  12714. // sharing attribute.
  12715. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12716. if (isOpenMPPrivate(DVar.CKind)) {
  12717. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12718. << getOpenMPClauseName(DVar.CKind)
  12719. << getOpenMPClauseName(OMPC_is_device_ptr)
  12720. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12721. reportOriginalDsa(*this, DSAStack, D, DVar);
  12722. continue;
  12723. }
  12724. const Expr *ConflictExpr;
  12725. if (DSAStack->checkMappableExprComponentListsForDecl(
  12726. D, /*CurrentRegionOnly=*/true,
  12727. [&ConflictExpr](
  12728. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  12729. OpenMPClauseKind) -> bool {
  12730. ConflictExpr = R.front().getAssociatedExpression();
  12731. return true;
  12732. })) {
  12733. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  12734. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  12735. << ConflictExpr->getSourceRange();
  12736. continue;
  12737. }
  12738. // Store the components in the stack so that they can be used to check
  12739. // against other clauses later on.
  12740. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  12741. DSAStack->addMappableExpressionComponents(
  12742. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  12743. // Record the expression we've just processed.
  12744. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  12745. // Create a mappable component for the list item. List items in this clause
  12746. // only need a component. We use a null declaration to signal fields in
  12747. // 'this'.
  12748. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12749. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12750. "Unexpected device pointer expression!");
  12751. MVLI.VarBaseDeclarations.push_back(
  12752. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12753. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12754. MVLI.VarComponents.back().push_back(MC);
  12755. }
  12756. if (MVLI.ProcessedVarList.empty())
  12757. return nullptr;
  12758. return OMPIsDevicePtrClause::Create(
  12759. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12760. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12761. }