SemaOpenMP.cpp 546 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763
  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. if ((I != StartI->SharingMap.end()) &&
  1189. I->getSecond().RefExpr.getPointer() &&
  1190. CPred(I->getSecond().Attributes) &&
  1191. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1192. return true;
  1193. // Check predetermined rules for the loop control variables.
  1194. auto LI = StartI->LCVMap.find(D);
  1195. if (LI != StartI->LCVMap.end())
  1196. return CPred(OMPC_private);
  1197. return false;
  1198. }
  1199. bool DSAStackTy::hasExplicitDirective(
  1200. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1201. unsigned Level) const {
  1202. if (isStackEmpty())
  1203. return false;
  1204. auto StartI = Stack.back().first.begin();
  1205. auto EndI = Stack.back().first.end();
  1206. if (std::distance(StartI, EndI) <= (int)Level)
  1207. return false;
  1208. std::advance(StartI, Level);
  1209. return DPred(StartI->Directive);
  1210. }
  1211. bool DSAStackTy::hasDirective(
  1212. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1213. const DeclarationNameInfo &, SourceLocation)>
  1214. DPred,
  1215. bool FromParent) const {
  1216. // We look only in the enclosing region.
  1217. if (isStackEmpty())
  1218. return false;
  1219. auto StartI = std::next(Stack.back().first.rbegin());
  1220. auto EndI = Stack.back().first.rend();
  1221. if (FromParent && StartI != EndI)
  1222. StartI = std::next(StartI);
  1223. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1224. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1225. return true;
  1226. }
  1227. return false;
  1228. }
  1229. void Sema::InitDataSharingAttributesStack() {
  1230. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1231. }
  1232. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1233. void Sema::pushOpenMPFunctionRegion() {
  1234. DSAStack->pushFunction();
  1235. }
  1236. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1237. DSAStack->popFunction(OldFSI);
  1238. }
  1239. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1240. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1241. ASTContext &Ctx = getASTContext();
  1242. bool IsByRef = true;
  1243. // Find the directive that is associated with the provided scope.
  1244. D = cast<ValueDecl>(D->getCanonicalDecl());
  1245. QualType Ty = D->getType();
  1246. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1247. // This table summarizes how a given variable should be passed to the device
  1248. // given its type and the clauses where it appears. This table is based on
  1249. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1250. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1251. //
  1252. // =========================================================================
  1253. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1254. // | |(tofrom:scalar)| | pvt | | | |
  1255. // =========================================================================
  1256. // | scl | | | | - | | bycopy|
  1257. // | scl | | - | x | - | - | bycopy|
  1258. // | scl | | x | - | - | - | null |
  1259. // | scl | x | | | - | | byref |
  1260. // | scl | x | - | x | - | - | bycopy|
  1261. // | scl | x | x | - | - | - | null |
  1262. // | scl | | - | - | - | x | byref |
  1263. // | scl | x | - | - | - | x | byref |
  1264. //
  1265. // | agg | n.a. | | | - | | byref |
  1266. // | agg | n.a. | - | x | - | - | byref |
  1267. // | agg | n.a. | x | - | - | - | null |
  1268. // | agg | n.a. | - | - | - | x | byref |
  1269. // | agg | n.a. | - | - | - | x[] | byref |
  1270. //
  1271. // | ptr | n.a. | | | - | | bycopy|
  1272. // | ptr | n.a. | - | x | - | - | bycopy|
  1273. // | ptr | n.a. | x | - | - | - | null |
  1274. // | ptr | n.a. | - | - | - | x | byref |
  1275. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1276. // | ptr | n.a. | - | - | x | | bycopy|
  1277. // | ptr | n.a. | - | - | x | x | bycopy|
  1278. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1279. // =========================================================================
  1280. // Legend:
  1281. // scl - scalar
  1282. // ptr - pointer
  1283. // agg - aggregate
  1284. // x - applies
  1285. // - - invalid in this combination
  1286. // [] - mapped with an array section
  1287. // byref - should be mapped by reference
  1288. // byval - should be mapped by value
  1289. // null - initialize a local variable to null on the device
  1290. //
  1291. // Observations:
  1292. // - All scalar declarations that show up in a map clause have to be passed
  1293. // by reference, because they may have been mapped in the enclosing data
  1294. // environment.
  1295. // - If the scalar value does not fit the size of uintptr, it has to be
  1296. // passed by reference, regardless the result in the table above.
  1297. // - For pointers mapped by value that have either an implicit map or an
  1298. // array section, the runtime library may pass the NULL value to the
  1299. // device instead of the value passed to it by the compiler.
  1300. if (Ty->isReferenceType())
  1301. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1302. // Locate map clauses and see if the variable being captured is referred to
  1303. // in any of those clauses. Here we only care about variables, not fields,
  1304. // because fields are part of aggregates.
  1305. bool IsVariableUsedInMapClause = false;
  1306. bool IsVariableAssociatedWithSection = false;
  1307. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1308. D, Level,
  1309. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1310. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1311. MapExprComponents,
  1312. OpenMPClauseKind WhereFoundClauseKind) {
  1313. // Only the map clause information influences how a variable is
  1314. // captured. E.g. is_device_ptr does not require changing the default
  1315. // behavior.
  1316. if (WhereFoundClauseKind != OMPC_map)
  1317. return false;
  1318. auto EI = MapExprComponents.rbegin();
  1319. auto EE = MapExprComponents.rend();
  1320. assert(EI != EE && "Invalid map expression!");
  1321. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1322. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1323. ++EI;
  1324. if (EI == EE)
  1325. return false;
  1326. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1327. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1328. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1329. IsVariableAssociatedWithSection = true;
  1330. // There is nothing more we need to know about this variable.
  1331. return true;
  1332. }
  1333. // Keep looking for more map info.
  1334. return false;
  1335. });
  1336. if (IsVariableUsedInMapClause) {
  1337. // If variable is identified in a map clause it is always captured by
  1338. // reference except if it is a pointer that is dereferenced somehow.
  1339. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1340. } else {
  1341. // By default, all the data that has a scalar type is mapped by copy
  1342. // (except for reduction variables).
  1343. IsByRef =
  1344. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1345. !Ty->isAnyPointerType()) ||
  1346. !Ty->isScalarType() ||
  1347. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1348. DSAStack->hasExplicitDSA(
  1349. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1350. }
  1351. }
  1352. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1353. IsByRef =
  1354. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1355. !Ty->isAnyPointerType()) ||
  1356. !DSAStack->hasExplicitDSA(
  1357. D,
  1358. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1359. Level, /*NotLastprivate=*/true)) &&
  1360. // If the variable is artificial and must be captured by value - try to
  1361. // capture by value.
  1362. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1363. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1364. }
  1365. // When passing data by copy, we need to make sure it fits the uintptr size
  1366. // and alignment, because the runtime library only deals with uintptr types.
  1367. // If it does not fit the uintptr size, we need to pass the data by reference
  1368. // instead.
  1369. if (!IsByRef &&
  1370. (Ctx.getTypeSizeInChars(Ty) >
  1371. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1372. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1373. IsByRef = true;
  1374. }
  1375. return IsByRef;
  1376. }
  1377. unsigned Sema::getOpenMPNestingLevel() const {
  1378. assert(getLangOpts().OpenMP);
  1379. return DSAStack->getNestingLevel();
  1380. }
  1381. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1382. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1383. !DSAStack->isClauseParsingMode()) ||
  1384. DSAStack->hasDirective(
  1385. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1386. SourceLocation) -> bool {
  1387. return isOpenMPTargetExecutionDirective(K);
  1388. },
  1389. false);
  1390. }
  1391. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
  1392. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1393. D = getCanonicalDecl(D);
  1394. // If we are attempting to capture a global variable in a directive with
  1395. // 'target' we return true so that this global is also mapped to the device.
  1396. //
  1397. auto *VD = dyn_cast<VarDecl>(D);
  1398. if (VD && !VD->hasLocalStorage()) {
  1399. if (isInOpenMPDeclareTargetContext() &&
  1400. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1401. // Try to mark variable as declare target if it is used in capturing
  1402. // regions.
  1403. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1404. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1405. return nullptr;
  1406. } else if (isInOpenMPTargetExecutionDirective()) {
  1407. // If the declaration is enclosed in a 'declare target' directive,
  1408. // then it should not be captured.
  1409. //
  1410. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1411. return nullptr;
  1412. return VD;
  1413. }
  1414. }
  1415. // Capture variables captured by reference in lambdas for target-based
  1416. // directives.
  1417. if (VD && !DSAStack->isClauseParsingMode()) {
  1418. if (const auto *RD = VD->getType()
  1419. .getCanonicalType()
  1420. .getNonReferenceType()
  1421. ->getAsCXXRecordDecl()) {
  1422. bool SavedForceCaptureByReferenceInTargetExecutable =
  1423. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1424. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1425. if (RD->isLambda()) {
  1426. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  1427. FieldDecl *ThisCapture;
  1428. RD->getCaptureFields(Captures, ThisCapture);
  1429. for (const LambdaCapture &LC : RD->captures()) {
  1430. if (LC.getCaptureKind() == LCK_ByRef) {
  1431. VarDecl *VD = LC.getCapturedVar();
  1432. DeclContext *VDC = VD->getDeclContext();
  1433. if (!VDC->Encloses(CurContext))
  1434. continue;
  1435. DSAStackTy::DSAVarData DVarPrivate =
  1436. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1437. // Do not capture already captured variables.
  1438. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1439. DVarPrivate.CKind == OMPC_unknown &&
  1440. !DSAStack->checkMappableExprComponentListsForDecl(
  1441. D, /*CurrentRegionOnly=*/true,
  1442. [](OMPClauseMappableExprCommon::
  1443. MappableExprComponentListRef,
  1444. OpenMPClauseKind) { return true; }))
  1445. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1446. } else if (LC.getCaptureKind() == LCK_This) {
  1447. QualType ThisTy = getCurrentThisType();
  1448. if (!ThisTy.isNull() &&
  1449. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  1450. CheckCXXThisCapture(LC.getLocation());
  1451. }
  1452. }
  1453. }
  1454. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1455. SavedForceCaptureByReferenceInTargetExecutable);
  1456. }
  1457. }
  1458. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1459. (!DSAStack->isClauseParsingMode() ||
  1460. DSAStack->getParentDirective() != OMPD_unknown)) {
  1461. auto &&Info = DSAStack->isLoopControlVariable(D);
  1462. if (Info.first ||
  1463. (VD && VD->hasLocalStorage() &&
  1464. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1465. (VD && DSAStack->isForceVarCapturing()))
  1466. return VD ? VD : Info.second;
  1467. DSAStackTy::DSAVarData DVarPrivate =
  1468. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1469. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1470. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1471. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1472. [](OpenMPDirectiveKind) { return true; },
  1473. DSAStack->isClauseParsingMode());
  1474. if (DVarPrivate.CKind != OMPC_unknown)
  1475. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1476. }
  1477. return nullptr;
  1478. }
  1479. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1480. unsigned Level) const {
  1481. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1482. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1483. FunctionScopesIndex -= Regions.size();
  1484. }
  1485. void Sema::startOpenMPLoop() {
  1486. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1487. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1488. DSAStack->loopInit();
  1489. }
  1490. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1491. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1492. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1493. if (DSAStack->getAssociatedLoops() > 0 &&
  1494. !DSAStack->isLoopStarted()) {
  1495. DSAStack->resetPossibleLoopCounter(D);
  1496. DSAStack->loopStart();
  1497. return true;
  1498. }
  1499. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1500. DSAStack->isLoopControlVariable(D).first) &&
  1501. !DSAStack->hasExplicitDSA(
  1502. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1503. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1504. return true;
  1505. }
  1506. return DSAStack->hasExplicitDSA(
  1507. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1508. (DSAStack->isClauseParsingMode() &&
  1509. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1510. // Consider taskgroup reduction descriptor variable a private to avoid
  1511. // possible capture in the region.
  1512. (DSAStack->hasExplicitDirective(
  1513. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1514. Level) &&
  1515. DSAStack->isTaskgroupReductionRef(D, Level));
  1516. }
  1517. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1518. unsigned Level) {
  1519. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1520. D = getCanonicalDecl(D);
  1521. OpenMPClauseKind OMPC = OMPC_unknown;
  1522. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1523. const unsigned NewLevel = I - 1;
  1524. if (DSAStack->hasExplicitDSA(D,
  1525. [&OMPC](const OpenMPClauseKind K) {
  1526. if (isOpenMPPrivate(K)) {
  1527. OMPC = K;
  1528. return true;
  1529. }
  1530. return false;
  1531. },
  1532. NewLevel))
  1533. break;
  1534. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1535. D, NewLevel,
  1536. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1537. OpenMPClauseKind) { return true; })) {
  1538. OMPC = OMPC_map;
  1539. break;
  1540. }
  1541. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1542. NewLevel)) {
  1543. OMPC = OMPC_map;
  1544. if (D->getType()->isScalarType() &&
  1545. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1546. DefaultMapAttributes::DMA_tofrom_scalar)
  1547. OMPC = OMPC_firstprivate;
  1548. break;
  1549. }
  1550. }
  1551. if (OMPC != OMPC_unknown)
  1552. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1553. }
  1554. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1555. unsigned Level) const {
  1556. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1557. // Return true if the current level is no longer enclosed in a target region.
  1558. const auto *VD = dyn_cast<VarDecl>(D);
  1559. return VD && !VD->hasLocalStorage() &&
  1560. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1561. Level);
  1562. }
  1563. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1564. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1565. const DeclarationNameInfo &DirName,
  1566. Scope *CurScope, SourceLocation Loc) {
  1567. DSAStack->push(DKind, DirName, CurScope, Loc);
  1568. PushExpressionEvaluationContext(
  1569. ExpressionEvaluationContext::PotentiallyEvaluated);
  1570. }
  1571. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1572. DSAStack->setClauseParsingMode(K);
  1573. }
  1574. void Sema::EndOpenMPClause() {
  1575. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1576. }
  1577. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1578. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1579. // A variable of class type (or array thereof) that appears in a lastprivate
  1580. // clause requires an accessible, unambiguous default constructor for the
  1581. // class type, unless the list item is also specified in a firstprivate
  1582. // clause.
  1583. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1584. for (OMPClause *C : D->clauses()) {
  1585. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1586. SmallVector<Expr *, 8> PrivateCopies;
  1587. for (Expr *DE : Clause->varlists()) {
  1588. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1589. PrivateCopies.push_back(nullptr);
  1590. continue;
  1591. }
  1592. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1593. auto *VD = cast<VarDecl>(DRE->getDecl());
  1594. QualType Type = VD->getType().getNonReferenceType();
  1595. const DSAStackTy::DSAVarData DVar =
  1596. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1597. if (DVar.CKind == OMPC_lastprivate) {
  1598. // Generate helper private variable and initialize it with the
  1599. // default value. The address of the original variable is replaced
  1600. // by the address of the new private variable in CodeGen. This new
  1601. // variable is not added to IdResolver, so the code in the OpenMP
  1602. // region uses original variable for proper diagnostics.
  1603. VarDecl *VDPrivate = buildVarDecl(
  1604. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1605. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1606. ActOnUninitializedDecl(VDPrivate);
  1607. if (VDPrivate->isInvalidDecl())
  1608. continue;
  1609. PrivateCopies.push_back(buildDeclRefExpr(
  1610. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1611. } else {
  1612. // The variable is also a firstprivate, so initialization sequence
  1613. // for private copy is generated already.
  1614. PrivateCopies.push_back(nullptr);
  1615. }
  1616. }
  1617. // Set initializers to private copies if no errors were found.
  1618. if (PrivateCopies.size() == Clause->varlist_size())
  1619. Clause->setPrivateCopies(PrivateCopies);
  1620. }
  1621. }
  1622. }
  1623. DSAStack->pop();
  1624. DiscardCleanupsInEvaluationContext();
  1625. PopExpressionEvaluationContext();
  1626. }
  1627. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1628. Expr *NumIterations, Sema &SemaRef,
  1629. Scope *S, DSAStackTy *Stack);
  1630. namespace {
  1631. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1632. private:
  1633. Sema &SemaRef;
  1634. public:
  1635. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1636. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1637. NamedDecl *ND = Candidate.getCorrectionDecl();
  1638. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1639. return VD->hasGlobalStorage() &&
  1640. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1641. SemaRef.getCurScope());
  1642. }
  1643. return false;
  1644. }
  1645. };
  1646. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1647. private:
  1648. Sema &SemaRef;
  1649. public:
  1650. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1651. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1652. NamedDecl *ND = Candidate.getCorrectionDecl();
  1653. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1654. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1655. SemaRef.getCurScope());
  1656. }
  1657. return false;
  1658. }
  1659. };
  1660. } // namespace
  1661. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1662. CXXScopeSpec &ScopeSpec,
  1663. const DeclarationNameInfo &Id) {
  1664. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1665. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1666. if (Lookup.isAmbiguous())
  1667. return ExprError();
  1668. VarDecl *VD;
  1669. if (!Lookup.isSingleResult()) {
  1670. if (TypoCorrection Corrected = CorrectTypo(
  1671. Id, LookupOrdinaryName, CurScope, nullptr,
  1672. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1673. diagnoseTypo(Corrected,
  1674. PDiag(Lookup.empty()
  1675. ? diag::err_undeclared_var_use_suggest
  1676. : diag::err_omp_expected_var_arg_suggest)
  1677. << Id.getName());
  1678. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1679. } else {
  1680. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1681. : diag::err_omp_expected_var_arg)
  1682. << Id.getName();
  1683. return ExprError();
  1684. }
  1685. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1686. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1687. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1688. return ExprError();
  1689. }
  1690. Lookup.suppressDiagnostics();
  1691. // OpenMP [2.9.2, Syntax, C/C++]
  1692. // Variables must be file-scope, namespace-scope, or static block-scope.
  1693. if (!VD->hasGlobalStorage()) {
  1694. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1695. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1696. bool IsDecl =
  1697. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1698. Diag(VD->getLocation(),
  1699. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1700. << VD;
  1701. return ExprError();
  1702. }
  1703. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1704. NamedDecl *ND = CanonicalVD;
  1705. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1706. // A threadprivate directive for file-scope variables must appear outside
  1707. // any definition or declaration.
  1708. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1709. !getCurLexicalContext()->isTranslationUnit()) {
  1710. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1711. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1712. bool IsDecl =
  1713. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1714. Diag(VD->getLocation(),
  1715. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1716. << VD;
  1717. return ExprError();
  1718. }
  1719. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1720. // A threadprivate directive for static class member variables must appear
  1721. // in the class definition, in the same scope in which the member
  1722. // variables are declared.
  1723. if (CanonicalVD->isStaticDataMember() &&
  1724. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1725. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1726. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1727. bool IsDecl =
  1728. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1729. Diag(VD->getLocation(),
  1730. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1731. << VD;
  1732. return ExprError();
  1733. }
  1734. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1735. // A threadprivate directive for namespace-scope variables must appear
  1736. // outside any definition or declaration other than the namespace
  1737. // definition itself.
  1738. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1739. (!getCurLexicalContext()->isFileContext() ||
  1740. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1741. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1742. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1743. bool IsDecl =
  1744. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1745. Diag(VD->getLocation(),
  1746. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1747. << VD;
  1748. return ExprError();
  1749. }
  1750. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1751. // A threadprivate directive for static block-scope variables must appear
  1752. // in the scope of the variable and not in a nested scope.
  1753. if (CanonicalVD->isStaticLocal() && CurScope &&
  1754. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1755. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1756. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1757. bool IsDecl =
  1758. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1759. Diag(VD->getLocation(),
  1760. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1761. << VD;
  1762. return ExprError();
  1763. }
  1764. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1765. // A threadprivate directive must lexically precede all references to any
  1766. // of the variables in its list.
  1767. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1768. Diag(Id.getLoc(), diag::err_omp_var_used)
  1769. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1770. return ExprError();
  1771. }
  1772. QualType ExprType = VD->getType().getNonReferenceType();
  1773. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1774. SourceLocation(), VD,
  1775. /*RefersToEnclosingVariableOrCapture=*/false,
  1776. Id.getLoc(), ExprType, VK_LValue);
  1777. }
  1778. Sema::DeclGroupPtrTy
  1779. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1780. ArrayRef<Expr *> VarList) {
  1781. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1782. CurContext->addDecl(D);
  1783. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1784. }
  1785. return nullptr;
  1786. }
  1787. namespace {
  1788. class LocalVarRefChecker final
  1789. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1790. Sema &SemaRef;
  1791. public:
  1792. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1793. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1794. if (VD->hasLocalStorage()) {
  1795. SemaRef.Diag(E->getBeginLoc(),
  1796. diag::err_omp_local_var_in_threadprivate_init)
  1797. << E->getSourceRange();
  1798. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1799. << VD << VD->getSourceRange();
  1800. return true;
  1801. }
  1802. }
  1803. return false;
  1804. }
  1805. bool VisitStmt(const Stmt *S) {
  1806. for (const Stmt *Child : S->children()) {
  1807. if (Child && Visit(Child))
  1808. return true;
  1809. }
  1810. return false;
  1811. }
  1812. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1813. };
  1814. } // namespace
  1815. OMPThreadPrivateDecl *
  1816. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1817. SmallVector<Expr *, 8> Vars;
  1818. for (Expr *RefExpr : VarList) {
  1819. auto *DE = cast<DeclRefExpr>(RefExpr);
  1820. auto *VD = cast<VarDecl>(DE->getDecl());
  1821. SourceLocation ILoc = DE->getExprLoc();
  1822. // Mark variable as used.
  1823. VD->setReferenced();
  1824. VD->markUsed(Context);
  1825. QualType QType = VD->getType();
  1826. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1827. // It will be analyzed later.
  1828. Vars.push_back(DE);
  1829. continue;
  1830. }
  1831. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1832. // A threadprivate variable must not have an incomplete type.
  1833. if (RequireCompleteType(ILoc, VD->getType(),
  1834. diag::err_omp_threadprivate_incomplete_type)) {
  1835. continue;
  1836. }
  1837. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1838. // A threadprivate variable must not have a reference type.
  1839. if (VD->getType()->isReferenceType()) {
  1840. Diag(ILoc, diag::err_omp_ref_type_arg)
  1841. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1842. bool IsDecl =
  1843. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1844. Diag(VD->getLocation(),
  1845. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1846. << VD;
  1847. continue;
  1848. }
  1849. // Check if this is a TLS variable. If TLS is not being supported, produce
  1850. // the corresponding diagnostic.
  1851. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1852. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1853. getLangOpts().OpenMPUseTLS &&
  1854. getASTContext().getTargetInfo().isTLSSupported())) ||
  1855. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1856. !VD->isLocalVarDecl())) {
  1857. Diag(ILoc, diag::err_omp_var_thread_local)
  1858. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1859. bool IsDecl =
  1860. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1861. Diag(VD->getLocation(),
  1862. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1863. << VD;
  1864. continue;
  1865. }
  1866. // Check if initial value of threadprivate variable reference variable with
  1867. // local storage (it is not supported by runtime).
  1868. if (const Expr *Init = VD->getAnyInitializer()) {
  1869. LocalVarRefChecker Checker(*this);
  1870. if (Checker.Visit(Init))
  1871. continue;
  1872. }
  1873. Vars.push_back(RefExpr);
  1874. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1875. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1876. Context, SourceRange(Loc, Loc)));
  1877. if (ASTMutationListener *ML = Context.getASTMutationListener())
  1878. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1879. }
  1880. OMPThreadPrivateDecl *D = nullptr;
  1881. if (!Vars.empty()) {
  1882. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1883. Vars);
  1884. D->setAccess(AS_public);
  1885. }
  1886. return D;
  1887. }
  1888. Sema::DeclGroupPtrTy
  1889. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  1890. ArrayRef<OMPClause *> ClauseList) {
  1891. OMPRequiresDecl *D = nullptr;
  1892. if (!CurContext->isFileContext()) {
  1893. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  1894. } else {
  1895. D = CheckOMPRequiresDecl(Loc, ClauseList);
  1896. if (D) {
  1897. CurContext->addDecl(D);
  1898. DSAStack->addRequiresDecl(D);
  1899. }
  1900. }
  1901. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1902. }
  1903. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  1904. ArrayRef<OMPClause *> ClauseList) {
  1905. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  1906. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  1907. ClauseList);
  1908. return nullptr;
  1909. }
  1910. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  1911. const ValueDecl *D,
  1912. const DSAStackTy::DSAVarData &DVar,
  1913. bool IsLoopIterVar = false) {
  1914. if (DVar.RefExpr) {
  1915. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1916. << getOpenMPClauseName(DVar.CKind);
  1917. return;
  1918. }
  1919. enum {
  1920. PDSA_StaticMemberShared,
  1921. PDSA_StaticLocalVarShared,
  1922. PDSA_LoopIterVarPrivate,
  1923. PDSA_LoopIterVarLinear,
  1924. PDSA_LoopIterVarLastprivate,
  1925. PDSA_ConstVarShared,
  1926. PDSA_GlobalVarShared,
  1927. PDSA_TaskVarFirstprivate,
  1928. PDSA_LocalVarPrivate,
  1929. PDSA_Implicit
  1930. } Reason = PDSA_Implicit;
  1931. bool ReportHint = false;
  1932. auto ReportLoc = D->getLocation();
  1933. auto *VD = dyn_cast<VarDecl>(D);
  1934. if (IsLoopIterVar) {
  1935. if (DVar.CKind == OMPC_private)
  1936. Reason = PDSA_LoopIterVarPrivate;
  1937. else if (DVar.CKind == OMPC_lastprivate)
  1938. Reason = PDSA_LoopIterVarLastprivate;
  1939. else
  1940. Reason = PDSA_LoopIterVarLinear;
  1941. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1942. DVar.CKind == OMPC_firstprivate) {
  1943. Reason = PDSA_TaskVarFirstprivate;
  1944. ReportLoc = DVar.ImplicitDSALoc;
  1945. } else if (VD && VD->isStaticLocal())
  1946. Reason = PDSA_StaticLocalVarShared;
  1947. else if (VD && VD->isStaticDataMember())
  1948. Reason = PDSA_StaticMemberShared;
  1949. else if (VD && VD->isFileVarDecl())
  1950. Reason = PDSA_GlobalVarShared;
  1951. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1952. Reason = PDSA_ConstVarShared;
  1953. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1954. ReportHint = true;
  1955. Reason = PDSA_LocalVarPrivate;
  1956. }
  1957. if (Reason != PDSA_Implicit) {
  1958. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1959. << Reason << ReportHint
  1960. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1961. } else if (DVar.ImplicitDSALoc.isValid()) {
  1962. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1963. << getOpenMPClauseName(DVar.CKind);
  1964. }
  1965. }
  1966. namespace {
  1967. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  1968. DSAStackTy *Stack;
  1969. Sema &SemaRef;
  1970. bool ErrorFound = false;
  1971. CapturedStmt *CS = nullptr;
  1972. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  1973. llvm::SmallVector<Expr *, 4> ImplicitMap;
  1974. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  1975. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  1976. void VisitSubCaptures(OMPExecutableDirective *S) {
  1977. // Check implicitly captured variables.
  1978. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  1979. return;
  1980. for (const CapturedStmt::Capture &Cap :
  1981. S->getInnermostCapturedStmt()->captures()) {
  1982. if (!Cap.capturesVariable())
  1983. continue;
  1984. VarDecl *VD = Cap.getCapturedVar();
  1985. // Do not try to map the variable if it or its sub-component was mapped
  1986. // already.
  1987. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  1988. Stack->checkMappableExprComponentListsForDecl(
  1989. VD, /*CurrentRegionOnly=*/true,
  1990. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1991. OpenMPClauseKind) { return true; }))
  1992. continue;
  1993. DeclRefExpr *DRE = buildDeclRefExpr(
  1994. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  1995. Cap.getLocation(), /*RefersToCapture=*/true);
  1996. Visit(DRE);
  1997. }
  1998. }
  1999. public:
  2000. void VisitDeclRefExpr(DeclRefExpr *E) {
  2001. if (E->isTypeDependent() || E->isValueDependent() ||
  2002. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2003. return;
  2004. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2005. VD = VD->getCanonicalDecl();
  2006. // Skip internally declared variables.
  2007. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  2008. return;
  2009. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2010. // Check if the variable has explicit DSA set and stop analysis if it so.
  2011. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2012. return;
  2013. // Skip internally declared static variables.
  2014. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2015. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2016. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  2017. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2018. return;
  2019. SourceLocation ELoc = E->getExprLoc();
  2020. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2021. // The default(none) clause requires that each variable that is referenced
  2022. // in the construct, and does not have a predetermined data-sharing
  2023. // attribute, must have its data-sharing attribute explicitly determined
  2024. // by being listed in a data-sharing attribute clause.
  2025. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2026. isParallelOrTaskRegion(DKind) &&
  2027. VarsWithInheritedDSA.count(VD) == 0) {
  2028. VarsWithInheritedDSA[VD] = E;
  2029. return;
  2030. }
  2031. if (isOpenMPTargetExecutionDirective(DKind) &&
  2032. !Stack->isLoopControlVariable(VD).first) {
  2033. if (!Stack->checkMappableExprComponentListsForDecl(
  2034. VD, /*CurrentRegionOnly=*/true,
  2035. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2036. StackComponents,
  2037. OpenMPClauseKind) {
  2038. // Variable is used if it has been marked as an array, array
  2039. // section or the variable iself.
  2040. return StackComponents.size() == 1 ||
  2041. std::all_of(
  2042. std::next(StackComponents.rbegin()),
  2043. StackComponents.rend(),
  2044. [](const OMPClauseMappableExprCommon::
  2045. MappableComponent &MC) {
  2046. return MC.getAssociatedDeclaration() ==
  2047. nullptr &&
  2048. (isa<OMPArraySectionExpr>(
  2049. MC.getAssociatedExpression()) ||
  2050. isa<ArraySubscriptExpr>(
  2051. MC.getAssociatedExpression()));
  2052. });
  2053. })) {
  2054. bool IsFirstprivate = false;
  2055. // By default lambdas are captured as firstprivates.
  2056. if (const auto *RD =
  2057. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2058. IsFirstprivate = RD->isLambda();
  2059. IsFirstprivate =
  2060. IsFirstprivate ||
  2061. (VD->getType().getNonReferenceType()->isScalarType() &&
  2062. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2063. if (IsFirstprivate)
  2064. ImplicitFirstprivate.emplace_back(E);
  2065. else
  2066. ImplicitMap.emplace_back(E);
  2067. return;
  2068. }
  2069. }
  2070. // OpenMP [2.9.3.6, Restrictions, p.2]
  2071. // A list item that appears in a reduction clause of the innermost
  2072. // enclosing worksharing or parallel construct may not be accessed in an
  2073. // explicit task.
  2074. DVar = Stack->hasInnermostDSA(
  2075. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2076. [](OpenMPDirectiveKind K) {
  2077. return isOpenMPParallelDirective(K) ||
  2078. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2079. },
  2080. /*FromParent=*/true);
  2081. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2082. ErrorFound = true;
  2083. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2084. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2085. return;
  2086. }
  2087. // Define implicit data-sharing attributes for task.
  2088. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2089. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2090. !Stack->isLoopControlVariable(VD).first)
  2091. ImplicitFirstprivate.push_back(E);
  2092. }
  2093. }
  2094. void VisitMemberExpr(MemberExpr *E) {
  2095. if (E->isTypeDependent() || E->isValueDependent() ||
  2096. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2097. return;
  2098. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2099. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2100. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2101. if (!FD)
  2102. return;
  2103. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2104. // Check if the variable has explicit DSA set and stop analysis if it
  2105. // so.
  2106. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2107. return;
  2108. if (isOpenMPTargetExecutionDirective(DKind) &&
  2109. !Stack->isLoopControlVariable(FD).first &&
  2110. !Stack->checkMappableExprComponentListsForDecl(
  2111. FD, /*CurrentRegionOnly=*/true,
  2112. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2113. StackComponents,
  2114. OpenMPClauseKind) {
  2115. return isa<CXXThisExpr>(
  2116. cast<MemberExpr>(
  2117. StackComponents.back().getAssociatedExpression())
  2118. ->getBase()
  2119. ->IgnoreParens());
  2120. })) {
  2121. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2122. // A bit-field cannot appear in a map clause.
  2123. //
  2124. if (FD->isBitField())
  2125. return;
  2126. ImplicitMap.emplace_back(E);
  2127. return;
  2128. }
  2129. SourceLocation ELoc = E->getExprLoc();
  2130. // OpenMP [2.9.3.6, Restrictions, p.2]
  2131. // A list item that appears in a reduction clause of the innermost
  2132. // enclosing worksharing or parallel construct may not be accessed in
  2133. // an explicit task.
  2134. DVar = Stack->hasInnermostDSA(
  2135. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2136. [](OpenMPDirectiveKind K) {
  2137. return isOpenMPParallelDirective(K) ||
  2138. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2139. },
  2140. /*FromParent=*/true);
  2141. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2142. ErrorFound = true;
  2143. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2144. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2145. return;
  2146. }
  2147. // Define implicit data-sharing attributes for task.
  2148. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2149. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2150. !Stack->isLoopControlVariable(FD).first) {
  2151. // Check if there is a captured expression for the current field in the
  2152. // region. Do not mark it as firstprivate unless there is no captured
  2153. // expression.
  2154. // TODO: try to make it firstprivate.
  2155. if (DVar.CKind != OMPC_unknown)
  2156. ImplicitFirstprivate.push_back(E);
  2157. }
  2158. return;
  2159. }
  2160. if (isOpenMPTargetExecutionDirective(DKind)) {
  2161. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2162. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2163. /*NoDiagnose=*/true))
  2164. return;
  2165. const auto *VD = cast<ValueDecl>(
  2166. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2167. if (!Stack->checkMappableExprComponentListsForDecl(
  2168. VD, /*CurrentRegionOnly=*/true,
  2169. [&CurComponents](
  2170. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2171. StackComponents,
  2172. OpenMPClauseKind) {
  2173. auto CCI = CurComponents.rbegin();
  2174. auto CCE = CurComponents.rend();
  2175. for (const auto &SC : llvm::reverse(StackComponents)) {
  2176. // Do both expressions have the same kind?
  2177. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2178. SC.getAssociatedExpression()->getStmtClass())
  2179. if (!(isa<OMPArraySectionExpr>(
  2180. SC.getAssociatedExpression()) &&
  2181. isa<ArraySubscriptExpr>(
  2182. CCI->getAssociatedExpression())))
  2183. return false;
  2184. const Decl *CCD = CCI->getAssociatedDeclaration();
  2185. const Decl *SCD = SC.getAssociatedDeclaration();
  2186. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2187. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2188. if (SCD != CCD)
  2189. return false;
  2190. std::advance(CCI, 1);
  2191. if (CCI == CCE)
  2192. break;
  2193. }
  2194. return true;
  2195. })) {
  2196. Visit(E->getBase());
  2197. }
  2198. } else {
  2199. Visit(E->getBase());
  2200. }
  2201. }
  2202. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2203. for (OMPClause *C : S->clauses()) {
  2204. // Skip analysis of arguments of implicitly defined firstprivate clause
  2205. // for task|target directives.
  2206. // Skip analysis of arguments of implicitly defined map clause for target
  2207. // directives.
  2208. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2209. C->isImplicit())) {
  2210. for (Stmt *CC : C->children()) {
  2211. if (CC)
  2212. Visit(CC);
  2213. }
  2214. }
  2215. }
  2216. // Check implicitly captured variables.
  2217. VisitSubCaptures(S);
  2218. }
  2219. void VisitStmt(Stmt *S) {
  2220. for (Stmt *C : S->children()) {
  2221. if (C) {
  2222. if (auto *OED = dyn_cast<OMPExecutableDirective>(C)) {
  2223. // Check implicitly captured variables in the task-based directives to
  2224. // check if they must be firstprivatized.
  2225. VisitSubCaptures(OED);
  2226. } else {
  2227. Visit(C);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. bool isErrorFound() const { return ErrorFound; }
  2233. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2234. return ImplicitFirstprivate;
  2235. }
  2236. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2237. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2238. return VarsWithInheritedDSA;
  2239. }
  2240. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2241. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  2242. };
  2243. } // namespace
  2244. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2245. switch (DKind) {
  2246. case OMPD_parallel:
  2247. case OMPD_parallel_for:
  2248. case OMPD_parallel_for_simd:
  2249. case OMPD_parallel_sections:
  2250. case OMPD_teams:
  2251. case OMPD_teams_distribute:
  2252. case OMPD_teams_distribute_simd: {
  2253. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2254. QualType KmpInt32PtrTy =
  2255. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2256. Sema::CapturedParamNameType Params[] = {
  2257. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2258. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2259. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2260. };
  2261. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2262. Params);
  2263. break;
  2264. }
  2265. case OMPD_target_teams:
  2266. case OMPD_target_parallel:
  2267. case OMPD_target_parallel_for:
  2268. case OMPD_target_parallel_for_simd:
  2269. case OMPD_target_teams_distribute:
  2270. case OMPD_target_teams_distribute_simd: {
  2271. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2272. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2273. QualType KmpInt32PtrTy =
  2274. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2275. QualType Args[] = {VoidPtrTy};
  2276. FunctionProtoType::ExtProtoInfo EPI;
  2277. EPI.Variadic = true;
  2278. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2279. Sema::CapturedParamNameType Params[] = {
  2280. std::make_pair(".global_tid.", KmpInt32Ty),
  2281. std::make_pair(".part_id.", KmpInt32PtrTy),
  2282. std::make_pair(".privates.", VoidPtrTy),
  2283. std::make_pair(
  2284. ".copy_fn.",
  2285. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2286. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2287. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2288. };
  2289. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2290. Params);
  2291. // Mark this captured region as inlined, because we don't use outlined
  2292. // function directly.
  2293. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2294. AlwaysInlineAttr::CreateImplicit(
  2295. Context, AlwaysInlineAttr::Keyword_forceinline));
  2296. Sema::CapturedParamNameType ParamsTarget[] = {
  2297. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2298. };
  2299. // Start a captured region for 'target' with no implicit parameters.
  2300. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2301. ParamsTarget);
  2302. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2303. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2304. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2305. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2306. };
  2307. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2308. // the same implicit parameters.
  2309. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2310. ParamsTeamsOrParallel);
  2311. break;
  2312. }
  2313. case OMPD_target:
  2314. case OMPD_target_simd: {
  2315. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2316. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2317. QualType KmpInt32PtrTy =
  2318. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2319. QualType Args[] = {VoidPtrTy};
  2320. FunctionProtoType::ExtProtoInfo EPI;
  2321. EPI.Variadic = true;
  2322. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2323. Sema::CapturedParamNameType Params[] = {
  2324. std::make_pair(".global_tid.", KmpInt32Ty),
  2325. std::make_pair(".part_id.", KmpInt32PtrTy),
  2326. std::make_pair(".privates.", VoidPtrTy),
  2327. std::make_pair(
  2328. ".copy_fn.",
  2329. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2330. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2331. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2332. };
  2333. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2334. Params);
  2335. // Mark this captured region as inlined, because we don't use outlined
  2336. // function directly.
  2337. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2338. AlwaysInlineAttr::CreateImplicit(
  2339. Context, AlwaysInlineAttr::Keyword_forceinline));
  2340. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2341. std::make_pair(StringRef(), QualType()));
  2342. break;
  2343. }
  2344. case OMPD_simd:
  2345. case OMPD_for:
  2346. case OMPD_for_simd:
  2347. case OMPD_sections:
  2348. case OMPD_section:
  2349. case OMPD_single:
  2350. case OMPD_master:
  2351. case OMPD_critical:
  2352. case OMPD_taskgroup:
  2353. case OMPD_distribute:
  2354. case OMPD_distribute_simd:
  2355. case OMPD_ordered:
  2356. case OMPD_atomic:
  2357. case OMPD_target_data: {
  2358. Sema::CapturedParamNameType Params[] = {
  2359. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2360. };
  2361. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2362. Params);
  2363. break;
  2364. }
  2365. case OMPD_task: {
  2366. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2367. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2368. QualType KmpInt32PtrTy =
  2369. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2370. QualType Args[] = {VoidPtrTy};
  2371. FunctionProtoType::ExtProtoInfo EPI;
  2372. EPI.Variadic = true;
  2373. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2374. Sema::CapturedParamNameType Params[] = {
  2375. std::make_pair(".global_tid.", KmpInt32Ty),
  2376. std::make_pair(".part_id.", KmpInt32PtrTy),
  2377. std::make_pair(".privates.", VoidPtrTy),
  2378. std::make_pair(
  2379. ".copy_fn.",
  2380. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2381. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2382. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2383. };
  2384. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2385. Params);
  2386. // Mark this captured region as inlined, because we don't use outlined
  2387. // function directly.
  2388. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2389. AlwaysInlineAttr::CreateImplicit(
  2390. Context, AlwaysInlineAttr::Keyword_forceinline));
  2391. break;
  2392. }
  2393. case OMPD_taskloop:
  2394. case OMPD_taskloop_simd: {
  2395. QualType KmpInt32Ty =
  2396. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2397. .withConst();
  2398. QualType KmpUInt64Ty =
  2399. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2400. .withConst();
  2401. QualType KmpInt64Ty =
  2402. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2403. .withConst();
  2404. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2405. QualType KmpInt32PtrTy =
  2406. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2407. QualType Args[] = {VoidPtrTy};
  2408. FunctionProtoType::ExtProtoInfo EPI;
  2409. EPI.Variadic = true;
  2410. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2411. Sema::CapturedParamNameType Params[] = {
  2412. std::make_pair(".global_tid.", KmpInt32Ty),
  2413. std::make_pair(".part_id.", KmpInt32PtrTy),
  2414. std::make_pair(".privates.", VoidPtrTy),
  2415. std::make_pair(
  2416. ".copy_fn.",
  2417. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2418. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2419. std::make_pair(".lb.", KmpUInt64Ty),
  2420. std::make_pair(".ub.", KmpUInt64Ty),
  2421. std::make_pair(".st.", KmpInt64Ty),
  2422. std::make_pair(".liter.", KmpInt32Ty),
  2423. std::make_pair(".reductions.", VoidPtrTy),
  2424. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2425. };
  2426. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2427. Params);
  2428. // Mark this captured region as inlined, because we don't use outlined
  2429. // function directly.
  2430. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2431. AlwaysInlineAttr::CreateImplicit(
  2432. Context, AlwaysInlineAttr::Keyword_forceinline));
  2433. break;
  2434. }
  2435. case OMPD_distribute_parallel_for_simd:
  2436. case OMPD_distribute_parallel_for: {
  2437. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2438. QualType KmpInt32PtrTy =
  2439. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2440. Sema::CapturedParamNameType Params[] = {
  2441. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2442. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2443. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2444. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2445. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2446. };
  2447. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2448. Params);
  2449. break;
  2450. }
  2451. case OMPD_target_teams_distribute_parallel_for:
  2452. case OMPD_target_teams_distribute_parallel_for_simd: {
  2453. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2454. QualType KmpInt32PtrTy =
  2455. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2456. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2457. QualType Args[] = {VoidPtrTy};
  2458. FunctionProtoType::ExtProtoInfo EPI;
  2459. EPI.Variadic = true;
  2460. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2461. Sema::CapturedParamNameType Params[] = {
  2462. std::make_pair(".global_tid.", KmpInt32Ty),
  2463. std::make_pair(".part_id.", KmpInt32PtrTy),
  2464. std::make_pair(".privates.", VoidPtrTy),
  2465. std::make_pair(
  2466. ".copy_fn.",
  2467. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2468. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2469. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2470. };
  2471. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2472. Params);
  2473. // Mark this captured region as inlined, because we don't use outlined
  2474. // function directly.
  2475. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2476. AlwaysInlineAttr::CreateImplicit(
  2477. Context, AlwaysInlineAttr::Keyword_forceinline));
  2478. Sema::CapturedParamNameType ParamsTarget[] = {
  2479. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2480. };
  2481. // Start a captured region for 'target' with no implicit parameters.
  2482. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2483. ParamsTarget);
  2484. Sema::CapturedParamNameType ParamsTeams[] = {
  2485. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2486. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2487. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2488. };
  2489. // Start a captured region for 'target' with no implicit parameters.
  2490. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2491. ParamsTeams);
  2492. Sema::CapturedParamNameType ParamsParallel[] = {
  2493. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2494. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2495. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2496. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2497. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2498. };
  2499. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2500. // the same implicit parameters.
  2501. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2502. ParamsParallel);
  2503. break;
  2504. }
  2505. case OMPD_teams_distribute_parallel_for:
  2506. case OMPD_teams_distribute_parallel_for_simd: {
  2507. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2508. QualType KmpInt32PtrTy =
  2509. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2510. Sema::CapturedParamNameType ParamsTeams[] = {
  2511. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2512. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2513. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2514. };
  2515. // Start a captured region for 'target' with no implicit parameters.
  2516. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2517. ParamsTeams);
  2518. Sema::CapturedParamNameType ParamsParallel[] = {
  2519. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2520. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2521. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2522. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2523. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2524. };
  2525. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2526. // the same implicit parameters.
  2527. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2528. ParamsParallel);
  2529. break;
  2530. }
  2531. case OMPD_target_update:
  2532. case OMPD_target_enter_data:
  2533. case OMPD_target_exit_data: {
  2534. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2535. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2536. QualType KmpInt32PtrTy =
  2537. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2538. QualType Args[] = {VoidPtrTy};
  2539. FunctionProtoType::ExtProtoInfo EPI;
  2540. EPI.Variadic = true;
  2541. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2542. Sema::CapturedParamNameType Params[] = {
  2543. std::make_pair(".global_tid.", KmpInt32Ty),
  2544. std::make_pair(".part_id.", KmpInt32PtrTy),
  2545. std::make_pair(".privates.", VoidPtrTy),
  2546. std::make_pair(
  2547. ".copy_fn.",
  2548. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2549. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2550. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2551. };
  2552. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2553. Params);
  2554. // Mark this captured region as inlined, because we don't use outlined
  2555. // function directly.
  2556. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2557. AlwaysInlineAttr::CreateImplicit(
  2558. Context, AlwaysInlineAttr::Keyword_forceinline));
  2559. break;
  2560. }
  2561. case OMPD_threadprivate:
  2562. case OMPD_taskyield:
  2563. case OMPD_barrier:
  2564. case OMPD_taskwait:
  2565. case OMPD_cancellation_point:
  2566. case OMPD_cancel:
  2567. case OMPD_flush:
  2568. case OMPD_declare_reduction:
  2569. case OMPD_declare_simd:
  2570. case OMPD_declare_target:
  2571. case OMPD_end_declare_target:
  2572. case OMPD_requires:
  2573. llvm_unreachable("OpenMP Directive is not allowed");
  2574. case OMPD_unknown:
  2575. llvm_unreachable("Unknown OpenMP directive");
  2576. }
  2577. }
  2578. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2579. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2580. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2581. return CaptureRegions.size();
  2582. }
  2583. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2584. Expr *CaptureExpr, bool WithInit,
  2585. bool AsExpression) {
  2586. assert(CaptureExpr);
  2587. ASTContext &C = S.getASTContext();
  2588. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2589. QualType Ty = Init->getType();
  2590. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2591. if (S.getLangOpts().CPlusPlus) {
  2592. Ty = C.getLValueReferenceType(Ty);
  2593. } else {
  2594. Ty = C.getPointerType(Ty);
  2595. ExprResult Res =
  2596. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2597. if (!Res.isUsable())
  2598. return nullptr;
  2599. Init = Res.get();
  2600. }
  2601. WithInit = true;
  2602. }
  2603. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2604. CaptureExpr->getBeginLoc());
  2605. if (!WithInit)
  2606. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2607. S.CurContext->addHiddenDecl(CED);
  2608. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2609. return CED;
  2610. }
  2611. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2612. bool WithInit) {
  2613. OMPCapturedExprDecl *CD;
  2614. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2615. CD = cast<OMPCapturedExprDecl>(VD);
  2616. else
  2617. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2618. /*AsExpression=*/false);
  2619. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2620. CaptureExpr->getExprLoc());
  2621. }
  2622. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2623. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2624. if (!Ref) {
  2625. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2626. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2627. /*WithInit=*/true, /*AsExpression=*/true);
  2628. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2629. CaptureExpr->getExprLoc());
  2630. }
  2631. ExprResult Res = Ref;
  2632. if (!S.getLangOpts().CPlusPlus &&
  2633. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2634. Ref->getType()->isPointerType()) {
  2635. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2636. if (!Res.isUsable())
  2637. return ExprError();
  2638. }
  2639. return S.DefaultLvalueConversion(Res.get());
  2640. }
  2641. namespace {
  2642. // OpenMP directives parsed in this section are represented as a
  2643. // CapturedStatement with an associated statement. If a syntax error
  2644. // is detected during the parsing of the associated statement, the
  2645. // compiler must abort processing and close the CapturedStatement.
  2646. //
  2647. // Combined directives such as 'target parallel' have more than one
  2648. // nested CapturedStatements. This RAII ensures that we unwind out
  2649. // of all the nested CapturedStatements when an error is found.
  2650. class CaptureRegionUnwinderRAII {
  2651. private:
  2652. Sema &S;
  2653. bool &ErrorFound;
  2654. OpenMPDirectiveKind DKind = OMPD_unknown;
  2655. public:
  2656. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2657. OpenMPDirectiveKind DKind)
  2658. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2659. ~CaptureRegionUnwinderRAII() {
  2660. if (ErrorFound) {
  2661. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2662. while (--ThisCaptureLevel >= 0)
  2663. S.ActOnCapturedRegionError();
  2664. }
  2665. }
  2666. };
  2667. } // namespace
  2668. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2669. ArrayRef<OMPClause *> Clauses) {
  2670. bool ErrorFound = false;
  2671. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2672. *this, ErrorFound, DSAStack->getCurrentDirective());
  2673. if (!S.isUsable()) {
  2674. ErrorFound = true;
  2675. return StmtError();
  2676. }
  2677. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2678. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2679. OMPOrderedClause *OC = nullptr;
  2680. OMPScheduleClause *SC = nullptr;
  2681. SmallVector<const OMPLinearClause *, 4> LCs;
  2682. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  2683. // This is required for proper codegen.
  2684. for (OMPClause *Clause : Clauses) {
  2685. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2686. Clause->getClauseKind() == OMPC_in_reduction) {
  2687. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2688. // with the corresponding in_reduction items.
  2689. auto *IRC = cast<OMPInReductionClause>(Clause);
  2690. for (Expr *E : IRC->taskgroup_descriptors())
  2691. if (E)
  2692. MarkDeclarationsReferencedInExpr(E);
  2693. }
  2694. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2695. Clause->getClauseKind() == OMPC_copyprivate ||
  2696. (getLangOpts().OpenMPUseTLS &&
  2697. getASTContext().getTargetInfo().isTLSSupported() &&
  2698. Clause->getClauseKind() == OMPC_copyin)) {
  2699. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2700. // Mark all variables in private list clauses as used in inner region.
  2701. for (Stmt *VarRef : Clause->children()) {
  2702. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2703. MarkDeclarationsReferencedInExpr(E);
  2704. }
  2705. }
  2706. DSAStack->setForceVarCapturing(/*V=*/false);
  2707. } else if (CaptureRegions.size() > 1 ||
  2708. CaptureRegions.back() != OMPD_unknown) {
  2709. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2710. PICs.push_back(C);
  2711. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2712. if (Expr *E = C->getPostUpdateExpr())
  2713. MarkDeclarationsReferencedInExpr(E);
  2714. }
  2715. }
  2716. if (Clause->getClauseKind() == OMPC_schedule)
  2717. SC = cast<OMPScheduleClause>(Clause);
  2718. else if (Clause->getClauseKind() == OMPC_ordered)
  2719. OC = cast<OMPOrderedClause>(Clause);
  2720. else if (Clause->getClauseKind() == OMPC_linear)
  2721. LCs.push_back(cast<OMPLinearClause>(Clause));
  2722. }
  2723. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2724. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2725. // specified.
  2726. if (SC &&
  2727. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2728. SC->getSecondScheduleModifier() ==
  2729. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2730. OC) {
  2731. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2732. ? SC->getFirstScheduleModifierLoc()
  2733. : SC->getSecondScheduleModifierLoc(),
  2734. diag::err_omp_schedule_nonmonotonic_ordered)
  2735. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2736. ErrorFound = true;
  2737. }
  2738. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2739. for (const OMPLinearClause *C : LCs) {
  2740. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  2741. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2742. }
  2743. ErrorFound = true;
  2744. }
  2745. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2746. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2747. OC->getNumForLoops()) {
  2748. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  2749. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2750. ErrorFound = true;
  2751. }
  2752. if (ErrorFound) {
  2753. return StmtError();
  2754. }
  2755. StmtResult SR = S;
  2756. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2757. // Mark all variables in private list clauses as used in inner region.
  2758. // Required for proper codegen of combined directives.
  2759. // TODO: add processing for other clauses.
  2760. if (ThisCaptureRegion != OMPD_unknown) {
  2761. for (const clang::OMPClauseWithPreInit *C : PICs) {
  2762. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2763. // Find the particular capture region for the clause if the
  2764. // directive is a combined one with multiple capture regions.
  2765. // If the directive is not a combined one, the capture region
  2766. // associated with the clause is OMPD_unknown and is generated
  2767. // only once.
  2768. if (CaptureRegion == ThisCaptureRegion ||
  2769. CaptureRegion == OMPD_unknown) {
  2770. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2771. for (Decl *D : DS->decls())
  2772. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2773. }
  2774. }
  2775. }
  2776. }
  2777. SR = ActOnCapturedRegionEnd(SR.get());
  2778. }
  2779. return SR;
  2780. }
  2781. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2782. OpenMPDirectiveKind CancelRegion,
  2783. SourceLocation StartLoc) {
  2784. // CancelRegion is only needed for cancel and cancellation_point.
  2785. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2786. return false;
  2787. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2788. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2789. return false;
  2790. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2791. << getOpenMPDirectiveName(CancelRegion);
  2792. return true;
  2793. }
  2794. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  2795. OpenMPDirectiveKind CurrentRegion,
  2796. const DeclarationNameInfo &CurrentName,
  2797. OpenMPDirectiveKind CancelRegion,
  2798. SourceLocation StartLoc) {
  2799. if (Stack->getCurScope()) {
  2800. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  2801. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  2802. bool NestingProhibited = false;
  2803. bool CloseNesting = true;
  2804. bool OrphanSeen = false;
  2805. enum {
  2806. NoRecommend,
  2807. ShouldBeInParallelRegion,
  2808. ShouldBeInOrderedRegion,
  2809. ShouldBeInTargetRegion,
  2810. ShouldBeInTeamsRegion
  2811. } Recommend = NoRecommend;
  2812. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2813. // OpenMP [2.16, Nesting of Regions]
  2814. // OpenMP constructs may not be nested inside a simd region.
  2815. // OpenMP [2.8.1,simd Construct, Restrictions]
  2816. // An ordered construct with the simd clause is the only OpenMP
  2817. // construct that can appear in the simd region.
  2818. // Allowing a SIMD construct nested in another SIMD construct is an
  2819. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2820. // message.
  2821. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2822. ? diag::err_omp_prohibited_region_simd
  2823. : diag::warn_omp_nesting_simd);
  2824. return CurrentRegion != OMPD_simd;
  2825. }
  2826. if (ParentRegion == OMPD_atomic) {
  2827. // OpenMP [2.16, Nesting of Regions]
  2828. // OpenMP constructs may not be nested inside an atomic region.
  2829. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2830. return true;
  2831. }
  2832. if (CurrentRegion == OMPD_section) {
  2833. // OpenMP [2.7.2, sections Construct, Restrictions]
  2834. // Orphaned section directives are prohibited. That is, the section
  2835. // directives must appear within the sections construct and must not be
  2836. // encountered elsewhere in the sections region.
  2837. if (ParentRegion != OMPD_sections &&
  2838. ParentRegion != OMPD_parallel_sections) {
  2839. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2840. << (ParentRegion != OMPD_unknown)
  2841. << getOpenMPDirectiveName(ParentRegion);
  2842. return true;
  2843. }
  2844. return false;
  2845. }
  2846. // Allow some constructs (except teams) to be orphaned (they could be
  2847. // used in functions, called from OpenMP regions with the required
  2848. // preconditions).
  2849. if (ParentRegion == OMPD_unknown &&
  2850. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2851. return false;
  2852. if (CurrentRegion == OMPD_cancellation_point ||
  2853. CurrentRegion == OMPD_cancel) {
  2854. // OpenMP [2.16, Nesting of Regions]
  2855. // A cancellation point construct for which construct-type-clause is
  2856. // taskgroup must be nested inside a task construct. A cancellation
  2857. // point construct for which construct-type-clause is not taskgroup must
  2858. // be closely nested inside an OpenMP construct that matches the type
  2859. // specified in construct-type-clause.
  2860. // A cancel construct for which construct-type-clause is taskgroup must be
  2861. // nested inside a task construct. A cancel construct for which
  2862. // construct-type-clause is not taskgroup must be closely nested inside an
  2863. // OpenMP construct that matches the type specified in
  2864. // construct-type-clause.
  2865. NestingProhibited =
  2866. !((CancelRegion == OMPD_parallel &&
  2867. (ParentRegion == OMPD_parallel ||
  2868. ParentRegion == OMPD_target_parallel)) ||
  2869. (CancelRegion == OMPD_for &&
  2870. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2871. ParentRegion == OMPD_target_parallel_for ||
  2872. ParentRegion == OMPD_distribute_parallel_for ||
  2873. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2874. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2875. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2876. (CancelRegion == OMPD_sections &&
  2877. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2878. ParentRegion == OMPD_parallel_sections)));
  2879. } else if (CurrentRegion == OMPD_master) {
  2880. // OpenMP [2.16, Nesting of Regions]
  2881. // A master region may not be closely nested inside a worksharing,
  2882. // atomic, or explicit task region.
  2883. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2884. isOpenMPTaskingDirective(ParentRegion);
  2885. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2886. // OpenMP [2.16, Nesting of Regions]
  2887. // A critical region may not be nested (closely or otherwise) inside a
  2888. // critical region with the same name. Note that this restriction is not
  2889. // sufficient to prevent deadlock.
  2890. SourceLocation PreviousCriticalLoc;
  2891. bool DeadLock = Stack->hasDirective(
  2892. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2893. const DeclarationNameInfo &DNI,
  2894. SourceLocation Loc) {
  2895. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2896. PreviousCriticalLoc = Loc;
  2897. return true;
  2898. }
  2899. return false;
  2900. },
  2901. false /* skip top directive */);
  2902. if (DeadLock) {
  2903. SemaRef.Diag(StartLoc,
  2904. diag::err_omp_prohibited_region_critical_same_name)
  2905. << CurrentName.getName();
  2906. if (PreviousCriticalLoc.isValid())
  2907. SemaRef.Diag(PreviousCriticalLoc,
  2908. diag::note_omp_previous_critical_region);
  2909. return true;
  2910. }
  2911. } else if (CurrentRegion == OMPD_barrier) {
  2912. // OpenMP [2.16, Nesting of Regions]
  2913. // A barrier region may not be closely nested inside a worksharing,
  2914. // explicit task, critical, ordered, atomic, or master region.
  2915. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2916. isOpenMPTaskingDirective(ParentRegion) ||
  2917. ParentRegion == OMPD_master ||
  2918. ParentRegion == OMPD_critical ||
  2919. ParentRegion == OMPD_ordered;
  2920. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2921. !isOpenMPParallelDirective(CurrentRegion) &&
  2922. !isOpenMPTeamsDirective(CurrentRegion)) {
  2923. // OpenMP [2.16, Nesting of Regions]
  2924. // A worksharing region may not be closely nested inside a worksharing,
  2925. // explicit task, critical, ordered, atomic, or master region.
  2926. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2927. isOpenMPTaskingDirective(ParentRegion) ||
  2928. ParentRegion == OMPD_master ||
  2929. ParentRegion == OMPD_critical ||
  2930. ParentRegion == OMPD_ordered;
  2931. Recommend = ShouldBeInParallelRegion;
  2932. } else if (CurrentRegion == OMPD_ordered) {
  2933. // OpenMP [2.16, Nesting of Regions]
  2934. // An ordered region may not be closely nested inside a critical,
  2935. // atomic, or explicit task region.
  2936. // An ordered region must be closely nested inside a loop region (or
  2937. // parallel loop region) with an ordered clause.
  2938. // OpenMP [2.8.1,simd Construct, Restrictions]
  2939. // An ordered construct with the simd clause is the only OpenMP construct
  2940. // that can appear in the simd region.
  2941. NestingProhibited = ParentRegion == OMPD_critical ||
  2942. isOpenMPTaskingDirective(ParentRegion) ||
  2943. !(isOpenMPSimdDirective(ParentRegion) ||
  2944. Stack->isParentOrderedRegion());
  2945. Recommend = ShouldBeInOrderedRegion;
  2946. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2947. // OpenMP [2.16, Nesting of Regions]
  2948. // If specified, a teams construct must be contained within a target
  2949. // construct.
  2950. NestingProhibited = ParentRegion != OMPD_target;
  2951. OrphanSeen = ParentRegion == OMPD_unknown;
  2952. Recommend = ShouldBeInTargetRegion;
  2953. }
  2954. if (!NestingProhibited &&
  2955. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2956. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2957. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2958. // OpenMP [2.16, Nesting of Regions]
  2959. // distribute, parallel, parallel sections, parallel workshare, and the
  2960. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2961. // constructs that can be closely nested in the teams region.
  2962. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2963. !isOpenMPDistributeDirective(CurrentRegion);
  2964. Recommend = ShouldBeInParallelRegion;
  2965. }
  2966. if (!NestingProhibited &&
  2967. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2968. // OpenMP 4.5 [2.17 Nesting of Regions]
  2969. // The region associated with the distribute construct must be strictly
  2970. // nested inside a teams region
  2971. NestingProhibited =
  2972. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2973. Recommend = ShouldBeInTeamsRegion;
  2974. }
  2975. if (!NestingProhibited &&
  2976. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2977. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2978. // OpenMP 4.5 [2.17 Nesting of Regions]
  2979. // If a target, target update, target data, target enter data, or
  2980. // target exit data construct is encountered during execution of a
  2981. // target region, the behavior is unspecified.
  2982. NestingProhibited = Stack->hasDirective(
  2983. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2984. SourceLocation) {
  2985. if (isOpenMPTargetExecutionDirective(K)) {
  2986. OffendingRegion = K;
  2987. return true;
  2988. }
  2989. return false;
  2990. },
  2991. false /* don't skip top directive */);
  2992. CloseNesting = false;
  2993. }
  2994. if (NestingProhibited) {
  2995. if (OrphanSeen) {
  2996. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2997. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2998. } else {
  2999. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3000. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3001. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3002. }
  3003. return true;
  3004. }
  3005. }
  3006. return false;
  3007. }
  3008. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3009. ArrayRef<OMPClause *> Clauses,
  3010. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3011. bool ErrorFound = false;
  3012. unsigned NamedModifiersNumber = 0;
  3013. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3014. OMPD_unknown + 1);
  3015. SmallVector<SourceLocation, 4> NameModifierLoc;
  3016. for (const OMPClause *C : Clauses) {
  3017. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3018. // At most one if clause without a directive-name-modifier can appear on
  3019. // the directive.
  3020. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3021. if (FoundNameModifiers[CurNM]) {
  3022. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3023. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3024. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3025. ErrorFound = true;
  3026. } else if (CurNM != OMPD_unknown) {
  3027. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3028. ++NamedModifiersNumber;
  3029. }
  3030. FoundNameModifiers[CurNM] = IC;
  3031. if (CurNM == OMPD_unknown)
  3032. continue;
  3033. // Check if the specified name modifier is allowed for the current
  3034. // directive.
  3035. // At most one if clause with the particular directive-name-modifier can
  3036. // appear on the directive.
  3037. bool MatchFound = false;
  3038. for (auto NM : AllowedNameModifiers) {
  3039. if (CurNM == NM) {
  3040. MatchFound = true;
  3041. break;
  3042. }
  3043. }
  3044. if (!MatchFound) {
  3045. S.Diag(IC->getNameModifierLoc(),
  3046. diag::err_omp_wrong_if_directive_name_modifier)
  3047. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3048. ErrorFound = true;
  3049. }
  3050. }
  3051. }
  3052. // If any if clause on the directive includes a directive-name-modifier then
  3053. // all if clauses on the directive must include a directive-name-modifier.
  3054. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3055. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3056. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3057. diag::err_omp_no_more_if_clause);
  3058. } else {
  3059. std::string Values;
  3060. std::string Sep(", ");
  3061. unsigned AllowedCnt = 0;
  3062. unsigned TotalAllowedNum =
  3063. AllowedNameModifiers.size() - NamedModifiersNumber;
  3064. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3065. ++Cnt) {
  3066. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3067. if (!FoundNameModifiers[NM]) {
  3068. Values += "'";
  3069. Values += getOpenMPDirectiveName(NM);
  3070. Values += "'";
  3071. if (AllowedCnt + 2 == TotalAllowedNum)
  3072. Values += " or ";
  3073. else if (AllowedCnt + 1 != TotalAllowedNum)
  3074. Values += Sep;
  3075. ++AllowedCnt;
  3076. }
  3077. }
  3078. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3079. diag::err_omp_unnamed_if_clause)
  3080. << (TotalAllowedNum > 1) << Values;
  3081. }
  3082. for (SourceLocation Loc : NameModifierLoc) {
  3083. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3084. }
  3085. ErrorFound = true;
  3086. }
  3087. return ErrorFound;
  3088. }
  3089. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3090. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3091. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3092. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3093. StmtResult Res = StmtError();
  3094. // First check CancelRegion which is then used in checkNestingOfRegions.
  3095. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3096. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3097. StartLoc))
  3098. return StmtError();
  3099. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3100. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3101. bool ErrorFound = false;
  3102. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3103. if (AStmt && !CurContext->isDependentContext()) {
  3104. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3105. // Check default data sharing attributes for referenced variables.
  3106. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3107. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3108. Stmt *S = AStmt;
  3109. while (--ThisCaptureLevel >= 0)
  3110. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3111. DSAChecker.Visit(S);
  3112. if (DSAChecker.isErrorFound())
  3113. return StmtError();
  3114. // Generate list of implicitly defined firstprivate variables.
  3115. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3116. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3117. DSAChecker.getImplicitFirstprivate().begin(),
  3118. DSAChecker.getImplicitFirstprivate().end());
  3119. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3120. DSAChecker.getImplicitMap().end());
  3121. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3122. for (OMPClause *C : Clauses) {
  3123. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3124. for (Expr *E : IRC->taskgroup_descriptors())
  3125. if (E)
  3126. ImplicitFirstprivates.emplace_back(E);
  3127. }
  3128. }
  3129. if (!ImplicitFirstprivates.empty()) {
  3130. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3131. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3132. SourceLocation())) {
  3133. ClausesWithImplicit.push_back(Implicit);
  3134. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3135. ImplicitFirstprivates.size();
  3136. } else {
  3137. ErrorFound = true;
  3138. }
  3139. }
  3140. if (!ImplicitMaps.empty()) {
  3141. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3142. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  3143. SourceLocation(), SourceLocation(), ImplicitMaps,
  3144. SourceLocation(), SourceLocation(), SourceLocation())) {
  3145. ClausesWithImplicit.emplace_back(Implicit);
  3146. ErrorFound |=
  3147. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3148. } else {
  3149. ErrorFound = true;
  3150. }
  3151. }
  3152. }
  3153. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3154. switch (Kind) {
  3155. case OMPD_parallel:
  3156. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3157. EndLoc);
  3158. AllowedNameModifiers.push_back(OMPD_parallel);
  3159. break;
  3160. case OMPD_simd:
  3161. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3162. VarsWithInheritedDSA);
  3163. break;
  3164. case OMPD_for:
  3165. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3166. VarsWithInheritedDSA);
  3167. break;
  3168. case OMPD_for_simd:
  3169. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3170. EndLoc, VarsWithInheritedDSA);
  3171. break;
  3172. case OMPD_sections:
  3173. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3174. EndLoc);
  3175. break;
  3176. case OMPD_section:
  3177. assert(ClausesWithImplicit.empty() &&
  3178. "No clauses are allowed for 'omp section' directive");
  3179. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3180. break;
  3181. case OMPD_single:
  3182. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3183. EndLoc);
  3184. break;
  3185. case OMPD_master:
  3186. assert(ClausesWithImplicit.empty() &&
  3187. "No clauses are allowed for 'omp master' directive");
  3188. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3189. break;
  3190. case OMPD_critical:
  3191. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3192. StartLoc, EndLoc);
  3193. break;
  3194. case OMPD_parallel_for:
  3195. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3196. EndLoc, VarsWithInheritedDSA);
  3197. AllowedNameModifiers.push_back(OMPD_parallel);
  3198. break;
  3199. case OMPD_parallel_for_simd:
  3200. Res = ActOnOpenMPParallelForSimdDirective(
  3201. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3202. AllowedNameModifiers.push_back(OMPD_parallel);
  3203. break;
  3204. case OMPD_parallel_sections:
  3205. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3206. StartLoc, EndLoc);
  3207. AllowedNameModifiers.push_back(OMPD_parallel);
  3208. break;
  3209. case OMPD_task:
  3210. Res =
  3211. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3212. AllowedNameModifiers.push_back(OMPD_task);
  3213. break;
  3214. case OMPD_taskyield:
  3215. assert(ClausesWithImplicit.empty() &&
  3216. "No clauses are allowed for 'omp taskyield' directive");
  3217. assert(AStmt == nullptr &&
  3218. "No associated statement allowed for 'omp taskyield' directive");
  3219. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3220. break;
  3221. case OMPD_barrier:
  3222. assert(ClausesWithImplicit.empty() &&
  3223. "No clauses are allowed for 'omp barrier' directive");
  3224. assert(AStmt == nullptr &&
  3225. "No associated statement allowed for 'omp barrier' directive");
  3226. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3227. break;
  3228. case OMPD_taskwait:
  3229. assert(ClausesWithImplicit.empty() &&
  3230. "No clauses are allowed for 'omp taskwait' directive");
  3231. assert(AStmt == nullptr &&
  3232. "No associated statement allowed for 'omp taskwait' directive");
  3233. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3234. break;
  3235. case OMPD_taskgroup:
  3236. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3237. EndLoc);
  3238. break;
  3239. case OMPD_flush:
  3240. assert(AStmt == nullptr &&
  3241. "No associated statement allowed for 'omp flush' directive");
  3242. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3243. break;
  3244. case OMPD_ordered:
  3245. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3246. EndLoc);
  3247. break;
  3248. case OMPD_atomic:
  3249. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3250. EndLoc);
  3251. break;
  3252. case OMPD_teams:
  3253. Res =
  3254. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3255. break;
  3256. case OMPD_target:
  3257. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3258. EndLoc);
  3259. AllowedNameModifiers.push_back(OMPD_target);
  3260. break;
  3261. case OMPD_target_parallel:
  3262. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3263. StartLoc, EndLoc);
  3264. AllowedNameModifiers.push_back(OMPD_target);
  3265. AllowedNameModifiers.push_back(OMPD_parallel);
  3266. break;
  3267. case OMPD_target_parallel_for:
  3268. Res = ActOnOpenMPTargetParallelForDirective(
  3269. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3270. AllowedNameModifiers.push_back(OMPD_target);
  3271. AllowedNameModifiers.push_back(OMPD_parallel);
  3272. break;
  3273. case OMPD_cancellation_point:
  3274. assert(ClausesWithImplicit.empty() &&
  3275. "No clauses are allowed for 'omp cancellation point' directive");
  3276. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3277. "cancellation point' directive");
  3278. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3279. break;
  3280. case OMPD_cancel:
  3281. assert(AStmt == nullptr &&
  3282. "No associated statement allowed for 'omp cancel' directive");
  3283. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3284. CancelRegion);
  3285. AllowedNameModifiers.push_back(OMPD_cancel);
  3286. break;
  3287. case OMPD_target_data:
  3288. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3289. EndLoc);
  3290. AllowedNameModifiers.push_back(OMPD_target_data);
  3291. break;
  3292. case OMPD_target_enter_data:
  3293. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3294. EndLoc, AStmt);
  3295. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3296. break;
  3297. case OMPD_target_exit_data:
  3298. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3299. EndLoc, AStmt);
  3300. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3301. break;
  3302. case OMPD_taskloop:
  3303. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3304. EndLoc, VarsWithInheritedDSA);
  3305. AllowedNameModifiers.push_back(OMPD_taskloop);
  3306. break;
  3307. case OMPD_taskloop_simd:
  3308. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3309. EndLoc, VarsWithInheritedDSA);
  3310. AllowedNameModifiers.push_back(OMPD_taskloop);
  3311. break;
  3312. case OMPD_distribute:
  3313. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3314. EndLoc, VarsWithInheritedDSA);
  3315. break;
  3316. case OMPD_target_update:
  3317. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3318. EndLoc, AStmt);
  3319. AllowedNameModifiers.push_back(OMPD_target_update);
  3320. break;
  3321. case OMPD_distribute_parallel_for:
  3322. Res = ActOnOpenMPDistributeParallelForDirective(
  3323. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3324. AllowedNameModifiers.push_back(OMPD_parallel);
  3325. break;
  3326. case OMPD_distribute_parallel_for_simd:
  3327. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3328. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3329. AllowedNameModifiers.push_back(OMPD_parallel);
  3330. break;
  3331. case OMPD_distribute_simd:
  3332. Res = ActOnOpenMPDistributeSimdDirective(
  3333. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3334. break;
  3335. case OMPD_target_parallel_for_simd:
  3336. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3337. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3338. AllowedNameModifiers.push_back(OMPD_target);
  3339. AllowedNameModifiers.push_back(OMPD_parallel);
  3340. break;
  3341. case OMPD_target_simd:
  3342. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3343. EndLoc, VarsWithInheritedDSA);
  3344. AllowedNameModifiers.push_back(OMPD_target);
  3345. break;
  3346. case OMPD_teams_distribute:
  3347. Res = ActOnOpenMPTeamsDistributeDirective(
  3348. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3349. break;
  3350. case OMPD_teams_distribute_simd:
  3351. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3352. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3353. break;
  3354. case OMPD_teams_distribute_parallel_for_simd:
  3355. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3356. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3357. AllowedNameModifiers.push_back(OMPD_parallel);
  3358. break;
  3359. case OMPD_teams_distribute_parallel_for:
  3360. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3361. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3362. AllowedNameModifiers.push_back(OMPD_parallel);
  3363. break;
  3364. case OMPD_target_teams:
  3365. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3366. EndLoc);
  3367. AllowedNameModifiers.push_back(OMPD_target);
  3368. break;
  3369. case OMPD_target_teams_distribute:
  3370. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3371. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3372. AllowedNameModifiers.push_back(OMPD_target);
  3373. break;
  3374. case OMPD_target_teams_distribute_parallel_for:
  3375. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3376. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3377. AllowedNameModifiers.push_back(OMPD_target);
  3378. AllowedNameModifiers.push_back(OMPD_parallel);
  3379. break;
  3380. case OMPD_target_teams_distribute_parallel_for_simd:
  3381. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3382. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3383. AllowedNameModifiers.push_back(OMPD_target);
  3384. AllowedNameModifiers.push_back(OMPD_parallel);
  3385. break;
  3386. case OMPD_target_teams_distribute_simd:
  3387. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3388. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3389. AllowedNameModifiers.push_back(OMPD_target);
  3390. break;
  3391. case OMPD_declare_target:
  3392. case OMPD_end_declare_target:
  3393. case OMPD_threadprivate:
  3394. case OMPD_declare_reduction:
  3395. case OMPD_declare_simd:
  3396. case OMPD_requires:
  3397. llvm_unreachable("OpenMP Directive is not allowed");
  3398. case OMPD_unknown:
  3399. llvm_unreachable("Unknown OpenMP directive");
  3400. }
  3401. for (const auto &P : VarsWithInheritedDSA) {
  3402. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3403. << P.first << P.second->getSourceRange();
  3404. }
  3405. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3406. if (!AllowedNameModifiers.empty())
  3407. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3408. ErrorFound;
  3409. if (ErrorFound)
  3410. return StmtError();
  3411. return Res;
  3412. }
  3413. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3414. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3415. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3416. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3417. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3418. assert(Aligneds.size() == Alignments.size());
  3419. assert(Linears.size() == LinModifiers.size());
  3420. assert(Linears.size() == Steps.size());
  3421. if (!DG || DG.get().isNull())
  3422. return DeclGroupPtrTy();
  3423. if (!DG.get().isSingleDecl()) {
  3424. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3425. return DG;
  3426. }
  3427. Decl *ADecl = DG.get().getSingleDecl();
  3428. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3429. ADecl = FTD->getTemplatedDecl();
  3430. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3431. if (!FD) {
  3432. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3433. return DeclGroupPtrTy();
  3434. }
  3435. // OpenMP [2.8.2, declare simd construct, Description]
  3436. // The parameter of the simdlen clause must be a constant positive integer
  3437. // expression.
  3438. ExprResult SL;
  3439. if (Simdlen)
  3440. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3441. // OpenMP [2.8.2, declare simd construct, Description]
  3442. // The special this pointer can be used as if was one of the arguments to the
  3443. // function in any of the linear, aligned, or uniform clauses.
  3444. // The uniform clause declares one or more arguments to have an invariant
  3445. // value for all concurrent invocations of the function in the execution of a
  3446. // single SIMD loop.
  3447. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3448. const Expr *UniformedLinearThis = nullptr;
  3449. for (const Expr *E : Uniforms) {
  3450. E = E->IgnoreParenImpCasts();
  3451. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3452. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3453. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3454. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3455. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3456. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3457. continue;
  3458. }
  3459. if (isa<CXXThisExpr>(E)) {
  3460. UniformedLinearThis = E;
  3461. continue;
  3462. }
  3463. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3464. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3465. }
  3466. // OpenMP [2.8.2, declare simd construct, Description]
  3467. // The aligned clause declares that the object to which each list item points
  3468. // is aligned to the number of bytes expressed in the optional parameter of
  3469. // the aligned clause.
  3470. // The special this pointer can be used as if was one of the arguments to the
  3471. // function in any of the linear, aligned, or uniform clauses.
  3472. // The type of list items appearing in the aligned clause must be array,
  3473. // pointer, reference to array, or reference to pointer.
  3474. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3475. const Expr *AlignedThis = nullptr;
  3476. for (const Expr *E : Aligneds) {
  3477. E = E->IgnoreParenImpCasts();
  3478. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3479. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3480. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3481. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3482. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3483. ->getCanonicalDecl() == CanonPVD) {
  3484. // OpenMP [2.8.1, simd construct, Restrictions]
  3485. // A list-item cannot appear in more than one aligned clause.
  3486. if (AlignedArgs.count(CanonPVD) > 0) {
  3487. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3488. << 1 << E->getSourceRange();
  3489. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3490. diag::note_omp_explicit_dsa)
  3491. << getOpenMPClauseName(OMPC_aligned);
  3492. continue;
  3493. }
  3494. AlignedArgs[CanonPVD] = E;
  3495. QualType QTy = PVD->getType()
  3496. .getNonReferenceType()
  3497. .getUnqualifiedType()
  3498. .getCanonicalType();
  3499. const Type *Ty = QTy.getTypePtrOrNull();
  3500. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3501. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3502. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3503. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3504. }
  3505. continue;
  3506. }
  3507. }
  3508. if (isa<CXXThisExpr>(E)) {
  3509. if (AlignedThis) {
  3510. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3511. << 2 << E->getSourceRange();
  3512. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3513. << getOpenMPClauseName(OMPC_aligned);
  3514. }
  3515. AlignedThis = E;
  3516. continue;
  3517. }
  3518. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3519. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3520. }
  3521. // The optional parameter of the aligned clause, alignment, must be a constant
  3522. // positive integer expression. If no optional parameter is specified,
  3523. // implementation-defined default alignments for SIMD instructions on the
  3524. // target platforms are assumed.
  3525. SmallVector<const Expr *, 4> NewAligns;
  3526. for (Expr *E : Alignments) {
  3527. ExprResult Align;
  3528. if (E)
  3529. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3530. NewAligns.push_back(Align.get());
  3531. }
  3532. // OpenMP [2.8.2, declare simd construct, Description]
  3533. // The linear clause declares one or more list items to be private to a SIMD
  3534. // lane and to have a linear relationship with respect to the iteration space
  3535. // of a loop.
  3536. // The special this pointer can be used as if was one of the arguments to the
  3537. // function in any of the linear, aligned, or uniform clauses.
  3538. // When a linear-step expression is specified in a linear clause it must be
  3539. // either a constant integer expression or an integer-typed parameter that is
  3540. // specified in a uniform clause on the directive.
  3541. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  3542. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3543. auto MI = LinModifiers.begin();
  3544. for (const Expr *E : Linears) {
  3545. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3546. ++MI;
  3547. E = E->IgnoreParenImpCasts();
  3548. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3549. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3550. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3551. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3552. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3553. ->getCanonicalDecl() == CanonPVD) {
  3554. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3555. // A list-item cannot appear in more than one linear clause.
  3556. if (LinearArgs.count(CanonPVD) > 0) {
  3557. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3558. << getOpenMPClauseName(OMPC_linear)
  3559. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3560. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3561. diag::note_omp_explicit_dsa)
  3562. << getOpenMPClauseName(OMPC_linear);
  3563. continue;
  3564. }
  3565. // Each argument can appear in at most one uniform or linear clause.
  3566. if (UniformedArgs.count(CanonPVD) > 0) {
  3567. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3568. << getOpenMPClauseName(OMPC_linear)
  3569. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3570. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3571. diag::note_omp_explicit_dsa)
  3572. << getOpenMPClauseName(OMPC_uniform);
  3573. continue;
  3574. }
  3575. LinearArgs[CanonPVD] = E;
  3576. if (E->isValueDependent() || E->isTypeDependent() ||
  3577. E->isInstantiationDependent() ||
  3578. E->containsUnexpandedParameterPack())
  3579. continue;
  3580. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3581. PVD->getOriginalType());
  3582. continue;
  3583. }
  3584. }
  3585. if (isa<CXXThisExpr>(E)) {
  3586. if (UniformedLinearThis) {
  3587. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3588. << getOpenMPClauseName(OMPC_linear)
  3589. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3590. << E->getSourceRange();
  3591. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3592. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3593. : OMPC_linear);
  3594. continue;
  3595. }
  3596. UniformedLinearThis = E;
  3597. if (E->isValueDependent() || E->isTypeDependent() ||
  3598. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3599. continue;
  3600. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3601. E->getType());
  3602. continue;
  3603. }
  3604. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3605. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3606. }
  3607. Expr *Step = nullptr;
  3608. Expr *NewStep = nullptr;
  3609. SmallVector<Expr *, 4> NewSteps;
  3610. for (Expr *E : Steps) {
  3611. // Skip the same step expression, it was checked already.
  3612. if (Step == E || !E) {
  3613. NewSteps.push_back(E ? NewStep : nullptr);
  3614. continue;
  3615. }
  3616. Step = E;
  3617. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3618. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3619. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3620. if (UniformedArgs.count(CanonPVD) == 0) {
  3621. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3622. << Step->getSourceRange();
  3623. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3624. E->isInstantiationDependent() ||
  3625. E->containsUnexpandedParameterPack() ||
  3626. CanonPVD->getType()->hasIntegerRepresentation()) {
  3627. NewSteps.push_back(Step);
  3628. } else {
  3629. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3630. << Step->getSourceRange();
  3631. }
  3632. continue;
  3633. }
  3634. NewStep = Step;
  3635. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3636. !Step->isInstantiationDependent() &&
  3637. !Step->containsUnexpandedParameterPack()) {
  3638. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3639. .get();
  3640. if (NewStep)
  3641. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3642. }
  3643. NewSteps.push_back(NewStep);
  3644. }
  3645. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3646. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3647. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3648. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3649. const_cast<Expr **>(Linears.data()), Linears.size(),
  3650. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3651. NewSteps.data(), NewSteps.size(), SR);
  3652. ADecl->addAttr(NewAttr);
  3653. return ConvertDeclToDeclGroup(ADecl);
  3654. }
  3655. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3656. Stmt *AStmt,
  3657. SourceLocation StartLoc,
  3658. SourceLocation EndLoc) {
  3659. if (!AStmt)
  3660. return StmtError();
  3661. auto *CS = cast<CapturedStmt>(AStmt);
  3662. // 1.2.2 OpenMP Language Terminology
  3663. // Structured block - An executable statement with a single entry at the
  3664. // top and a single exit at the bottom.
  3665. // The point of exit cannot be a branch out of the structured block.
  3666. // longjmp() and throw() must not violate the entry/exit criteria.
  3667. CS->getCapturedDecl()->setNothrow();
  3668. setFunctionHasBranchProtectedScope();
  3669. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3670. DSAStack->isCancelRegion());
  3671. }
  3672. namespace {
  3673. /// Helper class for checking canonical form of the OpenMP loops and
  3674. /// extracting iteration space of each loop in the loop nest, that will be used
  3675. /// for IR generation.
  3676. class OpenMPIterationSpaceChecker {
  3677. /// Reference to Sema.
  3678. Sema &SemaRef;
  3679. /// A location for diagnostics (when there is no some better location).
  3680. SourceLocation DefaultLoc;
  3681. /// A location for diagnostics (when increment is not compatible).
  3682. SourceLocation ConditionLoc;
  3683. /// A source location for referring to loop init later.
  3684. SourceRange InitSrcRange;
  3685. /// A source location for referring to condition later.
  3686. SourceRange ConditionSrcRange;
  3687. /// A source location for referring to increment later.
  3688. SourceRange IncrementSrcRange;
  3689. /// Loop variable.
  3690. ValueDecl *LCDecl = nullptr;
  3691. /// Reference to loop variable.
  3692. Expr *LCRef = nullptr;
  3693. /// Lower bound (initializer for the var).
  3694. Expr *LB = nullptr;
  3695. /// Upper bound.
  3696. Expr *UB = nullptr;
  3697. /// Loop step (increment).
  3698. Expr *Step = nullptr;
  3699. /// This flag is true when condition is one of:
  3700. /// Var < UB
  3701. /// Var <= UB
  3702. /// UB > Var
  3703. /// UB >= Var
  3704. /// This will have no value when the condition is !=
  3705. llvm::Optional<bool> TestIsLessOp;
  3706. /// This flag is true when condition is strict ( < or > ).
  3707. bool TestIsStrictOp = false;
  3708. /// This flag is true when step is subtracted on each iteration.
  3709. bool SubtractStep = false;
  3710. public:
  3711. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3712. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3713. /// Check init-expr for canonical loop form and save loop counter
  3714. /// variable - #Var and its initialization value - #LB.
  3715. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  3716. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  3717. /// for less/greater and for strict/non-strict comparison.
  3718. bool checkAndSetCond(Expr *S);
  3719. /// Check incr-expr for canonical loop form and return true if it
  3720. /// does not conform, otherwise save loop step (#Step).
  3721. bool checkAndSetInc(Expr *S);
  3722. /// Return the loop counter variable.
  3723. ValueDecl *getLoopDecl() const { return LCDecl; }
  3724. /// Return the reference expression to loop counter variable.
  3725. Expr *getLoopDeclRefExpr() const { return LCRef; }
  3726. /// Source range of the loop init.
  3727. SourceRange getInitSrcRange() const { return InitSrcRange; }
  3728. /// Source range of the loop condition.
  3729. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  3730. /// Source range of the loop increment.
  3731. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  3732. /// True if the step should be subtracted.
  3733. bool shouldSubtractStep() const { return SubtractStep; }
  3734. /// Build the expression to calculate the number of iterations.
  3735. Expr *buildNumIterations(
  3736. Scope *S, const bool LimitedType,
  3737. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3738. /// Build the precondition expression for the loops.
  3739. Expr *
  3740. buildPreCond(Scope *S, Expr *Cond,
  3741. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3742. /// Build reference expression to the counter be used for codegen.
  3743. DeclRefExpr *
  3744. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3745. DSAStackTy &DSA) const;
  3746. /// Build reference expression to the private counter be used for
  3747. /// codegen.
  3748. Expr *buildPrivateCounterVar() const;
  3749. /// Build initialization of the counter be used for codegen.
  3750. Expr *buildCounterInit() const;
  3751. /// Build step of the counter be used for codegen.
  3752. Expr *buildCounterStep() const;
  3753. /// Build loop data with counter value for depend clauses in ordered
  3754. /// directives.
  3755. Expr *
  3756. buildOrderedLoopData(Scope *S, Expr *Counter,
  3757. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3758. SourceLocation Loc, Expr *Inc = nullptr,
  3759. OverloadedOperatorKind OOK = OO_Amp);
  3760. /// Return true if any expression is dependent.
  3761. bool dependent() const;
  3762. private:
  3763. /// Check the right-hand side of an assignment in the increment
  3764. /// expression.
  3765. bool checkAndSetIncRHS(Expr *RHS);
  3766. /// Helper to set loop counter variable and its initializer.
  3767. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3768. /// Helper to set upper bound.
  3769. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  3770. SourceRange SR, SourceLocation SL);
  3771. /// Helper to set loop increment.
  3772. bool setStep(Expr *NewStep, bool Subtract);
  3773. };
  3774. bool OpenMPIterationSpaceChecker::dependent() const {
  3775. if (!LCDecl) {
  3776. assert(!LB && !UB && !Step);
  3777. return false;
  3778. }
  3779. return LCDecl->getType()->isDependentType() ||
  3780. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3781. (Step && Step->isValueDependent());
  3782. }
  3783. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  3784. Expr *NewLCRefExpr,
  3785. Expr *NewLB) {
  3786. // State consistency checking to ensure correct usage.
  3787. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3788. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3789. if (!NewLCDecl || !NewLB)
  3790. return true;
  3791. LCDecl = getCanonicalDecl(NewLCDecl);
  3792. LCRef = NewLCRefExpr;
  3793. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3794. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3795. if ((Ctor->isCopyOrMoveConstructor() ||
  3796. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3797. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3798. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3799. LB = NewLB;
  3800. return false;
  3801. }
  3802. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, llvm::Optional<bool> LessOp,
  3803. bool StrictOp, SourceRange SR,
  3804. SourceLocation SL) {
  3805. // State consistency checking to ensure correct usage.
  3806. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3807. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3808. if (!NewUB)
  3809. return true;
  3810. UB = NewUB;
  3811. if (LessOp)
  3812. TestIsLessOp = LessOp;
  3813. TestIsStrictOp = StrictOp;
  3814. ConditionSrcRange = SR;
  3815. ConditionLoc = SL;
  3816. return false;
  3817. }
  3818. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  3819. // State consistency checking to ensure correct usage.
  3820. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3821. if (!NewStep)
  3822. return true;
  3823. if (!NewStep->isValueDependent()) {
  3824. // Check that the step is integer expression.
  3825. SourceLocation StepLoc = NewStep->getBeginLoc();
  3826. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3827. StepLoc, getExprAsWritten(NewStep));
  3828. if (Val.isInvalid())
  3829. return true;
  3830. NewStep = Val.get();
  3831. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3832. // If test-expr is of form var relational-op b and relational-op is < or
  3833. // <= then incr-expr must cause var to increase on each iteration of the
  3834. // loop. If test-expr is of form var relational-op b and relational-op is
  3835. // > or >= then incr-expr must cause var to decrease on each iteration of
  3836. // the loop.
  3837. // If test-expr is of form b relational-op var and relational-op is < or
  3838. // <= then incr-expr must cause var to decrease on each iteration of the
  3839. // loop. If test-expr is of form b relational-op var and relational-op is
  3840. // > or >= then incr-expr must cause var to increase on each iteration of
  3841. // the loop.
  3842. llvm::APSInt Result;
  3843. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3844. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3845. bool IsConstNeg =
  3846. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3847. bool IsConstPos =
  3848. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3849. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3850. // != with increment is treated as <; != with decrement is treated as >
  3851. if (!TestIsLessOp.hasValue())
  3852. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  3853. if (UB && (IsConstZero ||
  3854. (TestIsLessOp.getValue() ?
  3855. (IsConstNeg || (IsUnsigned && Subtract)) :
  3856. (IsConstPos || (IsUnsigned && !Subtract))))) {
  3857. SemaRef.Diag(NewStep->getExprLoc(),
  3858. diag::err_omp_loop_incr_not_compatible)
  3859. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  3860. SemaRef.Diag(ConditionLoc,
  3861. diag::note_omp_loop_cond_requres_compatible_incr)
  3862. << TestIsLessOp.getValue() << ConditionSrcRange;
  3863. return true;
  3864. }
  3865. if (TestIsLessOp.getValue() == Subtract) {
  3866. NewStep =
  3867. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3868. .get();
  3869. Subtract = !Subtract;
  3870. }
  3871. }
  3872. Step = NewStep;
  3873. SubtractStep = Subtract;
  3874. return false;
  3875. }
  3876. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  3877. // Check init-expr for canonical loop form and save loop counter
  3878. // variable - #Var and its initialization value - #LB.
  3879. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3880. // var = lb
  3881. // integer-type var = lb
  3882. // random-access-iterator-type var = lb
  3883. // pointer-type var = lb
  3884. //
  3885. if (!S) {
  3886. if (EmitDiags) {
  3887. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3888. }
  3889. return true;
  3890. }
  3891. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3892. if (!ExprTemp->cleanupsHaveSideEffects())
  3893. S = ExprTemp->getSubExpr();
  3894. InitSrcRange = S->getSourceRange();
  3895. if (Expr *E = dyn_cast<Expr>(S))
  3896. S = E->IgnoreParens();
  3897. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3898. if (BO->getOpcode() == BO_Assign) {
  3899. Expr *LHS = BO->getLHS()->IgnoreParens();
  3900. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3901. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3902. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3903. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3904. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3905. }
  3906. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3907. if (ME->isArrow() &&
  3908. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3909. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3910. }
  3911. }
  3912. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3913. if (DS->isSingleDecl()) {
  3914. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3915. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3916. // Accept non-canonical init form here but emit ext. warning.
  3917. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3918. SemaRef.Diag(S->getBeginLoc(),
  3919. diag::ext_omp_loop_not_canonical_init)
  3920. << S->getSourceRange();
  3921. return setLCDeclAndLB(
  3922. Var,
  3923. buildDeclRefExpr(SemaRef, Var,
  3924. Var->getType().getNonReferenceType(),
  3925. DS->getBeginLoc()),
  3926. Var->getInit());
  3927. }
  3928. }
  3929. }
  3930. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3931. if (CE->getOperator() == OO_Equal) {
  3932. Expr *LHS = CE->getArg(0);
  3933. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3934. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3935. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3936. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3937. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3938. }
  3939. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3940. if (ME->isArrow() &&
  3941. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3942. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3943. }
  3944. }
  3945. }
  3946. if (dependent() || SemaRef.CurContext->isDependentContext())
  3947. return false;
  3948. if (EmitDiags) {
  3949. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  3950. << S->getSourceRange();
  3951. }
  3952. return true;
  3953. }
  3954. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  3955. /// variable (which may be the loop variable) if possible.
  3956. static const ValueDecl *getInitLCDecl(const Expr *E) {
  3957. if (!E)
  3958. return nullptr;
  3959. E = getExprAsWritten(E);
  3960. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3961. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3962. if ((Ctor->isCopyOrMoveConstructor() ||
  3963. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3964. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3965. E = CE->getArg(0)->IgnoreParenImpCasts();
  3966. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3967. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3968. return getCanonicalDecl(VD);
  3969. }
  3970. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3971. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3972. return getCanonicalDecl(ME->getMemberDecl());
  3973. return nullptr;
  3974. }
  3975. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  3976. // Check test-expr for canonical form, save upper-bound UB, flags for
  3977. // less/greater and for strict/non-strict comparison.
  3978. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3979. // var relational-op b
  3980. // b relational-op var
  3981. //
  3982. if (!S) {
  3983. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3984. return true;
  3985. }
  3986. S = getExprAsWritten(S);
  3987. SourceLocation CondLoc = S->getBeginLoc();
  3988. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3989. if (BO->isRelationalOp()) {
  3990. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  3991. return setUB(BO->getRHS(),
  3992. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3993. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3994. BO->getSourceRange(), BO->getOperatorLoc());
  3995. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  3996. return setUB(BO->getLHS(),
  3997. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3998. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3999. BO->getSourceRange(), BO->getOperatorLoc());
  4000. } else if (BO->getOpcode() == BO_NE)
  4001. return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
  4002. BO->getRHS() : BO->getLHS(),
  4003. /*LessOp=*/llvm::None,
  4004. /*StrictOp=*/true,
  4005. BO->getSourceRange(), BO->getOperatorLoc());
  4006. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4007. if (CE->getNumArgs() == 2) {
  4008. auto Op = CE->getOperator();
  4009. switch (Op) {
  4010. case OO_Greater:
  4011. case OO_GreaterEqual:
  4012. case OO_Less:
  4013. case OO_LessEqual:
  4014. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4015. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  4016. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4017. CE->getOperatorLoc());
  4018. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  4019. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  4020. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4021. CE->getOperatorLoc());
  4022. break;
  4023. case OO_ExclaimEqual:
  4024. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
  4025. CE->getArg(1) : CE->getArg(0),
  4026. /*LessOp=*/llvm::None,
  4027. /*StrictOp=*/true,
  4028. CE->getSourceRange(),
  4029. CE->getOperatorLoc());
  4030. break;
  4031. default:
  4032. break;
  4033. }
  4034. }
  4035. }
  4036. if (dependent() || SemaRef.CurContext->isDependentContext())
  4037. return false;
  4038. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4039. << S->getSourceRange() << LCDecl;
  4040. return true;
  4041. }
  4042. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4043. // RHS of canonical loop form increment can be:
  4044. // var + incr
  4045. // incr + var
  4046. // var - incr
  4047. //
  4048. RHS = RHS->IgnoreParenImpCasts();
  4049. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4050. if (BO->isAdditiveOp()) {
  4051. bool IsAdd = BO->getOpcode() == BO_Add;
  4052. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4053. return setStep(BO->getRHS(), !IsAdd);
  4054. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4055. return setStep(BO->getLHS(), /*Subtract=*/false);
  4056. }
  4057. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4058. bool IsAdd = CE->getOperator() == OO_Plus;
  4059. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4060. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4061. return setStep(CE->getArg(1), !IsAdd);
  4062. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4063. return setStep(CE->getArg(0), /*Subtract=*/false);
  4064. }
  4065. }
  4066. if (dependent() || SemaRef.CurContext->isDependentContext())
  4067. return false;
  4068. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4069. << RHS->getSourceRange() << LCDecl;
  4070. return true;
  4071. }
  4072. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4073. // Check incr-expr for canonical loop form and return true if it
  4074. // does not conform.
  4075. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4076. // ++var
  4077. // var++
  4078. // --var
  4079. // var--
  4080. // var += incr
  4081. // var -= incr
  4082. // var = var + incr
  4083. // var = incr + var
  4084. // var = var - incr
  4085. //
  4086. if (!S) {
  4087. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4088. return true;
  4089. }
  4090. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4091. if (!ExprTemp->cleanupsHaveSideEffects())
  4092. S = ExprTemp->getSubExpr();
  4093. IncrementSrcRange = S->getSourceRange();
  4094. S = S->IgnoreParens();
  4095. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4096. if (UO->isIncrementDecrementOp() &&
  4097. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4098. return setStep(SemaRef
  4099. .ActOnIntegerConstant(UO->getBeginLoc(),
  4100. (UO->isDecrementOp() ? -1 : 1))
  4101. .get(),
  4102. /*Subtract=*/false);
  4103. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4104. switch (BO->getOpcode()) {
  4105. case BO_AddAssign:
  4106. case BO_SubAssign:
  4107. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4108. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4109. break;
  4110. case BO_Assign:
  4111. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4112. return checkAndSetIncRHS(BO->getRHS());
  4113. break;
  4114. default:
  4115. break;
  4116. }
  4117. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4118. switch (CE->getOperator()) {
  4119. case OO_PlusPlus:
  4120. case OO_MinusMinus:
  4121. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4122. return setStep(SemaRef
  4123. .ActOnIntegerConstant(
  4124. CE->getBeginLoc(),
  4125. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  4126. .get(),
  4127. /*Subtract=*/false);
  4128. break;
  4129. case OO_PlusEqual:
  4130. case OO_MinusEqual:
  4131. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4132. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  4133. break;
  4134. case OO_Equal:
  4135. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4136. return checkAndSetIncRHS(CE->getArg(1));
  4137. break;
  4138. default:
  4139. break;
  4140. }
  4141. }
  4142. if (dependent() || SemaRef.CurContext->isDependentContext())
  4143. return false;
  4144. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4145. << S->getSourceRange() << LCDecl;
  4146. return true;
  4147. }
  4148. static ExprResult
  4149. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  4150. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4151. if (SemaRef.CurContext->isDependentContext())
  4152. return ExprResult(Capture);
  4153. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  4154. return SemaRef.PerformImplicitConversion(
  4155. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  4156. /*AllowExplicit=*/true);
  4157. auto I = Captures.find(Capture);
  4158. if (I != Captures.end())
  4159. return buildCapture(SemaRef, Capture, I->second);
  4160. DeclRefExpr *Ref = nullptr;
  4161. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  4162. Captures[Capture] = Ref;
  4163. return Res;
  4164. }
  4165. /// Build the expression to calculate the number of iterations.
  4166. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  4167. Scope *S, const bool LimitedType,
  4168. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4169. ExprResult Diff;
  4170. QualType VarType = LCDecl->getType().getNonReferenceType();
  4171. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4172. SemaRef.getLangOpts().CPlusPlus) {
  4173. // Upper - Lower
  4174. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  4175. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  4176. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  4177. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  4178. if (!Upper || !Lower)
  4179. return nullptr;
  4180. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4181. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4182. // BuildBinOp already emitted error, this one is to point user to upper
  4183. // and lower bound, and to tell what is passed to 'operator-'.
  4184. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4185. << Upper->getSourceRange() << Lower->getSourceRange();
  4186. return nullptr;
  4187. }
  4188. }
  4189. if (!Diff.isUsable())
  4190. return nullptr;
  4191. // Upper - Lower [- 1]
  4192. if (TestIsStrictOp)
  4193. Diff = SemaRef.BuildBinOp(
  4194. S, DefaultLoc, BO_Sub, Diff.get(),
  4195. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4196. if (!Diff.isUsable())
  4197. return nullptr;
  4198. // Upper - Lower [- 1] + Step
  4199. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4200. if (!NewStep.isUsable())
  4201. return nullptr;
  4202. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  4203. if (!Diff.isUsable())
  4204. return nullptr;
  4205. // Parentheses (for dumping/debugging purposes only).
  4206. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4207. if (!Diff.isUsable())
  4208. return nullptr;
  4209. // (Upper - Lower [- 1] + Step) / Step
  4210. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4211. if (!Diff.isUsable())
  4212. return nullptr;
  4213. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  4214. QualType Type = Diff.get()->getType();
  4215. ASTContext &C = SemaRef.Context;
  4216. bool UseVarType = VarType->hasIntegerRepresentation() &&
  4217. C.getTypeSize(Type) > C.getTypeSize(VarType);
  4218. if (!Type->isIntegerType() || UseVarType) {
  4219. unsigned NewSize =
  4220. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  4221. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  4222. : Type->hasSignedIntegerRepresentation();
  4223. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  4224. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  4225. Diff = SemaRef.PerformImplicitConversion(
  4226. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  4227. if (!Diff.isUsable())
  4228. return nullptr;
  4229. }
  4230. }
  4231. if (LimitedType) {
  4232. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  4233. if (NewSize != C.getTypeSize(Type)) {
  4234. if (NewSize < C.getTypeSize(Type)) {
  4235. assert(NewSize == 64 && "incorrect loop var size");
  4236. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  4237. << InitSrcRange << ConditionSrcRange;
  4238. }
  4239. QualType NewType = C.getIntTypeForBitwidth(
  4240. NewSize, Type->hasSignedIntegerRepresentation() ||
  4241. C.getTypeSize(Type) < NewSize);
  4242. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  4243. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  4244. Sema::AA_Converting, true);
  4245. if (!Diff.isUsable())
  4246. return nullptr;
  4247. }
  4248. }
  4249. }
  4250. return Diff.get();
  4251. }
  4252. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4253. Scope *S, Expr *Cond,
  4254. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4255. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4256. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4257. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4258. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4259. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4260. if (!NewLB.isUsable() || !NewUB.isUsable())
  4261. return nullptr;
  4262. ExprResult CondExpr =
  4263. SemaRef.BuildBinOp(S, DefaultLoc,
  4264. TestIsLessOp.getValue() ?
  4265. (TestIsStrictOp ? BO_LT : BO_LE) :
  4266. (TestIsStrictOp ? BO_GT : BO_GE),
  4267. NewLB.get(), NewUB.get());
  4268. if (CondExpr.isUsable()) {
  4269. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4270. SemaRef.Context.BoolTy))
  4271. CondExpr = SemaRef.PerformImplicitConversion(
  4272. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4273. /*AllowExplicit=*/true);
  4274. }
  4275. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4276. // Otherwise use original loop conditon and evaluate it in runtime.
  4277. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4278. }
  4279. /// Build reference expression to the counter be used for codegen.
  4280. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4281. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4282. DSAStackTy &DSA) const {
  4283. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4284. if (!VD) {
  4285. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4286. DeclRefExpr *Ref = buildDeclRefExpr(
  4287. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4288. const DSAStackTy::DSAVarData Data =
  4289. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4290. // If the loop control decl is explicitly marked as private, do not mark it
  4291. // as captured again.
  4292. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4293. Captures.insert(std::make_pair(LCRef, Ref));
  4294. return Ref;
  4295. }
  4296. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  4297. DefaultLoc);
  4298. }
  4299. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4300. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4301. QualType Type = LCDecl->getType().getNonReferenceType();
  4302. VarDecl *PrivateVar = buildVarDecl(
  4303. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4304. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4305. isa<VarDecl>(LCDecl)
  4306. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4307. : nullptr);
  4308. if (PrivateVar->isInvalidDecl())
  4309. return nullptr;
  4310. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4311. }
  4312. return nullptr;
  4313. }
  4314. /// Build initialization of the counter to be used for codegen.
  4315. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4316. /// Build step of the counter be used for codegen.
  4317. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4318. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  4319. Scope *S, Expr *Counter,
  4320. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  4321. Expr *Inc, OverloadedOperatorKind OOK) {
  4322. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  4323. if (!Cnt)
  4324. return nullptr;
  4325. if (Inc) {
  4326. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  4327. "Expected only + or - operations for depend clauses.");
  4328. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  4329. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  4330. if (!Cnt)
  4331. return nullptr;
  4332. }
  4333. ExprResult Diff;
  4334. QualType VarType = LCDecl->getType().getNonReferenceType();
  4335. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4336. SemaRef.getLangOpts().CPlusPlus) {
  4337. // Upper - Lower
  4338. Expr *Upper =
  4339. TestIsLessOp.getValue() ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
  4340. Expr *Lower =
  4341. TestIsLessOp.getValue() ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
  4342. if (!Upper || !Lower)
  4343. return nullptr;
  4344. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4345. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4346. // BuildBinOp already emitted error, this one is to point user to upper
  4347. // and lower bound, and to tell what is passed to 'operator-'.
  4348. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4349. << Upper->getSourceRange() << Lower->getSourceRange();
  4350. return nullptr;
  4351. }
  4352. }
  4353. if (!Diff.isUsable())
  4354. return nullptr;
  4355. // Parentheses (for dumping/debugging purposes only).
  4356. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4357. if (!Diff.isUsable())
  4358. return nullptr;
  4359. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4360. if (!NewStep.isUsable())
  4361. return nullptr;
  4362. // (Upper - Lower) / Step
  4363. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4364. if (!Diff.isUsable())
  4365. return nullptr;
  4366. return Diff.get();
  4367. }
  4368. /// Iteration space of a single for loop.
  4369. struct LoopIterationSpace final {
  4370. /// Condition of the loop.
  4371. Expr *PreCond = nullptr;
  4372. /// This expression calculates the number of iterations in the loop.
  4373. /// It is always possible to calculate it before starting the loop.
  4374. Expr *NumIterations = nullptr;
  4375. /// The loop counter variable.
  4376. Expr *CounterVar = nullptr;
  4377. /// Private loop counter variable.
  4378. Expr *PrivateCounterVar = nullptr;
  4379. /// This is initializer for the initial value of #CounterVar.
  4380. Expr *CounterInit = nullptr;
  4381. /// This is step for the #CounterVar used to generate its update:
  4382. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4383. Expr *CounterStep = nullptr;
  4384. /// Should step be subtracted?
  4385. bool Subtract = false;
  4386. /// Source range of the loop init.
  4387. SourceRange InitSrcRange;
  4388. /// Source range of the loop condition.
  4389. SourceRange CondSrcRange;
  4390. /// Source range of the loop increment.
  4391. SourceRange IncSrcRange;
  4392. };
  4393. } // namespace
  4394. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4395. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4396. assert(Init && "Expected loop in canonical form.");
  4397. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4398. if (AssociatedLoops > 0 &&
  4399. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4400. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4401. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4402. if (ValueDecl *D = ISC.getLoopDecl()) {
  4403. auto *VD = dyn_cast<VarDecl>(D);
  4404. if (!VD) {
  4405. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4406. VD = Private;
  4407. } else {
  4408. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4409. /*WithInit=*/false);
  4410. VD = cast<VarDecl>(Ref->getDecl());
  4411. }
  4412. }
  4413. DSAStack->addLoopControlVariable(D, VD);
  4414. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  4415. if (LD != D->getCanonicalDecl()) {
  4416. DSAStack->resetPossibleLoopCounter();
  4417. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  4418. MarkDeclarationsReferencedInExpr(
  4419. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  4420. Var->getType().getNonLValueExprType(Context),
  4421. ForLoc, /*RefersToCapture=*/true));
  4422. }
  4423. }
  4424. }
  4425. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4426. }
  4427. }
  4428. /// Called on a for stmt to check and extract its iteration space
  4429. /// for further processing (such as collapsing).
  4430. static bool checkOpenMPIterationSpace(
  4431. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4432. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4433. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  4434. Expr *OrderedLoopCountExpr,
  4435. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4436. LoopIterationSpace &ResultIterSpace,
  4437. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4438. // OpenMP [2.6, Canonical Loop Form]
  4439. // for (init-expr; test-expr; incr-expr) structured-block
  4440. auto *For = dyn_cast_or_null<ForStmt>(S);
  4441. if (!For) {
  4442. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  4443. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4444. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  4445. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4446. if (TotalNestedLoopCount > 1) {
  4447. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4448. SemaRef.Diag(DSA.getConstructLoc(),
  4449. diag::note_omp_collapse_ordered_expr)
  4450. << 2 << CollapseLoopCountExpr->getSourceRange()
  4451. << OrderedLoopCountExpr->getSourceRange();
  4452. else if (CollapseLoopCountExpr)
  4453. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4454. diag::note_omp_collapse_ordered_expr)
  4455. << 0 << CollapseLoopCountExpr->getSourceRange();
  4456. else
  4457. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4458. diag::note_omp_collapse_ordered_expr)
  4459. << 1 << OrderedLoopCountExpr->getSourceRange();
  4460. }
  4461. return true;
  4462. }
  4463. assert(For->getBody());
  4464. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4465. // Check init.
  4466. Stmt *Init = For->getInit();
  4467. if (ISC.checkAndSetInit(Init))
  4468. return true;
  4469. bool HasErrors = false;
  4470. // Check loop variable's type.
  4471. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  4472. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  4473. // OpenMP [2.6, Canonical Loop Form]
  4474. // Var is one of the following:
  4475. // A variable of signed or unsigned integer type.
  4476. // For C++, a variable of a random access iterator type.
  4477. // For C, a variable of a pointer type.
  4478. QualType VarType = LCDecl->getType().getNonReferenceType();
  4479. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  4480. !VarType->isPointerType() &&
  4481. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  4482. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  4483. << SemaRef.getLangOpts().CPlusPlus;
  4484. HasErrors = true;
  4485. }
  4486. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  4487. // a Construct
  4488. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4489. // parallel for construct is (are) private.
  4490. // The loop iteration variable in the associated for-loop of a simd
  4491. // construct with just one associated for-loop is linear with a
  4492. // constant-linear-step that is the increment of the associated for-loop.
  4493. // Exclude loop var from the list of variables with implicitly defined data
  4494. // sharing attributes.
  4495. VarsWithImplicitDSA.erase(LCDecl);
  4496. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4497. // in a Construct, C/C++].
  4498. // The loop iteration variable in the associated for-loop of a simd
  4499. // construct with just one associated for-loop may be listed in a linear
  4500. // clause with a constant-linear-step that is the increment of the
  4501. // associated for-loop.
  4502. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4503. // parallel for construct may be listed in a private or lastprivate clause.
  4504. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  4505. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  4506. // declared in the loop and it is predetermined as a private.
  4507. OpenMPClauseKind PredeterminedCKind =
  4508. isOpenMPSimdDirective(DKind)
  4509. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  4510. : OMPC_private;
  4511. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4512. DVar.CKind != PredeterminedCKind) ||
  4513. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  4514. isOpenMPDistributeDirective(DKind)) &&
  4515. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4516. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  4517. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4518. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  4519. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  4520. << getOpenMPClauseName(PredeterminedCKind);
  4521. if (DVar.RefExpr == nullptr)
  4522. DVar.CKind = PredeterminedCKind;
  4523. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  4524. HasErrors = true;
  4525. } else if (LoopDeclRefExpr != nullptr) {
  4526. // Make the loop iteration variable private (for worksharing constructs),
  4527. // linear (for simd directives with the only one associated loop) or
  4528. // lastprivate (for simd directives with several collapsed or ordered
  4529. // loops).
  4530. if (DVar.CKind == OMPC_unknown)
  4531. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  4532. [](OpenMPDirectiveKind) -> bool { return true; },
  4533. /*FromParent=*/false);
  4534. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  4535. }
  4536. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  4537. // Check test-expr.
  4538. HasErrors |= ISC.checkAndSetCond(For->getCond());
  4539. // Check incr-expr.
  4540. HasErrors |= ISC.checkAndSetInc(For->getInc());
  4541. }
  4542. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4543. return HasErrors;
  4544. // Build the loop's iteration space representation.
  4545. ResultIterSpace.PreCond =
  4546. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4547. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  4548. DSA.getCurScope(),
  4549. (isOpenMPWorksharingDirective(DKind) ||
  4550. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4551. Captures);
  4552. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  4553. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  4554. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  4555. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  4556. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  4557. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  4558. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  4559. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  4560. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4561. ResultIterSpace.NumIterations == nullptr ||
  4562. ResultIterSpace.CounterVar == nullptr ||
  4563. ResultIterSpace.PrivateCounterVar == nullptr ||
  4564. ResultIterSpace.CounterInit == nullptr ||
  4565. ResultIterSpace.CounterStep == nullptr);
  4566. if (!HasErrors && DSA.isOrderedRegion()) {
  4567. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  4568. if (CurrentNestedLoopCount <
  4569. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  4570. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  4571. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  4572. DSA.getOrderedRegionParam().second->setLoopCounter(
  4573. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  4574. }
  4575. }
  4576. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  4577. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  4578. // Erroneous case - clause has some problems.
  4579. continue;
  4580. }
  4581. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  4582. Pair.second.size() <= CurrentNestedLoopCount) {
  4583. // Erroneous case - clause has some problems.
  4584. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  4585. continue;
  4586. }
  4587. Expr *CntValue;
  4588. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4589. CntValue = ISC.buildOrderedLoopData(
  4590. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4591. Pair.first->getDependencyLoc());
  4592. else
  4593. CntValue = ISC.buildOrderedLoopData(
  4594. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4595. Pair.first->getDependencyLoc(),
  4596. Pair.second[CurrentNestedLoopCount].first,
  4597. Pair.second[CurrentNestedLoopCount].second);
  4598. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  4599. }
  4600. }
  4601. return HasErrors;
  4602. }
  4603. /// Build 'VarRef = Start.
  4604. static ExprResult
  4605. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4606. ExprResult Start,
  4607. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4608. // Build 'VarRef = Start.
  4609. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4610. if (!NewStart.isUsable())
  4611. return ExprError();
  4612. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4613. VarRef.get()->getType())) {
  4614. NewStart = SemaRef.PerformImplicitConversion(
  4615. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4616. /*AllowExplicit=*/true);
  4617. if (!NewStart.isUsable())
  4618. return ExprError();
  4619. }
  4620. ExprResult Init =
  4621. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4622. return Init;
  4623. }
  4624. /// Build 'VarRef = Start + Iter * Step'.
  4625. static ExprResult buildCounterUpdate(
  4626. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4627. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  4628. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  4629. // Add parentheses (for debugging purposes only).
  4630. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4631. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4632. !Step.isUsable())
  4633. return ExprError();
  4634. ExprResult NewStep = Step;
  4635. if (Captures)
  4636. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4637. if (NewStep.isInvalid())
  4638. return ExprError();
  4639. ExprResult Update =
  4640. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4641. if (!Update.isUsable())
  4642. return ExprError();
  4643. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4644. // 'VarRef = Start (+|-) Iter * Step'.
  4645. ExprResult NewStart = Start;
  4646. if (Captures)
  4647. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4648. if (NewStart.isInvalid())
  4649. return ExprError();
  4650. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4651. ExprResult SavedUpdate = Update;
  4652. ExprResult UpdateVal;
  4653. if (VarRef.get()->getType()->isOverloadableType() ||
  4654. NewStart.get()->getType()->isOverloadableType() ||
  4655. Update.get()->getType()->isOverloadableType()) {
  4656. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4657. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4658. Update =
  4659. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4660. if (Update.isUsable()) {
  4661. UpdateVal =
  4662. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4663. VarRef.get(), SavedUpdate.get());
  4664. if (UpdateVal.isUsable()) {
  4665. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4666. UpdateVal.get());
  4667. }
  4668. }
  4669. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4670. }
  4671. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4672. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4673. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4674. NewStart.get(), SavedUpdate.get());
  4675. if (!Update.isUsable())
  4676. return ExprError();
  4677. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4678. VarRef.get()->getType())) {
  4679. Update = SemaRef.PerformImplicitConversion(
  4680. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4681. if (!Update.isUsable())
  4682. return ExprError();
  4683. }
  4684. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4685. }
  4686. return Update;
  4687. }
  4688. /// Convert integer expression \a E to make it have at least \a Bits
  4689. /// bits.
  4690. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4691. if (E == nullptr)
  4692. return ExprError();
  4693. ASTContext &C = SemaRef.Context;
  4694. QualType OldType = E->getType();
  4695. unsigned HasBits = C.getTypeSize(OldType);
  4696. if (HasBits >= Bits)
  4697. return ExprResult(E);
  4698. // OK to convert to signed, because new type has more bits than old.
  4699. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4700. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4701. true);
  4702. }
  4703. /// Check if the given expression \a E is a constant integer that fits
  4704. /// into \a Bits bits.
  4705. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  4706. if (E == nullptr)
  4707. return false;
  4708. llvm::APSInt Result;
  4709. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4710. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4711. return false;
  4712. }
  4713. /// Build preinits statement for the given declarations.
  4714. static Stmt *buildPreInits(ASTContext &Context,
  4715. MutableArrayRef<Decl *> PreInits) {
  4716. if (!PreInits.empty()) {
  4717. return new (Context) DeclStmt(
  4718. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4719. SourceLocation(), SourceLocation());
  4720. }
  4721. return nullptr;
  4722. }
  4723. /// Build preinits statement for the given declarations.
  4724. static Stmt *
  4725. buildPreInits(ASTContext &Context,
  4726. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4727. if (!Captures.empty()) {
  4728. SmallVector<Decl *, 16> PreInits;
  4729. for (const auto &Pair : Captures)
  4730. PreInits.push_back(Pair.second->getDecl());
  4731. return buildPreInits(Context, PreInits);
  4732. }
  4733. return nullptr;
  4734. }
  4735. /// Build postupdate expression for the given list of postupdates expressions.
  4736. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4737. Expr *PostUpdate = nullptr;
  4738. if (!PostUpdates.empty()) {
  4739. for (Expr *E : PostUpdates) {
  4740. Expr *ConvE = S.BuildCStyleCastExpr(
  4741. E->getExprLoc(),
  4742. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4743. E->getExprLoc(), E)
  4744. .get();
  4745. PostUpdate = PostUpdate
  4746. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4747. PostUpdate, ConvE)
  4748. .get()
  4749. : ConvE;
  4750. }
  4751. }
  4752. return PostUpdate;
  4753. }
  4754. /// Called on a for stmt to check itself and nested loops (if any).
  4755. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4756. /// number of collapsed loops otherwise.
  4757. static unsigned
  4758. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4759. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4760. DSAStackTy &DSA,
  4761. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4762. OMPLoopDirective::HelperExprs &Built) {
  4763. unsigned NestedLoopCount = 1;
  4764. if (CollapseLoopCountExpr) {
  4765. // Found 'collapse' clause - calculate collapse number.
  4766. llvm::APSInt Result;
  4767. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4768. NestedLoopCount = Result.getLimitedValue();
  4769. }
  4770. unsigned OrderedLoopCount = 1;
  4771. if (OrderedLoopCountExpr) {
  4772. // Found 'ordered' clause - calculate collapse number.
  4773. llvm::APSInt Result;
  4774. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4775. if (Result.getLimitedValue() < NestedLoopCount) {
  4776. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4777. diag::err_omp_wrong_ordered_loop_count)
  4778. << OrderedLoopCountExpr->getSourceRange();
  4779. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4780. diag::note_collapse_loop_count)
  4781. << CollapseLoopCountExpr->getSourceRange();
  4782. }
  4783. OrderedLoopCount = Result.getLimitedValue();
  4784. }
  4785. }
  4786. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4787. // 'for simd', etc.).
  4788. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  4789. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4790. IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
  4791. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4792. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4793. if (checkOpenMPIterationSpace(
  4794. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4795. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4796. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4797. Captures))
  4798. return 0;
  4799. // Move on to the next nested for loop, or to the loop body.
  4800. // OpenMP [2.8.1, simd construct, Restrictions]
  4801. // All loops associated with the construct must be perfectly nested; that
  4802. // is, there must be no intervening code nor any OpenMP directive between
  4803. // any two loops.
  4804. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4805. }
  4806. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  4807. if (checkOpenMPIterationSpace(
  4808. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4809. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4810. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4811. Captures))
  4812. return 0;
  4813. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  4814. // Handle initialization of captured loop iterator variables.
  4815. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  4816. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  4817. Captures[DRE] = DRE;
  4818. }
  4819. }
  4820. // Move on to the next nested for loop, or to the loop body.
  4821. // OpenMP [2.8.1, simd construct, Restrictions]
  4822. // All loops associated with the construct must be perfectly nested; that
  4823. // is, there must be no intervening code nor any OpenMP directive between
  4824. // any two loops.
  4825. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4826. }
  4827. Built.clear(/* size */ NestedLoopCount);
  4828. if (SemaRef.CurContext->isDependentContext())
  4829. return NestedLoopCount;
  4830. // An example of what is generated for the following code:
  4831. //
  4832. // #pragma omp simd collapse(2) ordered(2)
  4833. // for (i = 0; i < NI; ++i)
  4834. // for (k = 0; k < NK; ++k)
  4835. // for (j = J0; j < NJ; j+=2) {
  4836. // <loop body>
  4837. // }
  4838. //
  4839. // We generate the code below.
  4840. // Note: the loop body may be outlined in CodeGen.
  4841. // Note: some counters may be C++ classes, operator- is used to find number of
  4842. // iterations and operator+= to calculate counter value.
  4843. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4844. // or i64 is currently supported).
  4845. //
  4846. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4847. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4848. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4849. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4850. // // similar updates for vars in clauses (e.g. 'linear')
  4851. // <loop body (using local i and j)>
  4852. // }
  4853. // i = NI; // assign final values of counters
  4854. // j = NJ;
  4855. //
  4856. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4857. // the iteration counts of the collapsed for loops.
  4858. // Precondition tests if there is at least one iteration (all conditions are
  4859. // true).
  4860. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4861. Expr *N0 = IterSpaces[0].NumIterations;
  4862. ExprResult LastIteration32 =
  4863. widenIterationCount(/*Bits=*/32,
  4864. SemaRef
  4865. .PerformImplicitConversion(
  4866. N0->IgnoreImpCasts(), N0->getType(),
  4867. Sema::AA_Converting, /*AllowExplicit=*/true)
  4868. .get(),
  4869. SemaRef);
  4870. ExprResult LastIteration64 = widenIterationCount(
  4871. /*Bits=*/64,
  4872. SemaRef
  4873. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  4874. Sema::AA_Converting,
  4875. /*AllowExplicit=*/true)
  4876. .get(),
  4877. SemaRef);
  4878. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4879. return NestedLoopCount;
  4880. ASTContext &C = SemaRef.Context;
  4881. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4882. Scope *CurScope = DSA.getCurScope();
  4883. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4884. if (PreCond.isUsable()) {
  4885. PreCond =
  4886. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4887. PreCond.get(), IterSpaces[Cnt].PreCond);
  4888. }
  4889. Expr *N = IterSpaces[Cnt].NumIterations;
  4890. SourceLocation Loc = N->getExprLoc();
  4891. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4892. if (LastIteration32.isUsable())
  4893. LastIteration32 = SemaRef.BuildBinOp(
  4894. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4895. SemaRef
  4896. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4897. Sema::AA_Converting,
  4898. /*AllowExplicit=*/true)
  4899. .get());
  4900. if (LastIteration64.isUsable())
  4901. LastIteration64 = SemaRef.BuildBinOp(
  4902. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4903. SemaRef
  4904. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4905. Sema::AA_Converting,
  4906. /*AllowExplicit=*/true)
  4907. .get());
  4908. }
  4909. // Choose either the 32-bit or 64-bit version.
  4910. ExprResult LastIteration = LastIteration64;
  4911. if (LastIteration32.isUsable() &&
  4912. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4913. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4914. fitsInto(
  4915. /*Bits=*/32,
  4916. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4917. LastIteration64.get(), SemaRef)))
  4918. LastIteration = LastIteration32;
  4919. QualType VType = LastIteration.get()->getType();
  4920. QualType RealVType = VType;
  4921. QualType StrideVType = VType;
  4922. if (isOpenMPTaskLoopDirective(DKind)) {
  4923. VType =
  4924. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4925. StrideVType =
  4926. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4927. }
  4928. if (!LastIteration.isUsable())
  4929. return 0;
  4930. // Save the number of iterations.
  4931. ExprResult NumIterations = LastIteration;
  4932. {
  4933. LastIteration = SemaRef.BuildBinOp(
  4934. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4935. LastIteration.get(),
  4936. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4937. if (!LastIteration.isUsable())
  4938. return 0;
  4939. }
  4940. // Calculate the last iteration number beforehand instead of doing this on
  4941. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4942. llvm::APSInt Result;
  4943. bool IsConstant =
  4944. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4945. ExprResult CalcLastIteration;
  4946. if (!IsConstant) {
  4947. ExprResult SaveRef =
  4948. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4949. LastIteration = SaveRef;
  4950. // Prepare SaveRef + 1.
  4951. NumIterations = SemaRef.BuildBinOp(
  4952. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4953. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4954. if (!NumIterations.isUsable())
  4955. return 0;
  4956. }
  4957. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4958. // Build variables passed into runtime, necessary for worksharing directives.
  4959. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4960. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4961. isOpenMPDistributeDirective(DKind)) {
  4962. // Lower bound variable, initialized with zero.
  4963. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4964. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4965. SemaRef.AddInitializerToDecl(LBDecl,
  4966. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4967. /*DirectInit*/ false);
  4968. // Upper bound variable, initialized with last iteration number.
  4969. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4970. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4971. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4972. /*DirectInit*/ false);
  4973. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4974. // This will be used to implement clause 'lastprivate'.
  4975. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4976. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4977. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4978. SemaRef.AddInitializerToDecl(ILDecl,
  4979. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4980. /*DirectInit*/ false);
  4981. // Stride variable returned by runtime (we initialize it to 1 by default).
  4982. VarDecl *STDecl =
  4983. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4984. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4985. SemaRef.AddInitializerToDecl(STDecl,
  4986. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4987. /*DirectInit*/ false);
  4988. // Build expression: UB = min(UB, LastIteration)
  4989. // It is necessary for CodeGen of directives with static scheduling.
  4990. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4991. UB.get(), LastIteration.get());
  4992. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4993. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  4994. LastIteration.get(), UB.get());
  4995. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4996. CondOp.get());
  4997. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4998. // If we have a combined directive that combines 'distribute', 'for' or
  4999. // 'simd' we need to be able to access the bounds of the schedule of the
  5000. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  5001. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  5002. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5003. // Lower bound variable, initialized with zero.
  5004. VarDecl *CombLBDecl =
  5005. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  5006. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  5007. SemaRef.AddInitializerToDecl(
  5008. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5009. /*DirectInit*/ false);
  5010. // Upper bound variable, initialized with last iteration number.
  5011. VarDecl *CombUBDecl =
  5012. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  5013. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  5014. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  5015. /*DirectInit*/ false);
  5016. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  5017. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  5018. ExprResult CombCondOp =
  5019. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  5020. LastIteration.get(), CombUB.get());
  5021. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  5022. CombCondOp.get());
  5023. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  5024. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  5025. // We expect to have at least 2 more parameters than the 'parallel'
  5026. // directive does - the lower and upper bounds of the previous schedule.
  5027. assert(CD->getNumParams() >= 4 &&
  5028. "Unexpected number of parameters in loop combined directive");
  5029. // Set the proper type for the bounds given what we learned from the
  5030. // enclosed loops.
  5031. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  5032. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  5033. // Previous lower and upper bounds are obtained from the region
  5034. // parameters.
  5035. PrevLB =
  5036. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5037. PrevUB =
  5038. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5039. }
  5040. }
  5041. // Build the iteration variable and its initialization before loop.
  5042. ExprResult IV;
  5043. ExprResult Init, CombInit;
  5044. {
  5045. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5046. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5047. Expr *RHS =
  5048. (isOpenMPWorksharingDirective(DKind) ||
  5049. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5050. ? LB.get()
  5051. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5052. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5053. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  5054. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5055. Expr *CombRHS =
  5056. (isOpenMPWorksharingDirective(DKind) ||
  5057. isOpenMPTaskLoopDirective(DKind) ||
  5058. isOpenMPDistributeDirective(DKind))
  5059. ? CombLB.get()
  5060. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5061. CombInit =
  5062. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5063. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  5064. }
  5065. }
  5066. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  5067. SourceLocation CondLoc = AStmt->getBeginLoc();
  5068. ExprResult Cond =
  5069. (isOpenMPWorksharingDirective(DKind) ||
  5070. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5071. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  5072. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5073. NumIterations.get());
  5074. ExprResult CombDistCond;
  5075. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5076. CombDistCond =
  5077. SemaRef.BuildBinOp(
  5078. CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
  5079. }
  5080. ExprResult CombCond;
  5081. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5082. CombCond =
  5083. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  5084. }
  5085. // Loop increment (IV = IV + 1)
  5086. SourceLocation IncLoc = AStmt->getBeginLoc();
  5087. ExprResult Inc =
  5088. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  5089. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  5090. if (!Inc.isUsable())
  5091. return 0;
  5092. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  5093. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  5094. if (!Inc.isUsable())
  5095. return 0;
  5096. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  5097. // Used for directives with static scheduling.
  5098. // In combined construct, add combined version that use CombLB and CombUB
  5099. // base variables for the update
  5100. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  5101. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5102. isOpenMPDistributeDirective(DKind)) {
  5103. // LB + ST
  5104. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  5105. if (!NextLB.isUsable())
  5106. return 0;
  5107. // LB = LB + ST
  5108. NextLB =
  5109. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  5110. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  5111. if (!NextLB.isUsable())
  5112. return 0;
  5113. // UB + ST
  5114. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  5115. if (!NextUB.isUsable())
  5116. return 0;
  5117. // UB = UB + ST
  5118. NextUB =
  5119. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  5120. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  5121. if (!NextUB.isUsable())
  5122. return 0;
  5123. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5124. CombNextLB =
  5125. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  5126. if (!NextLB.isUsable())
  5127. return 0;
  5128. // LB = LB + ST
  5129. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  5130. CombNextLB.get());
  5131. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  5132. if (!CombNextLB.isUsable())
  5133. return 0;
  5134. // UB + ST
  5135. CombNextUB =
  5136. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  5137. if (!CombNextUB.isUsable())
  5138. return 0;
  5139. // UB = UB + ST
  5140. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  5141. CombNextUB.get());
  5142. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  5143. if (!CombNextUB.isUsable())
  5144. return 0;
  5145. }
  5146. }
  5147. // Create increment expression for distribute loop when combined in a same
  5148. // directive with for as IV = IV + ST; ensure upper bound expression based
  5149. // on PrevUB instead of NumIterations - used to implement 'for' when found
  5150. // in combination with 'distribute', like in 'distribute parallel for'
  5151. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  5152. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  5153. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5154. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  5155. assert(DistCond.isUsable() && "distribute cond expr was not built");
  5156. DistInc =
  5157. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  5158. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5159. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  5160. DistInc.get());
  5161. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  5162. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5163. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  5164. // construct
  5165. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  5166. ExprResult IsUBGreater =
  5167. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  5168. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5169. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  5170. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  5171. CondOp.get());
  5172. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  5173. // Build IV <= PrevUB to be used in parallel for is in combination with
  5174. // a distribute directive with schedule(static, 1)
  5175. ParForInDistCond =
  5176. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
  5177. }
  5178. // Build updates and final values of the loop counters.
  5179. bool HasErrors = false;
  5180. Built.Counters.resize(NestedLoopCount);
  5181. Built.Inits.resize(NestedLoopCount);
  5182. Built.Updates.resize(NestedLoopCount);
  5183. Built.Finals.resize(NestedLoopCount);
  5184. {
  5185. ExprResult Div;
  5186. // Go from inner nested loop to outer.
  5187. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  5188. LoopIterationSpace &IS = IterSpaces[Cnt];
  5189. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  5190. // Build: Iter = (IV / Div) % IS.NumIters
  5191. // where Div is product of previous iterations' IS.NumIters.
  5192. ExprResult Iter;
  5193. if (Div.isUsable()) {
  5194. Iter =
  5195. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  5196. } else {
  5197. Iter = IV;
  5198. assert((Cnt == (int)NestedLoopCount - 1) &&
  5199. "unusable div expected on first iteration only");
  5200. }
  5201. if (Cnt != 0 && Iter.isUsable())
  5202. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  5203. IS.NumIterations);
  5204. if (!Iter.isUsable()) {
  5205. HasErrors = true;
  5206. break;
  5207. }
  5208. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  5209. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  5210. DeclRefExpr *CounterVar = buildDeclRefExpr(
  5211. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  5212. /*RefersToCapture=*/true);
  5213. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  5214. IS.CounterInit, Captures);
  5215. if (!Init.isUsable()) {
  5216. HasErrors = true;
  5217. break;
  5218. }
  5219. ExprResult Update = buildCounterUpdate(
  5220. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  5221. IS.CounterStep, IS.Subtract, &Captures);
  5222. if (!Update.isUsable()) {
  5223. HasErrors = true;
  5224. break;
  5225. }
  5226. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  5227. ExprResult Final = buildCounterUpdate(
  5228. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  5229. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  5230. if (!Final.isUsable()) {
  5231. HasErrors = true;
  5232. break;
  5233. }
  5234. // Build Div for the next iteration: Div <- Div * IS.NumIters
  5235. if (Cnt != 0) {
  5236. if (Div.isUnset())
  5237. Div = IS.NumIterations;
  5238. else
  5239. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  5240. IS.NumIterations);
  5241. // Add parentheses (for debugging purposes only).
  5242. if (Div.isUsable())
  5243. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  5244. if (!Div.isUsable()) {
  5245. HasErrors = true;
  5246. break;
  5247. }
  5248. }
  5249. if (!Update.isUsable() || !Final.isUsable()) {
  5250. HasErrors = true;
  5251. break;
  5252. }
  5253. // Save results
  5254. Built.Counters[Cnt] = IS.CounterVar;
  5255. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  5256. Built.Inits[Cnt] = Init.get();
  5257. Built.Updates[Cnt] = Update.get();
  5258. Built.Finals[Cnt] = Final.get();
  5259. }
  5260. }
  5261. if (HasErrors)
  5262. return 0;
  5263. // Save results
  5264. Built.IterationVarRef = IV.get();
  5265. Built.LastIteration = LastIteration.get();
  5266. Built.NumIterations = NumIterations.get();
  5267. Built.CalcLastIteration =
  5268. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  5269. Built.PreCond = PreCond.get();
  5270. Built.PreInits = buildPreInits(C, Captures);
  5271. Built.Cond = Cond.get();
  5272. Built.Init = Init.get();
  5273. Built.Inc = Inc.get();
  5274. Built.LB = LB.get();
  5275. Built.UB = UB.get();
  5276. Built.IL = IL.get();
  5277. Built.ST = ST.get();
  5278. Built.EUB = EUB.get();
  5279. Built.NLB = NextLB.get();
  5280. Built.NUB = NextUB.get();
  5281. Built.PrevLB = PrevLB.get();
  5282. Built.PrevUB = PrevUB.get();
  5283. Built.DistInc = DistInc.get();
  5284. Built.PrevEUB = PrevEUB.get();
  5285. Built.DistCombinedFields.LB = CombLB.get();
  5286. Built.DistCombinedFields.UB = CombUB.get();
  5287. Built.DistCombinedFields.EUB = CombEUB.get();
  5288. Built.DistCombinedFields.Init = CombInit.get();
  5289. Built.DistCombinedFields.Cond = CombCond.get();
  5290. Built.DistCombinedFields.NLB = CombNextLB.get();
  5291. Built.DistCombinedFields.NUB = CombNextUB.get();
  5292. Built.DistCombinedFields.DistCond = CombDistCond.get();
  5293. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  5294. return NestedLoopCount;
  5295. }
  5296. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5297. auto CollapseClauses =
  5298. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  5299. if (CollapseClauses.begin() != CollapseClauses.end())
  5300. return (*CollapseClauses.begin())->getNumForLoops();
  5301. return nullptr;
  5302. }
  5303. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5304. auto OrderedClauses =
  5305. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  5306. if (OrderedClauses.begin() != OrderedClauses.end())
  5307. return (*OrderedClauses.begin())->getNumForLoops();
  5308. return nullptr;
  5309. }
  5310. static bool checkSimdlenSafelenSpecified(Sema &S,
  5311. const ArrayRef<OMPClause *> Clauses) {
  5312. const OMPSafelenClause *Safelen = nullptr;
  5313. const OMPSimdlenClause *Simdlen = nullptr;
  5314. for (const OMPClause *Clause : Clauses) {
  5315. if (Clause->getClauseKind() == OMPC_safelen)
  5316. Safelen = cast<OMPSafelenClause>(Clause);
  5317. else if (Clause->getClauseKind() == OMPC_simdlen)
  5318. Simdlen = cast<OMPSimdlenClause>(Clause);
  5319. if (Safelen && Simdlen)
  5320. break;
  5321. }
  5322. if (Simdlen && Safelen) {
  5323. llvm::APSInt SimdlenRes, SafelenRes;
  5324. const Expr *SimdlenLength = Simdlen->getSimdlen();
  5325. const Expr *SafelenLength = Safelen->getSafelen();
  5326. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  5327. SimdlenLength->isInstantiationDependent() ||
  5328. SimdlenLength->containsUnexpandedParameterPack())
  5329. return false;
  5330. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  5331. SafelenLength->isInstantiationDependent() ||
  5332. SafelenLength->containsUnexpandedParameterPack())
  5333. return false;
  5334. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  5335. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  5336. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5337. // If both simdlen and safelen clauses are specified, the value of the
  5338. // simdlen parameter must be less than or equal to the value of the safelen
  5339. // parameter.
  5340. if (SimdlenRes > SafelenRes) {
  5341. S.Diag(SimdlenLength->getExprLoc(),
  5342. diag::err_omp_wrong_simdlen_safelen_values)
  5343. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5344. return true;
  5345. }
  5346. }
  5347. return false;
  5348. }
  5349. StmtResult
  5350. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5351. SourceLocation StartLoc, SourceLocation EndLoc,
  5352. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5353. if (!AStmt)
  5354. return StmtError();
  5355. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5356. OMPLoopDirective::HelperExprs B;
  5357. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5358. // define the nested loops number.
  5359. unsigned NestedLoopCount = checkOpenMPLoop(
  5360. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5361. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5362. if (NestedLoopCount == 0)
  5363. return StmtError();
  5364. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5365. "omp simd loop exprs were not built");
  5366. if (!CurContext->isDependentContext()) {
  5367. // Finalize the clauses that need pre-built expressions for CodeGen.
  5368. for (OMPClause *C : Clauses) {
  5369. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5370. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5371. B.NumIterations, *this, CurScope,
  5372. DSAStack))
  5373. return StmtError();
  5374. }
  5375. }
  5376. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5377. return StmtError();
  5378. setFunctionHasBranchProtectedScope();
  5379. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5380. Clauses, AStmt, B);
  5381. }
  5382. StmtResult
  5383. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5384. SourceLocation StartLoc, SourceLocation EndLoc,
  5385. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5386. if (!AStmt)
  5387. return StmtError();
  5388. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5389. OMPLoopDirective::HelperExprs B;
  5390. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5391. // define the nested loops number.
  5392. unsigned NestedLoopCount = checkOpenMPLoop(
  5393. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5394. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5395. if (NestedLoopCount == 0)
  5396. return StmtError();
  5397. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5398. "omp for loop exprs were not built");
  5399. if (!CurContext->isDependentContext()) {
  5400. // Finalize the clauses that need pre-built expressions for CodeGen.
  5401. for (OMPClause *C : Clauses) {
  5402. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5403. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5404. B.NumIterations, *this, CurScope,
  5405. DSAStack))
  5406. return StmtError();
  5407. }
  5408. }
  5409. setFunctionHasBranchProtectedScope();
  5410. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5411. Clauses, AStmt, B, DSAStack->isCancelRegion());
  5412. }
  5413. StmtResult Sema::ActOnOpenMPForSimdDirective(
  5414. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5415. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5416. if (!AStmt)
  5417. return StmtError();
  5418. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5419. OMPLoopDirective::HelperExprs B;
  5420. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5421. // define the nested loops number.
  5422. unsigned NestedLoopCount =
  5423. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  5424. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5425. VarsWithImplicitDSA, B);
  5426. if (NestedLoopCount == 0)
  5427. return StmtError();
  5428. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5429. "omp for simd loop exprs were not built");
  5430. if (!CurContext->isDependentContext()) {
  5431. // Finalize the clauses that need pre-built expressions for CodeGen.
  5432. for (OMPClause *C : Clauses) {
  5433. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5434. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5435. B.NumIterations, *this, CurScope,
  5436. DSAStack))
  5437. return StmtError();
  5438. }
  5439. }
  5440. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5441. return StmtError();
  5442. setFunctionHasBranchProtectedScope();
  5443. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5444. Clauses, AStmt, B);
  5445. }
  5446. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5447. Stmt *AStmt,
  5448. SourceLocation StartLoc,
  5449. SourceLocation EndLoc) {
  5450. if (!AStmt)
  5451. return StmtError();
  5452. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5453. auto BaseStmt = AStmt;
  5454. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5455. BaseStmt = CS->getCapturedStmt();
  5456. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5457. auto S = C->children();
  5458. if (S.begin() == S.end())
  5459. return StmtError();
  5460. // All associated statements must be '#pragma omp section' except for
  5461. // the first one.
  5462. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5463. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5464. if (SectionStmt)
  5465. Diag(SectionStmt->getBeginLoc(),
  5466. diag::err_omp_sections_substmt_not_section);
  5467. return StmtError();
  5468. }
  5469. cast<OMPSectionDirective>(SectionStmt)
  5470. ->setHasCancel(DSAStack->isCancelRegion());
  5471. }
  5472. } else {
  5473. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  5474. return StmtError();
  5475. }
  5476. setFunctionHasBranchProtectedScope();
  5477. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5478. DSAStack->isCancelRegion());
  5479. }
  5480. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  5481. SourceLocation StartLoc,
  5482. SourceLocation EndLoc) {
  5483. if (!AStmt)
  5484. return StmtError();
  5485. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5486. setFunctionHasBranchProtectedScope();
  5487. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  5488. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  5489. DSAStack->isCancelRegion());
  5490. }
  5491. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  5492. Stmt *AStmt,
  5493. SourceLocation StartLoc,
  5494. SourceLocation EndLoc) {
  5495. if (!AStmt)
  5496. return StmtError();
  5497. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5498. setFunctionHasBranchProtectedScope();
  5499. // OpenMP [2.7.3, single Construct, Restrictions]
  5500. // The copyprivate clause must not be used with the nowait clause.
  5501. const OMPClause *Nowait = nullptr;
  5502. const OMPClause *Copyprivate = nullptr;
  5503. for (const OMPClause *Clause : Clauses) {
  5504. if (Clause->getClauseKind() == OMPC_nowait)
  5505. Nowait = Clause;
  5506. else if (Clause->getClauseKind() == OMPC_copyprivate)
  5507. Copyprivate = Clause;
  5508. if (Copyprivate && Nowait) {
  5509. Diag(Copyprivate->getBeginLoc(),
  5510. diag::err_omp_single_copyprivate_with_nowait);
  5511. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  5512. return StmtError();
  5513. }
  5514. }
  5515. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5516. }
  5517. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  5518. SourceLocation StartLoc,
  5519. SourceLocation EndLoc) {
  5520. if (!AStmt)
  5521. return StmtError();
  5522. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5523. setFunctionHasBranchProtectedScope();
  5524. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  5525. }
  5526. StmtResult Sema::ActOnOpenMPCriticalDirective(
  5527. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  5528. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5529. if (!AStmt)
  5530. return StmtError();
  5531. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5532. bool ErrorFound = false;
  5533. llvm::APSInt Hint;
  5534. SourceLocation HintLoc;
  5535. bool DependentHint = false;
  5536. for (const OMPClause *C : Clauses) {
  5537. if (C->getClauseKind() == OMPC_hint) {
  5538. if (!DirName.getName()) {
  5539. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  5540. ErrorFound = true;
  5541. }
  5542. Expr *E = cast<OMPHintClause>(C)->getHint();
  5543. if (E->isTypeDependent() || E->isValueDependent() ||
  5544. E->isInstantiationDependent()) {
  5545. DependentHint = true;
  5546. } else {
  5547. Hint = E->EvaluateKnownConstInt(Context);
  5548. HintLoc = C->getBeginLoc();
  5549. }
  5550. }
  5551. }
  5552. if (ErrorFound)
  5553. return StmtError();
  5554. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  5555. if (Pair.first && DirName.getName() && !DependentHint) {
  5556. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  5557. Diag(StartLoc, diag::err_omp_critical_with_hint);
  5558. if (HintLoc.isValid())
  5559. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5560. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5561. else
  5562. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5563. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5564. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  5565. << 1
  5566. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5567. /*Radix=*/10, /*Signed=*/false);
  5568. } else {
  5569. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  5570. }
  5571. }
  5572. }
  5573. setFunctionHasBranchProtectedScope();
  5574. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5575. Clauses, AStmt);
  5576. if (!Pair.first && DirName.getName() && !DependentHint)
  5577. DSAStack->addCriticalWithHint(Dir, Hint);
  5578. return Dir;
  5579. }
  5580. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5581. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5582. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5583. if (!AStmt)
  5584. return StmtError();
  5585. auto *CS = cast<CapturedStmt>(AStmt);
  5586. // 1.2.2 OpenMP Language Terminology
  5587. // Structured block - An executable statement with a single entry at the
  5588. // top and a single exit at the bottom.
  5589. // The point of exit cannot be a branch out of the structured block.
  5590. // longjmp() and throw() must not violate the entry/exit criteria.
  5591. CS->getCapturedDecl()->setNothrow();
  5592. OMPLoopDirective::HelperExprs B;
  5593. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5594. // define the nested loops number.
  5595. unsigned NestedLoopCount =
  5596. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5597. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5598. VarsWithImplicitDSA, B);
  5599. if (NestedLoopCount == 0)
  5600. return StmtError();
  5601. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5602. "omp parallel for loop exprs were not built");
  5603. if (!CurContext->isDependentContext()) {
  5604. // Finalize the clauses that need pre-built expressions for CodeGen.
  5605. for (OMPClause *C : Clauses) {
  5606. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5607. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5608. B.NumIterations, *this, CurScope,
  5609. DSAStack))
  5610. return StmtError();
  5611. }
  5612. }
  5613. setFunctionHasBranchProtectedScope();
  5614. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5615. NestedLoopCount, Clauses, AStmt, B,
  5616. DSAStack->isCancelRegion());
  5617. }
  5618. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5619. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5620. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5621. if (!AStmt)
  5622. return StmtError();
  5623. auto *CS = cast<CapturedStmt>(AStmt);
  5624. // 1.2.2 OpenMP Language Terminology
  5625. // Structured block - An executable statement with a single entry at the
  5626. // top and a single exit at the bottom.
  5627. // The point of exit cannot be a branch out of the structured block.
  5628. // longjmp() and throw() must not violate the entry/exit criteria.
  5629. CS->getCapturedDecl()->setNothrow();
  5630. OMPLoopDirective::HelperExprs B;
  5631. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5632. // define the nested loops number.
  5633. unsigned NestedLoopCount =
  5634. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5635. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5636. VarsWithImplicitDSA, B);
  5637. if (NestedLoopCount == 0)
  5638. return StmtError();
  5639. if (!CurContext->isDependentContext()) {
  5640. // Finalize the clauses that need pre-built expressions for CodeGen.
  5641. for (OMPClause *C : Clauses) {
  5642. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5643. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5644. B.NumIterations, *this, CurScope,
  5645. DSAStack))
  5646. return StmtError();
  5647. }
  5648. }
  5649. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5650. return StmtError();
  5651. setFunctionHasBranchProtectedScope();
  5652. return OMPParallelForSimdDirective::Create(
  5653. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5654. }
  5655. StmtResult
  5656. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5657. Stmt *AStmt, SourceLocation StartLoc,
  5658. SourceLocation EndLoc) {
  5659. if (!AStmt)
  5660. return StmtError();
  5661. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5662. auto BaseStmt = AStmt;
  5663. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5664. BaseStmt = CS->getCapturedStmt();
  5665. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5666. auto S = C->children();
  5667. if (S.begin() == S.end())
  5668. return StmtError();
  5669. // All associated statements must be '#pragma omp section' except for
  5670. // the first one.
  5671. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5672. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5673. if (SectionStmt)
  5674. Diag(SectionStmt->getBeginLoc(),
  5675. diag::err_omp_parallel_sections_substmt_not_section);
  5676. return StmtError();
  5677. }
  5678. cast<OMPSectionDirective>(SectionStmt)
  5679. ->setHasCancel(DSAStack->isCancelRegion());
  5680. }
  5681. } else {
  5682. Diag(AStmt->getBeginLoc(),
  5683. diag::err_omp_parallel_sections_not_compound_stmt);
  5684. return StmtError();
  5685. }
  5686. setFunctionHasBranchProtectedScope();
  5687. return OMPParallelSectionsDirective::Create(
  5688. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5689. }
  5690. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5691. Stmt *AStmt, SourceLocation StartLoc,
  5692. SourceLocation EndLoc) {
  5693. if (!AStmt)
  5694. return StmtError();
  5695. auto *CS = cast<CapturedStmt>(AStmt);
  5696. // 1.2.2 OpenMP Language Terminology
  5697. // Structured block - An executable statement with a single entry at the
  5698. // top and a single exit at the bottom.
  5699. // The point of exit cannot be a branch out of the structured block.
  5700. // longjmp() and throw() must not violate the entry/exit criteria.
  5701. CS->getCapturedDecl()->setNothrow();
  5702. setFunctionHasBranchProtectedScope();
  5703. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5704. DSAStack->isCancelRegion());
  5705. }
  5706. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5707. SourceLocation EndLoc) {
  5708. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5709. }
  5710. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5711. SourceLocation EndLoc) {
  5712. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5713. }
  5714. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5715. SourceLocation EndLoc) {
  5716. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5717. }
  5718. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5719. Stmt *AStmt,
  5720. SourceLocation StartLoc,
  5721. SourceLocation EndLoc) {
  5722. if (!AStmt)
  5723. return StmtError();
  5724. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5725. setFunctionHasBranchProtectedScope();
  5726. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5727. AStmt,
  5728. DSAStack->getTaskgroupReductionRef());
  5729. }
  5730. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5731. SourceLocation StartLoc,
  5732. SourceLocation EndLoc) {
  5733. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5734. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5735. }
  5736. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5737. Stmt *AStmt,
  5738. SourceLocation StartLoc,
  5739. SourceLocation EndLoc) {
  5740. const OMPClause *DependFound = nullptr;
  5741. const OMPClause *DependSourceClause = nullptr;
  5742. const OMPClause *DependSinkClause = nullptr;
  5743. bool ErrorFound = false;
  5744. const OMPThreadsClause *TC = nullptr;
  5745. const OMPSIMDClause *SC = nullptr;
  5746. for (const OMPClause *C : Clauses) {
  5747. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5748. DependFound = C;
  5749. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5750. if (DependSourceClause) {
  5751. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  5752. << getOpenMPDirectiveName(OMPD_ordered)
  5753. << getOpenMPClauseName(OMPC_depend) << 2;
  5754. ErrorFound = true;
  5755. } else {
  5756. DependSourceClause = C;
  5757. }
  5758. if (DependSinkClause) {
  5759. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5760. << 0;
  5761. ErrorFound = true;
  5762. }
  5763. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5764. if (DependSourceClause) {
  5765. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5766. << 1;
  5767. ErrorFound = true;
  5768. }
  5769. DependSinkClause = C;
  5770. }
  5771. } else if (C->getClauseKind() == OMPC_threads) {
  5772. TC = cast<OMPThreadsClause>(C);
  5773. } else if (C->getClauseKind() == OMPC_simd) {
  5774. SC = cast<OMPSIMDClause>(C);
  5775. }
  5776. }
  5777. if (!ErrorFound && !SC &&
  5778. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5779. // OpenMP [2.8.1,simd Construct, Restrictions]
  5780. // An ordered construct with the simd clause is the only OpenMP construct
  5781. // that can appear in the simd region.
  5782. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5783. ErrorFound = true;
  5784. } else if (DependFound && (TC || SC)) {
  5785. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  5786. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5787. ErrorFound = true;
  5788. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  5789. Diag(DependFound->getBeginLoc(),
  5790. diag::err_omp_ordered_directive_without_param);
  5791. ErrorFound = true;
  5792. } else if (TC || Clauses.empty()) {
  5793. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  5794. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  5795. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5796. << (TC != nullptr);
  5797. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  5798. ErrorFound = true;
  5799. }
  5800. }
  5801. if ((!AStmt && !DependFound) || ErrorFound)
  5802. return StmtError();
  5803. if (AStmt) {
  5804. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5805. setFunctionHasBranchProtectedScope();
  5806. }
  5807. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5808. }
  5809. namespace {
  5810. /// Helper class for checking expression in 'omp atomic [update]'
  5811. /// construct.
  5812. class OpenMPAtomicUpdateChecker {
  5813. /// Error results for atomic update expressions.
  5814. enum ExprAnalysisErrorCode {
  5815. /// A statement is not an expression statement.
  5816. NotAnExpression,
  5817. /// Expression is not builtin binary or unary operation.
  5818. NotABinaryOrUnaryExpression,
  5819. /// Unary operation is not post-/pre- increment/decrement operation.
  5820. NotAnUnaryIncDecExpression,
  5821. /// An expression is not of scalar type.
  5822. NotAScalarType,
  5823. /// A binary operation is not an assignment operation.
  5824. NotAnAssignmentOp,
  5825. /// RHS part of the binary operation is not a binary expression.
  5826. NotABinaryExpression,
  5827. /// RHS part is not additive/multiplicative/shift/biwise binary
  5828. /// expression.
  5829. NotABinaryOperator,
  5830. /// RHS binary operation does not have reference to the updated LHS
  5831. /// part.
  5832. NotAnUpdateExpression,
  5833. /// No errors is found.
  5834. NoError
  5835. };
  5836. /// Reference to Sema.
  5837. Sema &SemaRef;
  5838. /// A location for note diagnostics (when error is found).
  5839. SourceLocation NoteLoc;
  5840. /// 'x' lvalue part of the source atomic expression.
  5841. Expr *X;
  5842. /// 'expr' rvalue part of the source atomic expression.
  5843. Expr *E;
  5844. /// Helper expression of the form
  5845. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5846. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5847. Expr *UpdateExpr;
  5848. /// Is 'x' a LHS in a RHS part of full update expression. It is
  5849. /// important for non-associative operations.
  5850. bool IsXLHSInRHSPart;
  5851. BinaryOperatorKind Op;
  5852. SourceLocation OpLoc;
  5853. /// true if the source expression is a postfix unary operation, false
  5854. /// if it is a prefix unary operation.
  5855. bool IsPostfixUpdate;
  5856. public:
  5857. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5858. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5859. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5860. /// Check specified statement that it is suitable for 'atomic update'
  5861. /// constructs and extract 'x', 'expr' and Operation from the original
  5862. /// expression. If DiagId and NoteId == 0, then only check is performed
  5863. /// without error notification.
  5864. /// \param DiagId Diagnostic which should be emitted if error is found.
  5865. /// \param NoteId Diagnostic note for the main error message.
  5866. /// \return true if statement is not an update expression, false otherwise.
  5867. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5868. /// Return the 'x' lvalue part of the source atomic expression.
  5869. Expr *getX() const { return X; }
  5870. /// Return the 'expr' rvalue part of the source atomic expression.
  5871. Expr *getExpr() const { return E; }
  5872. /// Return the update expression used in calculation of the updated
  5873. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5874. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5875. Expr *getUpdateExpr() const { return UpdateExpr; }
  5876. /// Return true if 'x' is LHS in RHS part of full update expression,
  5877. /// false otherwise.
  5878. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5879. /// true if the source expression is a postfix unary operation, false
  5880. /// if it is a prefix unary operation.
  5881. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5882. private:
  5883. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5884. unsigned NoteId = 0);
  5885. };
  5886. } // namespace
  5887. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5888. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5889. ExprAnalysisErrorCode ErrorFound = NoError;
  5890. SourceLocation ErrorLoc, NoteLoc;
  5891. SourceRange ErrorRange, NoteRange;
  5892. // Allowed constructs are:
  5893. // x = x binop expr;
  5894. // x = expr binop x;
  5895. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5896. X = AtomicBinOp->getLHS();
  5897. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5898. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5899. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5900. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5901. AtomicInnerBinOp->isBitwiseOp()) {
  5902. Op = AtomicInnerBinOp->getOpcode();
  5903. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5904. Expr *LHS = AtomicInnerBinOp->getLHS();
  5905. Expr *RHS = AtomicInnerBinOp->getRHS();
  5906. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5907. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5908. /*Canonical=*/true);
  5909. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5910. /*Canonical=*/true);
  5911. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5912. /*Canonical=*/true);
  5913. if (XId == LHSId) {
  5914. E = RHS;
  5915. IsXLHSInRHSPart = true;
  5916. } else if (XId == RHSId) {
  5917. E = LHS;
  5918. IsXLHSInRHSPart = false;
  5919. } else {
  5920. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5921. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5922. NoteLoc = X->getExprLoc();
  5923. NoteRange = X->getSourceRange();
  5924. ErrorFound = NotAnUpdateExpression;
  5925. }
  5926. } else {
  5927. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5928. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5929. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5930. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5931. ErrorFound = NotABinaryOperator;
  5932. }
  5933. } else {
  5934. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5935. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5936. ErrorFound = NotABinaryExpression;
  5937. }
  5938. } else {
  5939. ErrorLoc = AtomicBinOp->getExprLoc();
  5940. ErrorRange = AtomicBinOp->getSourceRange();
  5941. NoteLoc = AtomicBinOp->getOperatorLoc();
  5942. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5943. ErrorFound = NotAnAssignmentOp;
  5944. }
  5945. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5946. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5947. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5948. return true;
  5949. }
  5950. if (SemaRef.CurContext->isDependentContext())
  5951. E = X = UpdateExpr = nullptr;
  5952. return ErrorFound != NoError;
  5953. }
  5954. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5955. unsigned NoteId) {
  5956. ExprAnalysisErrorCode ErrorFound = NoError;
  5957. SourceLocation ErrorLoc, NoteLoc;
  5958. SourceRange ErrorRange, NoteRange;
  5959. // Allowed constructs are:
  5960. // x++;
  5961. // x--;
  5962. // ++x;
  5963. // --x;
  5964. // x binop= expr;
  5965. // x = x binop expr;
  5966. // x = expr binop x;
  5967. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5968. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5969. if (AtomicBody->getType()->isScalarType() ||
  5970. AtomicBody->isInstantiationDependent()) {
  5971. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5972. AtomicBody->IgnoreParenImpCasts())) {
  5973. // Check for Compound Assignment Operation
  5974. Op = BinaryOperator::getOpForCompoundAssignment(
  5975. AtomicCompAssignOp->getOpcode());
  5976. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5977. E = AtomicCompAssignOp->getRHS();
  5978. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5979. IsXLHSInRHSPart = true;
  5980. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5981. AtomicBody->IgnoreParenImpCasts())) {
  5982. // Check for Binary Operation
  5983. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5984. return true;
  5985. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5986. AtomicBody->IgnoreParenImpCasts())) {
  5987. // Check for Unary Operation
  5988. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5989. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5990. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5991. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5992. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5993. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5994. IsXLHSInRHSPart = true;
  5995. } else {
  5996. ErrorFound = NotAnUnaryIncDecExpression;
  5997. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5998. ErrorRange = AtomicUnaryOp->getSourceRange();
  5999. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  6000. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6001. }
  6002. } else if (!AtomicBody->isInstantiationDependent()) {
  6003. ErrorFound = NotABinaryOrUnaryExpression;
  6004. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  6005. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  6006. }
  6007. } else {
  6008. ErrorFound = NotAScalarType;
  6009. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  6010. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6011. }
  6012. } else {
  6013. ErrorFound = NotAnExpression;
  6014. NoteLoc = ErrorLoc = S->getBeginLoc();
  6015. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6016. }
  6017. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6018. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6019. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6020. return true;
  6021. }
  6022. if (SemaRef.CurContext->isDependentContext())
  6023. E = X = UpdateExpr = nullptr;
  6024. if (ErrorFound == NoError && E && X) {
  6025. // Build an update expression of form 'OpaqueValueExpr(x) binop
  6026. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  6027. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  6028. auto *OVEX = new (SemaRef.getASTContext())
  6029. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  6030. auto *OVEExpr = new (SemaRef.getASTContext())
  6031. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  6032. ExprResult Update =
  6033. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6034. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6035. if (Update.isInvalid())
  6036. return true;
  6037. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  6038. Sema::AA_Casting);
  6039. if (Update.isInvalid())
  6040. return true;
  6041. UpdateExpr = Update.get();
  6042. }
  6043. return ErrorFound != NoError;
  6044. }
  6045. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  6046. Stmt *AStmt,
  6047. SourceLocation StartLoc,
  6048. SourceLocation EndLoc) {
  6049. if (!AStmt)
  6050. return StmtError();
  6051. auto *CS = cast<CapturedStmt>(AStmt);
  6052. // 1.2.2 OpenMP Language Terminology
  6053. // Structured block - An executable statement with a single entry at the
  6054. // top and a single exit at the bottom.
  6055. // The point of exit cannot be a branch out of the structured block.
  6056. // longjmp() and throw() must not violate the entry/exit criteria.
  6057. OpenMPClauseKind AtomicKind = OMPC_unknown;
  6058. SourceLocation AtomicKindLoc;
  6059. for (const OMPClause *C : Clauses) {
  6060. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  6061. C->getClauseKind() == OMPC_update ||
  6062. C->getClauseKind() == OMPC_capture) {
  6063. if (AtomicKind != OMPC_unknown) {
  6064. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  6065. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  6066. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  6067. << getOpenMPClauseName(AtomicKind);
  6068. } else {
  6069. AtomicKind = C->getClauseKind();
  6070. AtomicKindLoc = C->getBeginLoc();
  6071. }
  6072. }
  6073. }
  6074. Stmt *Body = CS->getCapturedStmt();
  6075. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  6076. Body = EWC->getSubExpr();
  6077. Expr *X = nullptr;
  6078. Expr *V = nullptr;
  6079. Expr *E = nullptr;
  6080. Expr *UE = nullptr;
  6081. bool IsXLHSInRHSPart = false;
  6082. bool IsPostfixUpdate = false;
  6083. // OpenMP [2.12.6, atomic Construct]
  6084. // In the next expressions:
  6085. // * x and v (as applicable) are both l-value expressions with scalar type.
  6086. // * During the execution of an atomic region, multiple syntactic
  6087. // occurrences of x must designate the same storage location.
  6088. // * Neither of v and expr (as applicable) may access the storage location
  6089. // designated by x.
  6090. // * Neither of x and expr (as applicable) may access the storage location
  6091. // designated by v.
  6092. // * expr is an expression with scalar type.
  6093. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  6094. // * binop, binop=, ++, and -- are not overloaded operators.
  6095. // * The expression x binop expr must be numerically equivalent to x binop
  6096. // (expr). This requirement is satisfied if the operators in expr have
  6097. // precedence greater than binop, or by using parentheses around expr or
  6098. // subexpressions of expr.
  6099. // * The expression expr binop x must be numerically equivalent to (expr)
  6100. // binop x. This requirement is satisfied if the operators in expr have
  6101. // precedence equal to or greater than binop, or by using parentheses around
  6102. // expr or subexpressions of expr.
  6103. // * For forms that allow multiple occurrences of x, the number of times
  6104. // that x is evaluated is unspecified.
  6105. if (AtomicKind == OMPC_read) {
  6106. enum {
  6107. NotAnExpression,
  6108. NotAnAssignmentOp,
  6109. NotAScalarType,
  6110. NotAnLValue,
  6111. NoError
  6112. } ErrorFound = NoError;
  6113. SourceLocation ErrorLoc, NoteLoc;
  6114. SourceRange ErrorRange, NoteRange;
  6115. // If clause is read:
  6116. // v = x;
  6117. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6118. const auto *AtomicBinOp =
  6119. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6120. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6121. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6122. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  6123. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6124. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  6125. if (!X->isLValue() || !V->isLValue()) {
  6126. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  6127. ErrorFound = NotAnLValue;
  6128. ErrorLoc = AtomicBinOp->getExprLoc();
  6129. ErrorRange = AtomicBinOp->getSourceRange();
  6130. NoteLoc = NotLValueExpr->getExprLoc();
  6131. NoteRange = NotLValueExpr->getSourceRange();
  6132. }
  6133. } else if (!X->isInstantiationDependent() ||
  6134. !V->isInstantiationDependent()) {
  6135. const Expr *NotScalarExpr =
  6136. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6137. ? V
  6138. : X;
  6139. ErrorFound = NotAScalarType;
  6140. ErrorLoc = AtomicBinOp->getExprLoc();
  6141. ErrorRange = AtomicBinOp->getSourceRange();
  6142. NoteLoc = NotScalarExpr->getExprLoc();
  6143. NoteRange = NotScalarExpr->getSourceRange();
  6144. }
  6145. } else if (!AtomicBody->isInstantiationDependent()) {
  6146. ErrorFound = NotAnAssignmentOp;
  6147. ErrorLoc = AtomicBody->getExprLoc();
  6148. ErrorRange = AtomicBody->getSourceRange();
  6149. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6150. : AtomicBody->getExprLoc();
  6151. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6152. : AtomicBody->getSourceRange();
  6153. }
  6154. } else {
  6155. ErrorFound = NotAnExpression;
  6156. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6157. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6158. }
  6159. if (ErrorFound != NoError) {
  6160. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  6161. << ErrorRange;
  6162. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6163. << NoteRange;
  6164. return StmtError();
  6165. }
  6166. if (CurContext->isDependentContext())
  6167. V = X = nullptr;
  6168. } else if (AtomicKind == OMPC_write) {
  6169. enum {
  6170. NotAnExpression,
  6171. NotAnAssignmentOp,
  6172. NotAScalarType,
  6173. NotAnLValue,
  6174. NoError
  6175. } ErrorFound = NoError;
  6176. SourceLocation ErrorLoc, NoteLoc;
  6177. SourceRange ErrorRange, NoteRange;
  6178. // If clause is write:
  6179. // x = expr;
  6180. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6181. const auto *AtomicBinOp =
  6182. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6183. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6184. X = AtomicBinOp->getLHS();
  6185. E = AtomicBinOp->getRHS();
  6186. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6187. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  6188. if (!X->isLValue()) {
  6189. ErrorFound = NotAnLValue;
  6190. ErrorLoc = AtomicBinOp->getExprLoc();
  6191. ErrorRange = AtomicBinOp->getSourceRange();
  6192. NoteLoc = X->getExprLoc();
  6193. NoteRange = X->getSourceRange();
  6194. }
  6195. } else if (!X->isInstantiationDependent() ||
  6196. !E->isInstantiationDependent()) {
  6197. const Expr *NotScalarExpr =
  6198. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6199. ? E
  6200. : X;
  6201. ErrorFound = NotAScalarType;
  6202. ErrorLoc = AtomicBinOp->getExprLoc();
  6203. ErrorRange = AtomicBinOp->getSourceRange();
  6204. NoteLoc = NotScalarExpr->getExprLoc();
  6205. NoteRange = NotScalarExpr->getSourceRange();
  6206. }
  6207. } else if (!AtomicBody->isInstantiationDependent()) {
  6208. ErrorFound = NotAnAssignmentOp;
  6209. ErrorLoc = AtomicBody->getExprLoc();
  6210. ErrorRange = AtomicBody->getSourceRange();
  6211. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6212. : AtomicBody->getExprLoc();
  6213. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6214. : AtomicBody->getSourceRange();
  6215. }
  6216. } else {
  6217. ErrorFound = NotAnExpression;
  6218. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6219. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6220. }
  6221. if (ErrorFound != NoError) {
  6222. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  6223. << ErrorRange;
  6224. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6225. << NoteRange;
  6226. return StmtError();
  6227. }
  6228. if (CurContext->isDependentContext())
  6229. E = X = nullptr;
  6230. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  6231. // If clause is update:
  6232. // x++;
  6233. // x--;
  6234. // ++x;
  6235. // --x;
  6236. // x binop= expr;
  6237. // x = x binop expr;
  6238. // x = expr binop x;
  6239. OpenMPAtomicUpdateChecker Checker(*this);
  6240. if (Checker.checkStatement(
  6241. Body, (AtomicKind == OMPC_update)
  6242. ? diag::err_omp_atomic_update_not_expression_statement
  6243. : diag::err_omp_atomic_not_expression_statement,
  6244. diag::note_omp_atomic_update))
  6245. return StmtError();
  6246. if (!CurContext->isDependentContext()) {
  6247. E = Checker.getExpr();
  6248. X = Checker.getX();
  6249. UE = Checker.getUpdateExpr();
  6250. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6251. }
  6252. } else if (AtomicKind == OMPC_capture) {
  6253. enum {
  6254. NotAnAssignmentOp,
  6255. NotACompoundStatement,
  6256. NotTwoSubstatements,
  6257. NotASpecificExpression,
  6258. NoError
  6259. } ErrorFound = NoError;
  6260. SourceLocation ErrorLoc, NoteLoc;
  6261. SourceRange ErrorRange, NoteRange;
  6262. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6263. // If clause is a capture:
  6264. // v = x++;
  6265. // v = x--;
  6266. // v = ++x;
  6267. // v = --x;
  6268. // v = x binop= expr;
  6269. // v = x = x binop expr;
  6270. // v = x = expr binop x;
  6271. const auto *AtomicBinOp =
  6272. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6273. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6274. V = AtomicBinOp->getLHS();
  6275. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6276. OpenMPAtomicUpdateChecker Checker(*this);
  6277. if (Checker.checkStatement(
  6278. Body, diag::err_omp_atomic_capture_not_expression_statement,
  6279. diag::note_omp_atomic_update))
  6280. return StmtError();
  6281. E = Checker.getExpr();
  6282. X = Checker.getX();
  6283. UE = Checker.getUpdateExpr();
  6284. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6285. IsPostfixUpdate = Checker.isPostfixUpdate();
  6286. } else if (!AtomicBody->isInstantiationDependent()) {
  6287. ErrorLoc = AtomicBody->getExprLoc();
  6288. ErrorRange = AtomicBody->getSourceRange();
  6289. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6290. : AtomicBody->getExprLoc();
  6291. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6292. : AtomicBody->getSourceRange();
  6293. ErrorFound = NotAnAssignmentOp;
  6294. }
  6295. if (ErrorFound != NoError) {
  6296. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  6297. << ErrorRange;
  6298. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6299. return StmtError();
  6300. }
  6301. if (CurContext->isDependentContext())
  6302. UE = V = E = X = nullptr;
  6303. } else {
  6304. // If clause is a capture:
  6305. // { v = x; x = expr; }
  6306. // { v = x; x++; }
  6307. // { v = x; x--; }
  6308. // { v = x; ++x; }
  6309. // { v = x; --x; }
  6310. // { v = x; x binop= expr; }
  6311. // { v = x; x = x binop expr; }
  6312. // { v = x; x = expr binop x; }
  6313. // { x++; v = x; }
  6314. // { x--; v = x; }
  6315. // { ++x; v = x; }
  6316. // { --x; v = x; }
  6317. // { x binop= expr; v = x; }
  6318. // { x = x binop expr; v = x; }
  6319. // { x = expr binop x; v = x; }
  6320. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  6321. // Check that this is { expr1; expr2; }
  6322. if (CS->size() == 2) {
  6323. Stmt *First = CS->body_front();
  6324. Stmt *Second = CS->body_back();
  6325. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  6326. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  6327. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  6328. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  6329. // Need to find what subexpression is 'v' and what is 'x'.
  6330. OpenMPAtomicUpdateChecker Checker(*this);
  6331. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6332. BinaryOperator *BinOp = nullptr;
  6333. if (IsUpdateExprFound) {
  6334. BinOp = dyn_cast<BinaryOperator>(First);
  6335. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6336. }
  6337. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6338. // { v = x; x++; }
  6339. // { v = x; x--; }
  6340. // { v = x; ++x; }
  6341. // { v = x; --x; }
  6342. // { v = x; x binop= expr; }
  6343. // { v = x; x = x binop expr; }
  6344. // { v = x; x = expr binop x; }
  6345. // Check that the first expression has form v = x.
  6346. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6347. llvm::FoldingSetNodeID XId, PossibleXId;
  6348. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6349. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6350. IsUpdateExprFound = XId == PossibleXId;
  6351. if (IsUpdateExprFound) {
  6352. V = BinOp->getLHS();
  6353. X = Checker.getX();
  6354. E = Checker.getExpr();
  6355. UE = Checker.getUpdateExpr();
  6356. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6357. IsPostfixUpdate = true;
  6358. }
  6359. }
  6360. if (!IsUpdateExprFound) {
  6361. IsUpdateExprFound = !Checker.checkStatement(First);
  6362. BinOp = nullptr;
  6363. if (IsUpdateExprFound) {
  6364. BinOp = dyn_cast<BinaryOperator>(Second);
  6365. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6366. }
  6367. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6368. // { x++; v = x; }
  6369. // { x--; v = x; }
  6370. // { ++x; v = x; }
  6371. // { --x; v = x; }
  6372. // { x binop= expr; v = x; }
  6373. // { x = x binop expr; v = x; }
  6374. // { x = expr binop x; v = x; }
  6375. // Check that the second expression has form v = x.
  6376. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6377. llvm::FoldingSetNodeID XId, PossibleXId;
  6378. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6379. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6380. IsUpdateExprFound = XId == PossibleXId;
  6381. if (IsUpdateExprFound) {
  6382. V = BinOp->getLHS();
  6383. X = Checker.getX();
  6384. E = Checker.getExpr();
  6385. UE = Checker.getUpdateExpr();
  6386. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6387. IsPostfixUpdate = false;
  6388. }
  6389. }
  6390. }
  6391. if (!IsUpdateExprFound) {
  6392. // { v = x; x = expr; }
  6393. auto *FirstExpr = dyn_cast<Expr>(First);
  6394. auto *SecondExpr = dyn_cast<Expr>(Second);
  6395. if (!FirstExpr || !SecondExpr ||
  6396. !(FirstExpr->isInstantiationDependent() ||
  6397. SecondExpr->isInstantiationDependent())) {
  6398. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6399. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6400. ErrorFound = NotAnAssignmentOp;
  6401. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6402. : First->getBeginLoc();
  6403. NoteRange = ErrorRange = FirstBinOp
  6404. ? FirstBinOp->getSourceRange()
  6405. : SourceRange(ErrorLoc, ErrorLoc);
  6406. } else {
  6407. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  6408. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  6409. ErrorFound = NotAnAssignmentOp;
  6410. NoteLoc = ErrorLoc = SecondBinOp
  6411. ? SecondBinOp->getOperatorLoc()
  6412. : Second->getBeginLoc();
  6413. NoteRange = ErrorRange =
  6414. SecondBinOp ? SecondBinOp->getSourceRange()
  6415. : SourceRange(ErrorLoc, ErrorLoc);
  6416. } else {
  6417. Expr *PossibleXRHSInFirst =
  6418. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  6419. Expr *PossibleXLHSInSecond =
  6420. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  6421. llvm::FoldingSetNodeID X1Id, X2Id;
  6422. PossibleXRHSInFirst->Profile(X1Id, Context,
  6423. /*Canonical=*/true);
  6424. PossibleXLHSInSecond->Profile(X2Id, Context,
  6425. /*Canonical=*/true);
  6426. IsUpdateExprFound = X1Id == X2Id;
  6427. if (IsUpdateExprFound) {
  6428. V = FirstBinOp->getLHS();
  6429. X = SecondBinOp->getLHS();
  6430. E = SecondBinOp->getRHS();
  6431. UE = nullptr;
  6432. IsXLHSInRHSPart = false;
  6433. IsPostfixUpdate = true;
  6434. } else {
  6435. ErrorFound = NotASpecificExpression;
  6436. ErrorLoc = FirstBinOp->getExprLoc();
  6437. ErrorRange = FirstBinOp->getSourceRange();
  6438. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  6439. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  6440. }
  6441. }
  6442. }
  6443. }
  6444. }
  6445. } else {
  6446. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6447. NoteRange = ErrorRange =
  6448. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6449. ErrorFound = NotTwoSubstatements;
  6450. }
  6451. } else {
  6452. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6453. NoteRange = ErrorRange =
  6454. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6455. ErrorFound = NotACompoundStatement;
  6456. }
  6457. if (ErrorFound != NoError) {
  6458. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  6459. << ErrorRange;
  6460. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6461. return StmtError();
  6462. }
  6463. if (CurContext->isDependentContext())
  6464. UE = V = E = X = nullptr;
  6465. }
  6466. }
  6467. setFunctionHasBranchProtectedScope();
  6468. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6469. X, V, E, UE, IsXLHSInRHSPart,
  6470. IsPostfixUpdate);
  6471. }
  6472. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  6473. Stmt *AStmt,
  6474. SourceLocation StartLoc,
  6475. SourceLocation EndLoc) {
  6476. if (!AStmt)
  6477. return StmtError();
  6478. auto *CS = cast<CapturedStmt>(AStmt);
  6479. // 1.2.2 OpenMP Language Terminology
  6480. // Structured block - An executable statement with a single entry at the
  6481. // top and a single exit at the bottom.
  6482. // The point of exit cannot be a branch out of the structured block.
  6483. // longjmp() and throw() must not violate the entry/exit criteria.
  6484. CS->getCapturedDecl()->setNothrow();
  6485. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  6486. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6487. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6488. // 1.2.2 OpenMP Language Terminology
  6489. // Structured block - An executable statement with a single entry at the
  6490. // top and a single exit at the bottom.
  6491. // The point of exit cannot be a branch out of the structured block.
  6492. // longjmp() and throw() must not violate the entry/exit criteria.
  6493. CS->getCapturedDecl()->setNothrow();
  6494. }
  6495. // OpenMP [2.16, Nesting of Regions]
  6496. // If specified, a teams construct must be contained within a target
  6497. // construct. That target construct must contain no statements or directives
  6498. // outside of the teams construct.
  6499. if (DSAStack->hasInnerTeamsRegion()) {
  6500. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  6501. bool OMPTeamsFound = true;
  6502. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  6503. auto I = CS->body_begin();
  6504. while (I != CS->body_end()) {
  6505. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  6506. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  6507. OMPTeamsFound = false;
  6508. break;
  6509. }
  6510. ++I;
  6511. }
  6512. assert(I != CS->body_end() && "Not found statement");
  6513. S = *I;
  6514. } else {
  6515. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  6516. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  6517. }
  6518. if (!OMPTeamsFound) {
  6519. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  6520. Diag(DSAStack->getInnerTeamsRegionLoc(),
  6521. diag::note_omp_nested_teams_construct_here);
  6522. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  6523. << isa<OMPExecutableDirective>(S);
  6524. return StmtError();
  6525. }
  6526. }
  6527. setFunctionHasBranchProtectedScope();
  6528. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6529. }
  6530. StmtResult
  6531. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  6532. Stmt *AStmt, SourceLocation StartLoc,
  6533. SourceLocation EndLoc) {
  6534. if (!AStmt)
  6535. return StmtError();
  6536. auto *CS = cast<CapturedStmt>(AStmt);
  6537. // 1.2.2 OpenMP Language Terminology
  6538. // Structured block - An executable statement with a single entry at the
  6539. // top and a single exit at the bottom.
  6540. // The point of exit cannot be a branch out of the structured block.
  6541. // longjmp() and throw() must not violate the entry/exit criteria.
  6542. CS->getCapturedDecl()->setNothrow();
  6543. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  6544. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6545. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6546. // 1.2.2 OpenMP Language Terminology
  6547. // Structured block - An executable statement with a single entry at the
  6548. // top and a single exit at the bottom.
  6549. // The point of exit cannot be a branch out of the structured block.
  6550. // longjmp() and throw() must not violate the entry/exit criteria.
  6551. CS->getCapturedDecl()->setNothrow();
  6552. }
  6553. setFunctionHasBranchProtectedScope();
  6554. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6555. AStmt);
  6556. }
  6557. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  6558. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6559. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6560. if (!AStmt)
  6561. return StmtError();
  6562. auto *CS = cast<CapturedStmt>(AStmt);
  6563. // 1.2.2 OpenMP Language Terminology
  6564. // Structured block - An executable statement with a single entry at the
  6565. // top and a single exit at the bottom.
  6566. // The point of exit cannot be a branch out of the structured block.
  6567. // longjmp() and throw() must not violate the entry/exit criteria.
  6568. CS->getCapturedDecl()->setNothrow();
  6569. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6570. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6571. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6572. // 1.2.2 OpenMP Language Terminology
  6573. // Structured block - An executable statement with a single entry at the
  6574. // top and a single exit at the bottom.
  6575. // The point of exit cannot be a branch out of the structured block.
  6576. // longjmp() and throw() must not violate the entry/exit criteria.
  6577. CS->getCapturedDecl()->setNothrow();
  6578. }
  6579. OMPLoopDirective::HelperExprs B;
  6580. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6581. // define the nested loops number.
  6582. unsigned NestedLoopCount =
  6583. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6584. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6585. VarsWithImplicitDSA, B);
  6586. if (NestedLoopCount == 0)
  6587. return StmtError();
  6588. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6589. "omp target parallel for loop exprs were not built");
  6590. if (!CurContext->isDependentContext()) {
  6591. // Finalize the clauses that need pre-built expressions for CodeGen.
  6592. for (OMPClause *C : Clauses) {
  6593. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6594. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6595. B.NumIterations, *this, CurScope,
  6596. DSAStack))
  6597. return StmtError();
  6598. }
  6599. }
  6600. setFunctionHasBranchProtectedScope();
  6601. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6602. NestedLoopCount, Clauses, AStmt,
  6603. B, DSAStack->isCancelRegion());
  6604. }
  6605. /// Check for existence of a map clause in the list of clauses.
  6606. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6607. const OpenMPClauseKind K) {
  6608. return llvm::any_of(
  6609. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6610. }
  6611. template <typename... Params>
  6612. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6613. const Params... ClauseTypes) {
  6614. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6615. }
  6616. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6617. Stmt *AStmt,
  6618. SourceLocation StartLoc,
  6619. SourceLocation EndLoc) {
  6620. if (!AStmt)
  6621. return StmtError();
  6622. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6623. // OpenMP [2.10.1, Restrictions, p. 97]
  6624. // At least one map clause must appear on the directive.
  6625. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6626. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6627. << "'map' or 'use_device_ptr'"
  6628. << getOpenMPDirectiveName(OMPD_target_data);
  6629. return StmtError();
  6630. }
  6631. setFunctionHasBranchProtectedScope();
  6632. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6633. AStmt);
  6634. }
  6635. StmtResult
  6636. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6637. SourceLocation StartLoc,
  6638. SourceLocation EndLoc, Stmt *AStmt) {
  6639. if (!AStmt)
  6640. return StmtError();
  6641. auto *CS = cast<CapturedStmt>(AStmt);
  6642. // 1.2.2 OpenMP Language Terminology
  6643. // Structured block - An executable statement with a single entry at the
  6644. // top and a single exit at the bottom.
  6645. // The point of exit cannot be a branch out of the structured block.
  6646. // longjmp() and throw() must not violate the entry/exit criteria.
  6647. CS->getCapturedDecl()->setNothrow();
  6648. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6649. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6650. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6651. // 1.2.2 OpenMP Language Terminology
  6652. // Structured block - An executable statement with a single entry at the
  6653. // top and a single exit at the bottom.
  6654. // The point of exit cannot be a branch out of the structured block.
  6655. // longjmp() and throw() must not violate the entry/exit criteria.
  6656. CS->getCapturedDecl()->setNothrow();
  6657. }
  6658. // OpenMP [2.10.2, Restrictions, p. 99]
  6659. // At least one map clause must appear on the directive.
  6660. if (!hasClauses(Clauses, OMPC_map)) {
  6661. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6662. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6663. return StmtError();
  6664. }
  6665. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6666. AStmt);
  6667. }
  6668. StmtResult
  6669. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6670. SourceLocation StartLoc,
  6671. SourceLocation EndLoc, Stmt *AStmt) {
  6672. if (!AStmt)
  6673. return StmtError();
  6674. auto *CS = cast<CapturedStmt>(AStmt);
  6675. // 1.2.2 OpenMP Language Terminology
  6676. // Structured block - An executable statement with a single entry at the
  6677. // top and a single exit at the bottom.
  6678. // The point of exit cannot be a branch out of the structured block.
  6679. // longjmp() and throw() must not violate the entry/exit criteria.
  6680. CS->getCapturedDecl()->setNothrow();
  6681. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6682. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6683. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6684. // 1.2.2 OpenMP Language Terminology
  6685. // Structured block - An executable statement with a single entry at the
  6686. // top and a single exit at the bottom.
  6687. // The point of exit cannot be a branch out of the structured block.
  6688. // longjmp() and throw() must not violate the entry/exit criteria.
  6689. CS->getCapturedDecl()->setNothrow();
  6690. }
  6691. // OpenMP [2.10.3, Restrictions, p. 102]
  6692. // At least one map clause must appear on the directive.
  6693. if (!hasClauses(Clauses, OMPC_map)) {
  6694. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6695. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6696. return StmtError();
  6697. }
  6698. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6699. AStmt);
  6700. }
  6701. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6702. SourceLocation StartLoc,
  6703. SourceLocation EndLoc,
  6704. Stmt *AStmt) {
  6705. if (!AStmt)
  6706. return StmtError();
  6707. auto *CS = cast<CapturedStmt>(AStmt);
  6708. // 1.2.2 OpenMP Language Terminology
  6709. // Structured block - An executable statement with a single entry at the
  6710. // top and a single exit at the bottom.
  6711. // The point of exit cannot be a branch out of the structured block.
  6712. // longjmp() and throw() must not violate the entry/exit criteria.
  6713. CS->getCapturedDecl()->setNothrow();
  6714. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6715. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6716. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6717. // 1.2.2 OpenMP Language Terminology
  6718. // Structured block - An executable statement with a single entry at the
  6719. // top and a single exit at the bottom.
  6720. // The point of exit cannot be a branch out of the structured block.
  6721. // longjmp() and throw() must not violate the entry/exit criteria.
  6722. CS->getCapturedDecl()->setNothrow();
  6723. }
  6724. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6725. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6726. return StmtError();
  6727. }
  6728. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6729. AStmt);
  6730. }
  6731. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6732. Stmt *AStmt, SourceLocation StartLoc,
  6733. SourceLocation EndLoc) {
  6734. if (!AStmt)
  6735. return StmtError();
  6736. auto *CS = cast<CapturedStmt>(AStmt);
  6737. // 1.2.2 OpenMP Language Terminology
  6738. // Structured block - An executable statement with a single entry at the
  6739. // top and a single exit at the bottom.
  6740. // The point of exit cannot be a branch out of the structured block.
  6741. // longjmp() and throw() must not violate the entry/exit criteria.
  6742. CS->getCapturedDecl()->setNothrow();
  6743. setFunctionHasBranchProtectedScope();
  6744. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6745. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6746. }
  6747. StmtResult
  6748. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6749. SourceLocation EndLoc,
  6750. OpenMPDirectiveKind CancelRegion) {
  6751. if (DSAStack->isParentNowaitRegion()) {
  6752. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6753. return StmtError();
  6754. }
  6755. if (DSAStack->isParentOrderedRegion()) {
  6756. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6757. return StmtError();
  6758. }
  6759. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6760. CancelRegion);
  6761. }
  6762. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6763. SourceLocation StartLoc,
  6764. SourceLocation EndLoc,
  6765. OpenMPDirectiveKind CancelRegion) {
  6766. if (DSAStack->isParentNowaitRegion()) {
  6767. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6768. return StmtError();
  6769. }
  6770. if (DSAStack->isParentOrderedRegion()) {
  6771. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6772. return StmtError();
  6773. }
  6774. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6775. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6776. CancelRegion);
  6777. }
  6778. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6779. ArrayRef<OMPClause *> Clauses) {
  6780. const OMPClause *PrevClause = nullptr;
  6781. bool ErrorFound = false;
  6782. for (const OMPClause *C : Clauses) {
  6783. if (C->getClauseKind() == OMPC_grainsize ||
  6784. C->getClauseKind() == OMPC_num_tasks) {
  6785. if (!PrevClause)
  6786. PrevClause = C;
  6787. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6788. S.Diag(C->getBeginLoc(),
  6789. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6790. << getOpenMPClauseName(C->getClauseKind())
  6791. << getOpenMPClauseName(PrevClause->getClauseKind());
  6792. S.Diag(PrevClause->getBeginLoc(),
  6793. diag::note_omp_previous_grainsize_num_tasks)
  6794. << getOpenMPClauseName(PrevClause->getClauseKind());
  6795. ErrorFound = true;
  6796. }
  6797. }
  6798. }
  6799. return ErrorFound;
  6800. }
  6801. static bool checkReductionClauseWithNogroup(Sema &S,
  6802. ArrayRef<OMPClause *> Clauses) {
  6803. const OMPClause *ReductionClause = nullptr;
  6804. const OMPClause *NogroupClause = nullptr;
  6805. for (const OMPClause *C : Clauses) {
  6806. if (C->getClauseKind() == OMPC_reduction) {
  6807. ReductionClause = C;
  6808. if (NogroupClause)
  6809. break;
  6810. continue;
  6811. }
  6812. if (C->getClauseKind() == OMPC_nogroup) {
  6813. NogroupClause = C;
  6814. if (ReductionClause)
  6815. break;
  6816. continue;
  6817. }
  6818. }
  6819. if (ReductionClause && NogroupClause) {
  6820. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  6821. << SourceRange(NogroupClause->getBeginLoc(),
  6822. NogroupClause->getEndLoc());
  6823. return true;
  6824. }
  6825. return false;
  6826. }
  6827. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6828. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6829. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6830. if (!AStmt)
  6831. return StmtError();
  6832. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6833. OMPLoopDirective::HelperExprs B;
  6834. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6835. // define the nested loops number.
  6836. unsigned NestedLoopCount =
  6837. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6838. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6839. VarsWithImplicitDSA, B);
  6840. if (NestedLoopCount == 0)
  6841. return StmtError();
  6842. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6843. "omp for loop exprs were not built");
  6844. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6845. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6846. // not appear on the same taskloop directive.
  6847. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6848. return StmtError();
  6849. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6850. // If a reduction clause is present on the taskloop directive, the nogroup
  6851. // clause must not be specified.
  6852. if (checkReductionClauseWithNogroup(*this, Clauses))
  6853. return StmtError();
  6854. setFunctionHasBranchProtectedScope();
  6855. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6856. NestedLoopCount, Clauses, AStmt, B);
  6857. }
  6858. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6859. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6860. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6861. if (!AStmt)
  6862. return StmtError();
  6863. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6864. OMPLoopDirective::HelperExprs B;
  6865. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6866. // define the nested loops number.
  6867. unsigned NestedLoopCount =
  6868. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6869. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6870. VarsWithImplicitDSA, B);
  6871. if (NestedLoopCount == 0)
  6872. return StmtError();
  6873. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6874. "omp for loop exprs were not built");
  6875. if (!CurContext->isDependentContext()) {
  6876. // Finalize the clauses that need pre-built expressions for CodeGen.
  6877. for (OMPClause *C : Clauses) {
  6878. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6879. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6880. B.NumIterations, *this, CurScope,
  6881. DSAStack))
  6882. return StmtError();
  6883. }
  6884. }
  6885. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6886. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6887. // not appear on the same taskloop directive.
  6888. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6889. return StmtError();
  6890. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6891. // If a reduction clause is present on the taskloop directive, the nogroup
  6892. // clause must not be specified.
  6893. if (checkReductionClauseWithNogroup(*this, Clauses))
  6894. return StmtError();
  6895. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6896. return StmtError();
  6897. setFunctionHasBranchProtectedScope();
  6898. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6899. NestedLoopCount, Clauses, AStmt, B);
  6900. }
  6901. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6902. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6903. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6904. if (!AStmt)
  6905. return StmtError();
  6906. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6907. OMPLoopDirective::HelperExprs B;
  6908. // In presence of clause 'collapse' with number of loops, it will
  6909. // define the nested loops number.
  6910. unsigned NestedLoopCount =
  6911. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6912. nullptr /*ordered not a clause on distribute*/, AStmt,
  6913. *this, *DSAStack, VarsWithImplicitDSA, B);
  6914. if (NestedLoopCount == 0)
  6915. return StmtError();
  6916. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6917. "omp for loop exprs were not built");
  6918. setFunctionHasBranchProtectedScope();
  6919. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6920. NestedLoopCount, Clauses, AStmt, B);
  6921. }
  6922. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6923. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6924. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6925. if (!AStmt)
  6926. return StmtError();
  6927. auto *CS = cast<CapturedStmt>(AStmt);
  6928. // 1.2.2 OpenMP Language Terminology
  6929. // Structured block - An executable statement with a single entry at the
  6930. // top and a single exit at the bottom.
  6931. // The point of exit cannot be a branch out of the structured block.
  6932. // longjmp() and throw() must not violate the entry/exit criteria.
  6933. CS->getCapturedDecl()->setNothrow();
  6934. for (int ThisCaptureLevel =
  6935. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6936. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6937. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6938. // 1.2.2 OpenMP Language Terminology
  6939. // Structured block - An executable statement with a single entry at the
  6940. // top and a single exit at the bottom.
  6941. // The point of exit cannot be a branch out of the structured block.
  6942. // longjmp() and throw() must not violate the entry/exit criteria.
  6943. CS->getCapturedDecl()->setNothrow();
  6944. }
  6945. OMPLoopDirective::HelperExprs B;
  6946. // In presence of clause 'collapse' with number of loops, it will
  6947. // define the nested loops number.
  6948. unsigned NestedLoopCount = checkOpenMPLoop(
  6949. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6950. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6951. VarsWithImplicitDSA, B);
  6952. if (NestedLoopCount == 0)
  6953. return StmtError();
  6954. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6955. "omp for loop exprs were not built");
  6956. setFunctionHasBranchProtectedScope();
  6957. return OMPDistributeParallelForDirective::Create(
  6958. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6959. DSAStack->isCancelRegion());
  6960. }
  6961. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6962. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6963. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6964. if (!AStmt)
  6965. return StmtError();
  6966. auto *CS = cast<CapturedStmt>(AStmt);
  6967. // 1.2.2 OpenMP Language Terminology
  6968. // Structured block - An executable statement with a single entry at the
  6969. // top and a single exit at the bottom.
  6970. // The point of exit cannot be a branch out of the structured block.
  6971. // longjmp() and throw() must not violate the entry/exit criteria.
  6972. CS->getCapturedDecl()->setNothrow();
  6973. for (int ThisCaptureLevel =
  6974. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6975. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6976. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6977. // 1.2.2 OpenMP Language Terminology
  6978. // Structured block - An executable statement with a single entry at the
  6979. // top and a single exit at the bottom.
  6980. // The point of exit cannot be a branch out of the structured block.
  6981. // longjmp() and throw() must not violate the entry/exit criteria.
  6982. CS->getCapturedDecl()->setNothrow();
  6983. }
  6984. OMPLoopDirective::HelperExprs B;
  6985. // In presence of clause 'collapse' with number of loops, it will
  6986. // define the nested loops number.
  6987. unsigned NestedLoopCount = checkOpenMPLoop(
  6988. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6989. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6990. VarsWithImplicitDSA, B);
  6991. if (NestedLoopCount == 0)
  6992. return StmtError();
  6993. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6994. "omp for loop exprs were not built");
  6995. if (!CurContext->isDependentContext()) {
  6996. // Finalize the clauses that need pre-built expressions for CodeGen.
  6997. for (OMPClause *C : Clauses) {
  6998. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6999. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7000. B.NumIterations, *this, CurScope,
  7001. DSAStack))
  7002. return StmtError();
  7003. }
  7004. }
  7005. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7006. return StmtError();
  7007. setFunctionHasBranchProtectedScope();
  7008. return OMPDistributeParallelForSimdDirective::Create(
  7009. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7010. }
  7011. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  7012. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7013. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7014. if (!AStmt)
  7015. return StmtError();
  7016. auto *CS = cast<CapturedStmt>(AStmt);
  7017. // 1.2.2 OpenMP Language Terminology
  7018. // Structured block - An executable statement with a single entry at the
  7019. // top and a single exit at the bottom.
  7020. // The point of exit cannot be a branch out of the structured block.
  7021. // longjmp() and throw() must not violate the entry/exit criteria.
  7022. CS->getCapturedDecl()->setNothrow();
  7023. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  7024. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7025. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7026. // 1.2.2 OpenMP Language Terminology
  7027. // Structured block - An executable statement with a single entry at the
  7028. // top and a single exit at the bottom.
  7029. // The point of exit cannot be a branch out of the structured block.
  7030. // longjmp() and throw() must not violate the entry/exit criteria.
  7031. CS->getCapturedDecl()->setNothrow();
  7032. }
  7033. OMPLoopDirective::HelperExprs B;
  7034. // In presence of clause 'collapse' with number of loops, it will
  7035. // define the nested loops number.
  7036. unsigned NestedLoopCount =
  7037. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  7038. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7039. *DSAStack, VarsWithImplicitDSA, B);
  7040. if (NestedLoopCount == 0)
  7041. return StmtError();
  7042. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7043. "omp for loop exprs were not built");
  7044. if (!CurContext->isDependentContext()) {
  7045. // Finalize the clauses that need pre-built expressions for CodeGen.
  7046. for (OMPClause *C : Clauses) {
  7047. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7048. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7049. B.NumIterations, *this, CurScope,
  7050. DSAStack))
  7051. return StmtError();
  7052. }
  7053. }
  7054. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7055. return StmtError();
  7056. setFunctionHasBranchProtectedScope();
  7057. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  7058. NestedLoopCount, Clauses, AStmt, B);
  7059. }
  7060. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  7061. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7062. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7063. if (!AStmt)
  7064. return StmtError();
  7065. auto *CS = cast<CapturedStmt>(AStmt);
  7066. // 1.2.2 OpenMP Language Terminology
  7067. // Structured block - An executable statement with a single entry at the
  7068. // top and a single exit at the bottom.
  7069. // The point of exit cannot be a branch out of the structured block.
  7070. // longjmp() and throw() must not violate the entry/exit criteria.
  7071. CS->getCapturedDecl()->setNothrow();
  7072. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7073. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7074. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7075. // 1.2.2 OpenMP Language Terminology
  7076. // Structured block - An executable statement with a single entry at the
  7077. // top and a single exit at the bottom.
  7078. // The point of exit cannot be a branch out of the structured block.
  7079. // longjmp() and throw() must not violate the entry/exit criteria.
  7080. CS->getCapturedDecl()->setNothrow();
  7081. }
  7082. OMPLoopDirective::HelperExprs B;
  7083. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7084. // define the nested loops number.
  7085. unsigned NestedLoopCount = checkOpenMPLoop(
  7086. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7087. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7088. VarsWithImplicitDSA, B);
  7089. if (NestedLoopCount == 0)
  7090. return StmtError();
  7091. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7092. "omp target parallel for simd loop exprs were not built");
  7093. if (!CurContext->isDependentContext()) {
  7094. // Finalize the clauses that need pre-built expressions for CodeGen.
  7095. for (OMPClause *C : Clauses) {
  7096. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7097. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7098. B.NumIterations, *this, CurScope,
  7099. DSAStack))
  7100. return StmtError();
  7101. }
  7102. }
  7103. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7104. return StmtError();
  7105. setFunctionHasBranchProtectedScope();
  7106. return OMPTargetParallelForSimdDirective::Create(
  7107. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7108. }
  7109. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  7110. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7111. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7112. if (!AStmt)
  7113. return StmtError();
  7114. auto *CS = cast<CapturedStmt>(AStmt);
  7115. // 1.2.2 OpenMP Language Terminology
  7116. // Structured block - An executable statement with a single entry at the
  7117. // top and a single exit at the bottom.
  7118. // The point of exit cannot be a branch out of the structured block.
  7119. // longjmp() and throw() must not violate the entry/exit criteria.
  7120. CS->getCapturedDecl()->setNothrow();
  7121. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  7122. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7123. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7124. // 1.2.2 OpenMP Language Terminology
  7125. // Structured block - An executable statement with a single entry at the
  7126. // top and a single exit at the bottom.
  7127. // The point of exit cannot be a branch out of the structured block.
  7128. // longjmp() and throw() must not violate the entry/exit criteria.
  7129. CS->getCapturedDecl()->setNothrow();
  7130. }
  7131. OMPLoopDirective::HelperExprs B;
  7132. // In presence of clause 'collapse' with number of loops, it will define the
  7133. // nested loops number.
  7134. unsigned NestedLoopCount =
  7135. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  7136. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7137. VarsWithImplicitDSA, B);
  7138. if (NestedLoopCount == 0)
  7139. return StmtError();
  7140. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7141. "omp target simd loop exprs were not built");
  7142. if (!CurContext->isDependentContext()) {
  7143. // Finalize the clauses that need pre-built expressions for CodeGen.
  7144. for (OMPClause *C : Clauses) {
  7145. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7146. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7147. B.NumIterations, *this, CurScope,
  7148. DSAStack))
  7149. return StmtError();
  7150. }
  7151. }
  7152. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7153. return StmtError();
  7154. setFunctionHasBranchProtectedScope();
  7155. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  7156. NestedLoopCount, Clauses, AStmt, B);
  7157. }
  7158. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  7159. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7160. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7161. if (!AStmt)
  7162. return StmtError();
  7163. auto *CS = cast<CapturedStmt>(AStmt);
  7164. // 1.2.2 OpenMP Language Terminology
  7165. // Structured block - An executable statement with a single entry at the
  7166. // top and a single exit at the bottom.
  7167. // The point of exit cannot be a branch out of the structured block.
  7168. // longjmp() and throw() must not violate the entry/exit criteria.
  7169. CS->getCapturedDecl()->setNothrow();
  7170. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  7171. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7172. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7173. // 1.2.2 OpenMP Language Terminology
  7174. // Structured block - An executable statement with a single entry at the
  7175. // top and a single exit at the bottom.
  7176. // The point of exit cannot be a branch out of the structured block.
  7177. // longjmp() and throw() must not violate the entry/exit criteria.
  7178. CS->getCapturedDecl()->setNothrow();
  7179. }
  7180. OMPLoopDirective::HelperExprs B;
  7181. // In presence of clause 'collapse' with number of loops, it will
  7182. // define the nested loops number.
  7183. unsigned NestedLoopCount =
  7184. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  7185. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7186. *DSAStack, VarsWithImplicitDSA, B);
  7187. if (NestedLoopCount == 0)
  7188. return StmtError();
  7189. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7190. "omp teams distribute loop exprs were not built");
  7191. setFunctionHasBranchProtectedScope();
  7192. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7193. return OMPTeamsDistributeDirective::Create(
  7194. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7195. }
  7196. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  7197. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7198. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7199. if (!AStmt)
  7200. return StmtError();
  7201. auto *CS = cast<CapturedStmt>(AStmt);
  7202. // 1.2.2 OpenMP Language Terminology
  7203. // Structured block - An executable statement with a single entry at the
  7204. // top and a single exit at the bottom.
  7205. // The point of exit cannot be a branch out of the structured block.
  7206. // longjmp() and throw() must not violate the entry/exit criteria.
  7207. CS->getCapturedDecl()->setNothrow();
  7208. for (int ThisCaptureLevel =
  7209. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  7210. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7211. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7212. // 1.2.2 OpenMP Language Terminology
  7213. // Structured block - An executable statement with a single entry at the
  7214. // top and a single exit at the bottom.
  7215. // The point of exit cannot be a branch out of the structured block.
  7216. // longjmp() and throw() must not violate the entry/exit criteria.
  7217. CS->getCapturedDecl()->setNothrow();
  7218. }
  7219. OMPLoopDirective::HelperExprs B;
  7220. // In presence of clause 'collapse' with number of loops, it will
  7221. // define the nested loops number.
  7222. unsigned NestedLoopCount = checkOpenMPLoop(
  7223. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7224. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7225. VarsWithImplicitDSA, B);
  7226. if (NestedLoopCount == 0)
  7227. return StmtError();
  7228. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7229. "omp teams distribute simd loop exprs were not built");
  7230. if (!CurContext->isDependentContext()) {
  7231. // Finalize the clauses that need pre-built expressions for CodeGen.
  7232. for (OMPClause *C : Clauses) {
  7233. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7234. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7235. B.NumIterations, *this, CurScope,
  7236. DSAStack))
  7237. return StmtError();
  7238. }
  7239. }
  7240. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7241. return StmtError();
  7242. setFunctionHasBranchProtectedScope();
  7243. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7244. return OMPTeamsDistributeSimdDirective::Create(
  7245. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7246. }
  7247. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  7248. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7249. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7250. if (!AStmt)
  7251. return StmtError();
  7252. auto *CS = cast<CapturedStmt>(AStmt);
  7253. // 1.2.2 OpenMP Language Terminology
  7254. // Structured block - An executable statement with a single entry at the
  7255. // top and a single exit at the bottom.
  7256. // The point of exit cannot be a branch out of the structured block.
  7257. // longjmp() and throw() must not violate the entry/exit criteria.
  7258. CS->getCapturedDecl()->setNothrow();
  7259. for (int ThisCaptureLevel =
  7260. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  7261. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7262. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7263. // 1.2.2 OpenMP Language Terminology
  7264. // Structured block - An executable statement with a single entry at the
  7265. // top and a single exit at the bottom.
  7266. // The point of exit cannot be a branch out of the structured block.
  7267. // longjmp() and throw() must not violate the entry/exit criteria.
  7268. CS->getCapturedDecl()->setNothrow();
  7269. }
  7270. OMPLoopDirective::HelperExprs B;
  7271. // In presence of clause 'collapse' with number of loops, it will
  7272. // define the nested loops number.
  7273. unsigned NestedLoopCount = checkOpenMPLoop(
  7274. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7275. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7276. VarsWithImplicitDSA, B);
  7277. if (NestedLoopCount == 0)
  7278. return StmtError();
  7279. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7280. "omp for loop exprs were not built");
  7281. if (!CurContext->isDependentContext()) {
  7282. // Finalize the clauses that need pre-built expressions for CodeGen.
  7283. for (OMPClause *C : Clauses) {
  7284. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7285. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7286. B.NumIterations, *this, CurScope,
  7287. DSAStack))
  7288. return StmtError();
  7289. }
  7290. }
  7291. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7292. return StmtError();
  7293. setFunctionHasBranchProtectedScope();
  7294. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7295. return OMPTeamsDistributeParallelForSimdDirective::Create(
  7296. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7297. }
  7298. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  7299. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7300. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7301. if (!AStmt)
  7302. return StmtError();
  7303. auto *CS = cast<CapturedStmt>(AStmt);
  7304. // 1.2.2 OpenMP Language Terminology
  7305. // Structured block - An executable statement with a single entry at the
  7306. // top and a single exit at the bottom.
  7307. // The point of exit cannot be a branch out of the structured block.
  7308. // longjmp() and throw() must not violate the entry/exit criteria.
  7309. CS->getCapturedDecl()->setNothrow();
  7310. for (int ThisCaptureLevel =
  7311. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  7312. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7313. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7314. // 1.2.2 OpenMP Language Terminology
  7315. // Structured block - An executable statement with a single entry at the
  7316. // top and a single exit at the bottom.
  7317. // The point of exit cannot be a branch out of the structured block.
  7318. // longjmp() and throw() must not violate the entry/exit criteria.
  7319. CS->getCapturedDecl()->setNothrow();
  7320. }
  7321. OMPLoopDirective::HelperExprs B;
  7322. // In presence of clause 'collapse' with number of loops, it will
  7323. // define the nested loops number.
  7324. unsigned NestedLoopCount = checkOpenMPLoop(
  7325. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7326. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7327. VarsWithImplicitDSA, B);
  7328. if (NestedLoopCount == 0)
  7329. return StmtError();
  7330. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7331. "omp for loop exprs were not built");
  7332. setFunctionHasBranchProtectedScope();
  7333. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7334. return OMPTeamsDistributeParallelForDirective::Create(
  7335. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7336. DSAStack->isCancelRegion());
  7337. }
  7338. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7339. Stmt *AStmt,
  7340. SourceLocation StartLoc,
  7341. SourceLocation EndLoc) {
  7342. if (!AStmt)
  7343. return StmtError();
  7344. auto *CS = cast<CapturedStmt>(AStmt);
  7345. // 1.2.2 OpenMP Language Terminology
  7346. // Structured block - An executable statement with a single entry at the
  7347. // top and a single exit at the bottom.
  7348. // The point of exit cannot be a branch out of the structured block.
  7349. // longjmp() and throw() must not violate the entry/exit criteria.
  7350. CS->getCapturedDecl()->setNothrow();
  7351. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  7352. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7353. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7354. // 1.2.2 OpenMP Language Terminology
  7355. // Structured block - An executable statement with a single entry at the
  7356. // top and a single exit at the bottom.
  7357. // The point of exit cannot be a branch out of the structured block.
  7358. // longjmp() and throw() must not violate the entry/exit criteria.
  7359. CS->getCapturedDecl()->setNothrow();
  7360. }
  7361. setFunctionHasBranchProtectedScope();
  7362. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7363. AStmt);
  7364. }
  7365. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7366. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7367. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7368. if (!AStmt)
  7369. return StmtError();
  7370. auto *CS = cast<CapturedStmt>(AStmt);
  7371. // 1.2.2 OpenMP Language Terminology
  7372. // Structured block - An executable statement with a single entry at the
  7373. // top and a single exit at the bottom.
  7374. // The point of exit cannot be a branch out of the structured block.
  7375. // longjmp() and throw() must not violate the entry/exit criteria.
  7376. CS->getCapturedDecl()->setNothrow();
  7377. for (int ThisCaptureLevel =
  7378. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7379. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7380. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7381. // 1.2.2 OpenMP Language Terminology
  7382. // Structured block - An executable statement with a single entry at the
  7383. // top and a single exit at the bottom.
  7384. // The point of exit cannot be a branch out of the structured block.
  7385. // longjmp() and throw() must not violate the entry/exit criteria.
  7386. CS->getCapturedDecl()->setNothrow();
  7387. }
  7388. OMPLoopDirective::HelperExprs B;
  7389. // In presence of clause 'collapse' with number of loops, it will
  7390. // define the nested loops number.
  7391. unsigned NestedLoopCount = checkOpenMPLoop(
  7392. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7393. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7394. VarsWithImplicitDSA, B);
  7395. if (NestedLoopCount == 0)
  7396. return StmtError();
  7397. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7398. "omp target teams distribute loop exprs were not built");
  7399. setFunctionHasBranchProtectedScope();
  7400. return OMPTargetTeamsDistributeDirective::Create(
  7401. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7402. }
  7403. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  7404. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7405. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7406. if (!AStmt)
  7407. return StmtError();
  7408. auto *CS = cast<CapturedStmt>(AStmt);
  7409. // 1.2.2 OpenMP Language Terminology
  7410. // Structured block - An executable statement with a single entry at the
  7411. // top and a single exit at the bottom.
  7412. // The point of exit cannot be a branch out of the structured block.
  7413. // longjmp() and throw() must not violate the entry/exit criteria.
  7414. CS->getCapturedDecl()->setNothrow();
  7415. for (int ThisCaptureLevel =
  7416. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  7417. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7418. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7419. // 1.2.2 OpenMP Language Terminology
  7420. // Structured block - An executable statement with a single entry at the
  7421. // top and a single exit at the bottom.
  7422. // The point of exit cannot be a branch out of the structured block.
  7423. // longjmp() and throw() must not violate the entry/exit criteria.
  7424. CS->getCapturedDecl()->setNothrow();
  7425. }
  7426. OMPLoopDirective::HelperExprs B;
  7427. // In presence of clause 'collapse' with number of loops, it will
  7428. // define the nested loops number.
  7429. unsigned NestedLoopCount = checkOpenMPLoop(
  7430. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7431. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7432. VarsWithImplicitDSA, B);
  7433. if (NestedLoopCount == 0)
  7434. return StmtError();
  7435. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7436. "omp target teams distribute parallel for loop exprs were not built");
  7437. if (!CurContext->isDependentContext()) {
  7438. // Finalize the clauses that need pre-built expressions for CodeGen.
  7439. for (OMPClause *C : Clauses) {
  7440. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7441. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7442. B.NumIterations, *this, CurScope,
  7443. DSAStack))
  7444. return StmtError();
  7445. }
  7446. }
  7447. setFunctionHasBranchProtectedScope();
  7448. return OMPTargetTeamsDistributeParallelForDirective::Create(
  7449. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7450. DSAStack->isCancelRegion());
  7451. }
  7452. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  7453. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7454. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7455. if (!AStmt)
  7456. return StmtError();
  7457. auto *CS = cast<CapturedStmt>(AStmt);
  7458. // 1.2.2 OpenMP Language Terminology
  7459. // Structured block - An executable statement with a single entry at the
  7460. // top and a single exit at the bottom.
  7461. // The point of exit cannot be a branch out of the structured block.
  7462. // longjmp() and throw() must not violate the entry/exit criteria.
  7463. CS->getCapturedDecl()->setNothrow();
  7464. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  7465. OMPD_target_teams_distribute_parallel_for_simd);
  7466. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7467. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7468. // 1.2.2 OpenMP Language Terminology
  7469. // Structured block - An executable statement with a single entry at the
  7470. // top and a single exit at the bottom.
  7471. // The point of exit cannot be a branch out of the structured block.
  7472. // longjmp() and throw() must not violate the entry/exit criteria.
  7473. CS->getCapturedDecl()->setNothrow();
  7474. }
  7475. OMPLoopDirective::HelperExprs B;
  7476. // In presence of clause 'collapse' with number of loops, it will
  7477. // define the nested loops number.
  7478. unsigned NestedLoopCount =
  7479. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  7480. getCollapseNumberExpr(Clauses),
  7481. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7482. *DSAStack, VarsWithImplicitDSA, B);
  7483. if (NestedLoopCount == 0)
  7484. return StmtError();
  7485. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7486. "omp target teams distribute parallel for simd loop exprs were not "
  7487. "built");
  7488. if (!CurContext->isDependentContext()) {
  7489. // Finalize the clauses that need pre-built expressions for CodeGen.
  7490. for (OMPClause *C : Clauses) {
  7491. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7492. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7493. B.NumIterations, *this, CurScope,
  7494. DSAStack))
  7495. return StmtError();
  7496. }
  7497. }
  7498. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7499. return StmtError();
  7500. setFunctionHasBranchProtectedScope();
  7501. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  7502. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7503. }
  7504. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  7505. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7506. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7507. if (!AStmt)
  7508. return StmtError();
  7509. auto *CS = cast<CapturedStmt>(AStmt);
  7510. // 1.2.2 OpenMP Language Terminology
  7511. // Structured block - An executable statement with a single entry at the
  7512. // top and a single exit at the bottom.
  7513. // The point of exit cannot be a branch out of the structured block.
  7514. // longjmp() and throw() must not violate the entry/exit criteria.
  7515. CS->getCapturedDecl()->setNothrow();
  7516. for (int ThisCaptureLevel =
  7517. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  7518. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7519. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7520. // 1.2.2 OpenMP Language Terminology
  7521. // Structured block - An executable statement with a single entry at the
  7522. // top and a single exit at the bottom.
  7523. // The point of exit cannot be a branch out of the structured block.
  7524. // longjmp() and throw() must not violate the entry/exit criteria.
  7525. CS->getCapturedDecl()->setNothrow();
  7526. }
  7527. OMPLoopDirective::HelperExprs B;
  7528. // In presence of clause 'collapse' with number of loops, it will
  7529. // define the nested loops number.
  7530. unsigned NestedLoopCount = checkOpenMPLoop(
  7531. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7532. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7533. VarsWithImplicitDSA, B);
  7534. if (NestedLoopCount == 0)
  7535. return StmtError();
  7536. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7537. "omp target teams distribute simd loop exprs were not built");
  7538. if (!CurContext->isDependentContext()) {
  7539. // Finalize the clauses that need pre-built expressions for CodeGen.
  7540. for (OMPClause *C : Clauses) {
  7541. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7542. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7543. B.NumIterations, *this, CurScope,
  7544. DSAStack))
  7545. return StmtError();
  7546. }
  7547. }
  7548. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7549. return StmtError();
  7550. setFunctionHasBranchProtectedScope();
  7551. return OMPTargetTeamsDistributeSimdDirective::Create(
  7552. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7553. }
  7554. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  7555. SourceLocation StartLoc,
  7556. SourceLocation LParenLoc,
  7557. SourceLocation EndLoc) {
  7558. OMPClause *Res = nullptr;
  7559. switch (Kind) {
  7560. case OMPC_final:
  7561. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  7562. break;
  7563. case OMPC_num_threads:
  7564. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7565. break;
  7566. case OMPC_safelen:
  7567. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7568. break;
  7569. case OMPC_simdlen:
  7570. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7571. break;
  7572. case OMPC_collapse:
  7573. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  7574. break;
  7575. case OMPC_ordered:
  7576. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  7577. break;
  7578. case OMPC_device:
  7579. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  7580. break;
  7581. case OMPC_num_teams:
  7582. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7583. break;
  7584. case OMPC_thread_limit:
  7585. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  7586. break;
  7587. case OMPC_priority:
  7588. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  7589. break;
  7590. case OMPC_grainsize:
  7591. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  7592. break;
  7593. case OMPC_num_tasks:
  7594. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  7595. break;
  7596. case OMPC_hint:
  7597. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  7598. break;
  7599. case OMPC_if:
  7600. case OMPC_default:
  7601. case OMPC_proc_bind:
  7602. case OMPC_schedule:
  7603. case OMPC_private:
  7604. case OMPC_firstprivate:
  7605. case OMPC_lastprivate:
  7606. case OMPC_shared:
  7607. case OMPC_reduction:
  7608. case OMPC_task_reduction:
  7609. case OMPC_in_reduction:
  7610. case OMPC_linear:
  7611. case OMPC_aligned:
  7612. case OMPC_copyin:
  7613. case OMPC_copyprivate:
  7614. case OMPC_nowait:
  7615. case OMPC_untied:
  7616. case OMPC_mergeable:
  7617. case OMPC_threadprivate:
  7618. case OMPC_flush:
  7619. case OMPC_read:
  7620. case OMPC_write:
  7621. case OMPC_update:
  7622. case OMPC_capture:
  7623. case OMPC_seq_cst:
  7624. case OMPC_depend:
  7625. case OMPC_threads:
  7626. case OMPC_simd:
  7627. case OMPC_map:
  7628. case OMPC_nogroup:
  7629. case OMPC_dist_schedule:
  7630. case OMPC_defaultmap:
  7631. case OMPC_unknown:
  7632. case OMPC_uniform:
  7633. case OMPC_to:
  7634. case OMPC_from:
  7635. case OMPC_use_device_ptr:
  7636. case OMPC_is_device_ptr:
  7637. case OMPC_unified_address:
  7638. case OMPC_unified_shared_memory:
  7639. case OMPC_reverse_offload:
  7640. case OMPC_dynamic_allocators:
  7641. case OMPC_atomic_default_mem_order:
  7642. llvm_unreachable("Clause is not allowed.");
  7643. }
  7644. return Res;
  7645. }
  7646. // An OpenMP directive such as 'target parallel' has two captured regions:
  7647. // for the 'target' and 'parallel' respectively. This function returns
  7648. // the region in which to capture expressions associated with a clause.
  7649. // A return value of OMPD_unknown signifies that the expression should not
  7650. // be captured.
  7651. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7652. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7653. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7654. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7655. switch (CKind) {
  7656. case OMPC_if:
  7657. switch (DKind) {
  7658. case OMPD_target_parallel:
  7659. case OMPD_target_parallel_for:
  7660. case OMPD_target_parallel_for_simd:
  7661. // If this clause applies to the nested 'parallel' region, capture within
  7662. // the 'target' region, otherwise do not capture.
  7663. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7664. CaptureRegion = OMPD_target;
  7665. break;
  7666. case OMPD_target_teams_distribute_parallel_for:
  7667. case OMPD_target_teams_distribute_parallel_for_simd:
  7668. // If this clause applies to the nested 'parallel' region, capture within
  7669. // the 'teams' region, otherwise do not capture.
  7670. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7671. CaptureRegion = OMPD_teams;
  7672. break;
  7673. case OMPD_teams_distribute_parallel_for:
  7674. case OMPD_teams_distribute_parallel_for_simd:
  7675. CaptureRegion = OMPD_teams;
  7676. break;
  7677. case OMPD_target_update:
  7678. case OMPD_target_enter_data:
  7679. case OMPD_target_exit_data:
  7680. CaptureRegion = OMPD_task;
  7681. break;
  7682. case OMPD_cancel:
  7683. case OMPD_parallel:
  7684. case OMPD_parallel_sections:
  7685. case OMPD_parallel_for:
  7686. case OMPD_parallel_for_simd:
  7687. case OMPD_target:
  7688. case OMPD_target_simd:
  7689. case OMPD_target_teams:
  7690. case OMPD_target_teams_distribute:
  7691. case OMPD_target_teams_distribute_simd:
  7692. case OMPD_distribute_parallel_for:
  7693. case OMPD_distribute_parallel_for_simd:
  7694. case OMPD_task:
  7695. case OMPD_taskloop:
  7696. case OMPD_taskloop_simd:
  7697. case OMPD_target_data:
  7698. // Do not capture if-clause expressions.
  7699. break;
  7700. case OMPD_threadprivate:
  7701. case OMPD_taskyield:
  7702. case OMPD_barrier:
  7703. case OMPD_taskwait:
  7704. case OMPD_cancellation_point:
  7705. case OMPD_flush:
  7706. case OMPD_declare_reduction:
  7707. case OMPD_declare_simd:
  7708. case OMPD_declare_target:
  7709. case OMPD_end_declare_target:
  7710. case OMPD_teams:
  7711. case OMPD_simd:
  7712. case OMPD_for:
  7713. case OMPD_for_simd:
  7714. case OMPD_sections:
  7715. case OMPD_section:
  7716. case OMPD_single:
  7717. case OMPD_master:
  7718. case OMPD_critical:
  7719. case OMPD_taskgroup:
  7720. case OMPD_distribute:
  7721. case OMPD_ordered:
  7722. case OMPD_atomic:
  7723. case OMPD_distribute_simd:
  7724. case OMPD_teams_distribute:
  7725. case OMPD_teams_distribute_simd:
  7726. case OMPD_requires:
  7727. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7728. case OMPD_unknown:
  7729. llvm_unreachable("Unknown OpenMP directive");
  7730. }
  7731. break;
  7732. case OMPC_num_threads:
  7733. switch (DKind) {
  7734. case OMPD_target_parallel:
  7735. case OMPD_target_parallel_for:
  7736. case OMPD_target_parallel_for_simd:
  7737. CaptureRegion = OMPD_target;
  7738. break;
  7739. case OMPD_teams_distribute_parallel_for:
  7740. case OMPD_teams_distribute_parallel_for_simd:
  7741. case OMPD_target_teams_distribute_parallel_for:
  7742. case OMPD_target_teams_distribute_parallel_for_simd:
  7743. CaptureRegion = OMPD_teams;
  7744. break;
  7745. case OMPD_parallel:
  7746. case OMPD_parallel_sections:
  7747. case OMPD_parallel_for:
  7748. case OMPD_parallel_for_simd:
  7749. case OMPD_distribute_parallel_for:
  7750. case OMPD_distribute_parallel_for_simd:
  7751. // Do not capture num_threads-clause expressions.
  7752. break;
  7753. case OMPD_target_data:
  7754. case OMPD_target_enter_data:
  7755. case OMPD_target_exit_data:
  7756. case OMPD_target_update:
  7757. case OMPD_target:
  7758. case OMPD_target_simd:
  7759. case OMPD_target_teams:
  7760. case OMPD_target_teams_distribute:
  7761. case OMPD_target_teams_distribute_simd:
  7762. case OMPD_cancel:
  7763. case OMPD_task:
  7764. case OMPD_taskloop:
  7765. case OMPD_taskloop_simd:
  7766. case OMPD_threadprivate:
  7767. case OMPD_taskyield:
  7768. case OMPD_barrier:
  7769. case OMPD_taskwait:
  7770. case OMPD_cancellation_point:
  7771. case OMPD_flush:
  7772. case OMPD_declare_reduction:
  7773. case OMPD_declare_simd:
  7774. case OMPD_declare_target:
  7775. case OMPD_end_declare_target:
  7776. case OMPD_teams:
  7777. case OMPD_simd:
  7778. case OMPD_for:
  7779. case OMPD_for_simd:
  7780. case OMPD_sections:
  7781. case OMPD_section:
  7782. case OMPD_single:
  7783. case OMPD_master:
  7784. case OMPD_critical:
  7785. case OMPD_taskgroup:
  7786. case OMPD_distribute:
  7787. case OMPD_ordered:
  7788. case OMPD_atomic:
  7789. case OMPD_distribute_simd:
  7790. case OMPD_teams_distribute:
  7791. case OMPD_teams_distribute_simd:
  7792. case OMPD_requires:
  7793. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7794. case OMPD_unknown:
  7795. llvm_unreachable("Unknown OpenMP directive");
  7796. }
  7797. break;
  7798. case OMPC_num_teams:
  7799. switch (DKind) {
  7800. case OMPD_target_teams:
  7801. case OMPD_target_teams_distribute:
  7802. case OMPD_target_teams_distribute_simd:
  7803. case OMPD_target_teams_distribute_parallel_for:
  7804. case OMPD_target_teams_distribute_parallel_for_simd:
  7805. CaptureRegion = OMPD_target;
  7806. break;
  7807. case OMPD_teams_distribute_parallel_for:
  7808. case OMPD_teams_distribute_parallel_for_simd:
  7809. case OMPD_teams:
  7810. case OMPD_teams_distribute:
  7811. case OMPD_teams_distribute_simd:
  7812. // Do not capture num_teams-clause expressions.
  7813. break;
  7814. case OMPD_distribute_parallel_for:
  7815. case OMPD_distribute_parallel_for_simd:
  7816. case OMPD_task:
  7817. case OMPD_taskloop:
  7818. case OMPD_taskloop_simd:
  7819. case OMPD_target_data:
  7820. case OMPD_target_enter_data:
  7821. case OMPD_target_exit_data:
  7822. case OMPD_target_update:
  7823. case OMPD_cancel:
  7824. case OMPD_parallel:
  7825. case OMPD_parallel_sections:
  7826. case OMPD_parallel_for:
  7827. case OMPD_parallel_for_simd:
  7828. case OMPD_target:
  7829. case OMPD_target_simd:
  7830. case OMPD_target_parallel:
  7831. case OMPD_target_parallel_for:
  7832. case OMPD_target_parallel_for_simd:
  7833. case OMPD_threadprivate:
  7834. case OMPD_taskyield:
  7835. case OMPD_barrier:
  7836. case OMPD_taskwait:
  7837. case OMPD_cancellation_point:
  7838. case OMPD_flush:
  7839. case OMPD_declare_reduction:
  7840. case OMPD_declare_simd:
  7841. case OMPD_declare_target:
  7842. case OMPD_end_declare_target:
  7843. case OMPD_simd:
  7844. case OMPD_for:
  7845. case OMPD_for_simd:
  7846. case OMPD_sections:
  7847. case OMPD_section:
  7848. case OMPD_single:
  7849. case OMPD_master:
  7850. case OMPD_critical:
  7851. case OMPD_taskgroup:
  7852. case OMPD_distribute:
  7853. case OMPD_ordered:
  7854. case OMPD_atomic:
  7855. case OMPD_distribute_simd:
  7856. case OMPD_requires:
  7857. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7858. case OMPD_unknown:
  7859. llvm_unreachable("Unknown OpenMP directive");
  7860. }
  7861. break;
  7862. case OMPC_thread_limit:
  7863. switch (DKind) {
  7864. case OMPD_target_teams:
  7865. case OMPD_target_teams_distribute:
  7866. case OMPD_target_teams_distribute_simd:
  7867. case OMPD_target_teams_distribute_parallel_for:
  7868. case OMPD_target_teams_distribute_parallel_for_simd:
  7869. CaptureRegion = OMPD_target;
  7870. break;
  7871. case OMPD_teams_distribute_parallel_for:
  7872. case OMPD_teams_distribute_parallel_for_simd:
  7873. case OMPD_teams:
  7874. case OMPD_teams_distribute:
  7875. case OMPD_teams_distribute_simd:
  7876. // Do not capture thread_limit-clause expressions.
  7877. break;
  7878. case OMPD_distribute_parallel_for:
  7879. case OMPD_distribute_parallel_for_simd:
  7880. case OMPD_task:
  7881. case OMPD_taskloop:
  7882. case OMPD_taskloop_simd:
  7883. case OMPD_target_data:
  7884. case OMPD_target_enter_data:
  7885. case OMPD_target_exit_data:
  7886. case OMPD_target_update:
  7887. case OMPD_cancel:
  7888. case OMPD_parallel:
  7889. case OMPD_parallel_sections:
  7890. case OMPD_parallel_for:
  7891. case OMPD_parallel_for_simd:
  7892. case OMPD_target:
  7893. case OMPD_target_simd:
  7894. case OMPD_target_parallel:
  7895. case OMPD_target_parallel_for:
  7896. case OMPD_target_parallel_for_simd:
  7897. case OMPD_threadprivate:
  7898. case OMPD_taskyield:
  7899. case OMPD_barrier:
  7900. case OMPD_taskwait:
  7901. case OMPD_cancellation_point:
  7902. case OMPD_flush:
  7903. case OMPD_declare_reduction:
  7904. case OMPD_declare_simd:
  7905. case OMPD_declare_target:
  7906. case OMPD_end_declare_target:
  7907. case OMPD_simd:
  7908. case OMPD_for:
  7909. case OMPD_for_simd:
  7910. case OMPD_sections:
  7911. case OMPD_section:
  7912. case OMPD_single:
  7913. case OMPD_master:
  7914. case OMPD_critical:
  7915. case OMPD_taskgroup:
  7916. case OMPD_distribute:
  7917. case OMPD_ordered:
  7918. case OMPD_atomic:
  7919. case OMPD_distribute_simd:
  7920. case OMPD_requires:
  7921. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7922. case OMPD_unknown:
  7923. llvm_unreachable("Unknown OpenMP directive");
  7924. }
  7925. break;
  7926. case OMPC_schedule:
  7927. switch (DKind) {
  7928. case OMPD_parallel_for:
  7929. case OMPD_parallel_for_simd:
  7930. case OMPD_distribute_parallel_for:
  7931. case OMPD_distribute_parallel_for_simd:
  7932. case OMPD_teams_distribute_parallel_for:
  7933. case OMPD_teams_distribute_parallel_for_simd:
  7934. case OMPD_target_parallel_for:
  7935. case OMPD_target_parallel_for_simd:
  7936. case OMPD_target_teams_distribute_parallel_for:
  7937. case OMPD_target_teams_distribute_parallel_for_simd:
  7938. CaptureRegion = OMPD_parallel;
  7939. break;
  7940. case OMPD_for:
  7941. case OMPD_for_simd:
  7942. // Do not capture schedule-clause expressions.
  7943. break;
  7944. case OMPD_task:
  7945. case OMPD_taskloop:
  7946. case OMPD_taskloop_simd:
  7947. case OMPD_target_data:
  7948. case OMPD_target_enter_data:
  7949. case OMPD_target_exit_data:
  7950. case OMPD_target_update:
  7951. case OMPD_teams:
  7952. case OMPD_teams_distribute:
  7953. case OMPD_teams_distribute_simd:
  7954. case OMPD_target_teams_distribute:
  7955. case OMPD_target_teams_distribute_simd:
  7956. case OMPD_target:
  7957. case OMPD_target_simd:
  7958. case OMPD_target_parallel:
  7959. case OMPD_cancel:
  7960. case OMPD_parallel:
  7961. case OMPD_parallel_sections:
  7962. case OMPD_threadprivate:
  7963. case OMPD_taskyield:
  7964. case OMPD_barrier:
  7965. case OMPD_taskwait:
  7966. case OMPD_cancellation_point:
  7967. case OMPD_flush:
  7968. case OMPD_declare_reduction:
  7969. case OMPD_declare_simd:
  7970. case OMPD_declare_target:
  7971. case OMPD_end_declare_target:
  7972. case OMPD_simd:
  7973. case OMPD_sections:
  7974. case OMPD_section:
  7975. case OMPD_single:
  7976. case OMPD_master:
  7977. case OMPD_critical:
  7978. case OMPD_taskgroup:
  7979. case OMPD_distribute:
  7980. case OMPD_ordered:
  7981. case OMPD_atomic:
  7982. case OMPD_distribute_simd:
  7983. case OMPD_target_teams:
  7984. case OMPD_requires:
  7985. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7986. case OMPD_unknown:
  7987. llvm_unreachable("Unknown OpenMP directive");
  7988. }
  7989. break;
  7990. case OMPC_dist_schedule:
  7991. switch (DKind) {
  7992. case OMPD_teams_distribute_parallel_for:
  7993. case OMPD_teams_distribute_parallel_for_simd:
  7994. case OMPD_teams_distribute:
  7995. case OMPD_teams_distribute_simd:
  7996. case OMPD_target_teams_distribute_parallel_for:
  7997. case OMPD_target_teams_distribute_parallel_for_simd:
  7998. case OMPD_target_teams_distribute:
  7999. case OMPD_target_teams_distribute_simd:
  8000. CaptureRegion = OMPD_teams;
  8001. break;
  8002. case OMPD_distribute_parallel_for:
  8003. case OMPD_distribute_parallel_for_simd:
  8004. case OMPD_distribute:
  8005. case OMPD_distribute_simd:
  8006. // Do not capture thread_limit-clause expressions.
  8007. break;
  8008. case OMPD_parallel_for:
  8009. case OMPD_parallel_for_simd:
  8010. case OMPD_target_parallel_for_simd:
  8011. case OMPD_target_parallel_for:
  8012. case OMPD_task:
  8013. case OMPD_taskloop:
  8014. case OMPD_taskloop_simd:
  8015. case OMPD_target_data:
  8016. case OMPD_target_enter_data:
  8017. case OMPD_target_exit_data:
  8018. case OMPD_target_update:
  8019. case OMPD_teams:
  8020. case OMPD_target:
  8021. case OMPD_target_simd:
  8022. case OMPD_target_parallel:
  8023. case OMPD_cancel:
  8024. case OMPD_parallel:
  8025. case OMPD_parallel_sections:
  8026. case OMPD_threadprivate:
  8027. case OMPD_taskyield:
  8028. case OMPD_barrier:
  8029. case OMPD_taskwait:
  8030. case OMPD_cancellation_point:
  8031. case OMPD_flush:
  8032. case OMPD_declare_reduction:
  8033. case OMPD_declare_simd:
  8034. case OMPD_declare_target:
  8035. case OMPD_end_declare_target:
  8036. case OMPD_simd:
  8037. case OMPD_for:
  8038. case OMPD_for_simd:
  8039. case OMPD_sections:
  8040. case OMPD_section:
  8041. case OMPD_single:
  8042. case OMPD_master:
  8043. case OMPD_critical:
  8044. case OMPD_taskgroup:
  8045. case OMPD_ordered:
  8046. case OMPD_atomic:
  8047. case OMPD_target_teams:
  8048. case OMPD_requires:
  8049. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8050. case OMPD_unknown:
  8051. llvm_unreachable("Unknown OpenMP directive");
  8052. }
  8053. break;
  8054. case OMPC_device:
  8055. switch (DKind) {
  8056. case OMPD_target_update:
  8057. case OMPD_target_enter_data:
  8058. case OMPD_target_exit_data:
  8059. case OMPD_target:
  8060. case OMPD_target_simd:
  8061. case OMPD_target_teams:
  8062. case OMPD_target_parallel:
  8063. case OMPD_target_teams_distribute:
  8064. case OMPD_target_teams_distribute_simd:
  8065. case OMPD_target_parallel_for:
  8066. case OMPD_target_parallel_for_simd:
  8067. case OMPD_target_teams_distribute_parallel_for:
  8068. case OMPD_target_teams_distribute_parallel_for_simd:
  8069. CaptureRegion = OMPD_task;
  8070. break;
  8071. case OMPD_target_data:
  8072. // Do not capture device-clause expressions.
  8073. break;
  8074. case OMPD_teams_distribute_parallel_for:
  8075. case OMPD_teams_distribute_parallel_for_simd:
  8076. case OMPD_teams:
  8077. case OMPD_teams_distribute:
  8078. case OMPD_teams_distribute_simd:
  8079. case OMPD_distribute_parallel_for:
  8080. case OMPD_distribute_parallel_for_simd:
  8081. case OMPD_task:
  8082. case OMPD_taskloop:
  8083. case OMPD_taskloop_simd:
  8084. case OMPD_cancel:
  8085. case OMPD_parallel:
  8086. case OMPD_parallel_sections:
  8087. case OMPD_parallel_for:
  8088. case OMPD_parallel_for_simd:
  8089. case OMPD_threadprivate:
  8090. case OMPD_taskyield:
  8091. case OMPD_barrier:
  8092. case OMPD_taskwait:
  8093. case OMPD_cancellation_point:
  8094. case OMPD_flush:
  8095. case OMPD_declare_reduction:
  8096. case OMPD_declare_simd:
  8097. case OMPD_declare_target:
  8098. case OMPD_end_declare_target:
  8099. case OMPD_simd:
  8100. case OMPD_for:
  8101. case OMPD_for_simd:
  8102. case OMPD_sections:
  8103. case OMPD_section:
  8104. case OMPD_single:
  8105. case OMPD_master:
  8106. case OMPD_critical:
  8107. case OMPD_taskgroup:
  8108. case OMPD_distribute:
  8109. case OMPD_ordered:
  8110. case OMPD_atomic:
  8111. case OMPD_distribute_simd:
  8112. case OMPD_requires:
  8113. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8114. case OMPD_unknown:
  8115. llvm_unreachable("Unknown OpenMP directive");
  8116. }
  8117. break;
  8118. case OMPC_firstprivate:
  8119. case OMPC_lastprivate:
  8120. case OMPC_reduction:
  8121. case OMPC_task_reduction:
  8122. case OMPC_in_reduction:
  8123. case OMPC_linear:
  8124. case OMPC_default:
  8125. case OMPC_proc_bind:
  8126. case OMPC_final:
  8127. case OMPC_safelen:
  8128. case OMPC_simdlen:
  8129. case OMPC_collapse:
  8130. case OMPC_private:
  8131. case OMPC_shared:
  8132. case OMPC_aligned:
  8133. case OMPC_copyin:
  8134. case OMPC_copyprivate:
  8135. case OMPC_ordered:
  8136. case OMPC_nowait:
  8137. case OMPC_untied:
  8138. case OMPC_mergeable:
  8139. case OMPC_threadprivate:
  8140. case OMPC_flush:
  8141. case OMPC_read:
  8142. case OMPC_write:
  8143. case OMPC_update:
  8144. case OMPC_capture:
  8145. case OMPC_seq_cst:
  8146. case OMPC_depend:
  8147. case OMPC_threads:
  8148. case OMPC_simd:
  8149. case OMPC_map:
  8150. case OMPC_priority:
  8151. case OMPC_grainsize:
  8152. case OMPC_nogroup:
  8153. case OMPC_num_tasks:
  8154. case OMPC_hint:
  8155. case OMPC_defaultmap:
  8156. case OMPC_unknown:
  8157. case OMPC_uniform:
  8158. case OMPC_to:
  8159. case OMPC_from:
  8160. case OMPC_use_device_ptr:
  8161. case OMPC_is_device_ptr:
  8162. case OMPC_unified_address:
  8163. case OMPC_unified_shared_memory:
  8164. case OMPC_reverse_offload:
  8165. case OMPC_dynamic_allocators:
  8166. case OMPC_atomic_default_mem_order:
  8167. llvm_unreachable("Unexpected OpenMP clause.");
  8168. }
  8169. return CaptureRegion;
  8170. }
  8171. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  8172. Expr *Condition, SourceLocation StartLoc,
  8173. SourceLocation LParenLoc,
  8174. SourceLocation NameModifierLoc,
  8175. SourceLocation ColonLoc,
  8176. SourceLocation EndLoc) {
  8177. Expr *ValExpr = Condition;
  8178. Stmt *HelperValStmt = nullptr;
  8179. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8180. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8181. !Condition->isInstantiationDependent() &&
  8182. !Condition->containsUnexpandedParameterPack()) {
  8183. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8184. if (Val.isInvalid())
  8185. return nullptr;
  8186. ValExpr = Val.get();
  8187. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8188. CaptureRegion =
  8189. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  8190. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8191. ValExpr = MakeFullExpr(ValExpr).get();
  8192. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8193. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8194. HelperValStmt = buildPreInits(Context, Captures);
  8195. }
  8196. }
  8197. return new (Context)
  8198. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  8199. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  8200. }
  8201. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  8202. SourceLocation StartLoc,
  8203. SourceLocation LParenLoc,
  8204. SourceLocation EndLoc) {
  8205. Expr *ValExpr = Condition;
  8206. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8207. !Condition->isInstantiationDependent() &&
  8208. !Condition->containsUnexpandedParameterPack()) {
  8209. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8210. if (Val.isInvalid())
  8211. return nullptr;
  8212. ValExpr = MakeFullExpr(Val.get()).get();
  8213. }
  8214. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8215. }
  8216. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  8217. Expr *Op) {
  8218. if (!Op)
  8219. return ExprError();
  8220. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  8221. public:
  8222. IntConvertDiagnoser()
  8223. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  8224. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8225. QualType T) override {
  8226. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  8227. }
  8228. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  8229. QualType T) override {
  8230. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  8231. }
  8232. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  8233. QualType T,
  8234. QualType ConvTy) override {
  8235. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  8236. }
  8237. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  8238. QualType ConvTy) override {
  8239. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8240. << ConvTy->isEnumeralType() << ConvTy;
  8241. }
  8242. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8243. QualType T) override {
  8244. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  8245. }
  8246. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  8247. QualType ConvTy) override {
  8248. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8249. << ConvTy->isEnumeralType() << ConvTy;
  8250. }
  8251. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  8252. QualType) override {
  8253. llvm_unreachable("conversion functions are permitted");
  8254. }
  8255. } ConvertDiagnoser;
  8256. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  8257. }
  8258. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  8259. OpenMPClauseKind CKind,
  8260. bool StrictlyPositive) {
  8261. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  8262. !ValExpr->isInstantiationDependent()) {
  8263. SourceLocation Loc = ValExpr->getExprLoc();
  8264. ExprResult Value =
  8265. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  8266. if (Value.isInvalid())
  8267. return false;
  8268. ValExpr = Value.get();
  8269. // The expression must evaluate to a non-negative integer value.
  8270. llvm::APSInt Result;
  8271. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  8272. Result.isSigned() &&
  8273. !((!StrictlyPositive && Result.isNonNegative()) ||
  8274. (StrictlyPositive && Result.isStrictlyPositive()))) {
  8275. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  8276. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8277. << ValExpr->getSourceRange();
  8278. return false;
  8279. }
  8280. }
  8281. return true;
  8282. }
  8283. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  8284. SourceLocation StartLoc,
  8285. SourceLocation LParenLoc,
  8286. SourceLocation EndLoc) {
  8287. Expr *ValExpr = NumThreads;
  8288. Stmt *HelperValStmt = nullptr;
  8289. // OpenMP [2.5, Restrictions]
  8290. // The num_threads expression must evaluate to a positive integer value.
  8291. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  8292. /*StrictlyPositive=*/true))
  8293. return nullptr;
  8294. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8295. OpenMPDirectiveKind CaptureRegion =
  8296. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  8297. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8298. ValExpr = MakeFullExpr(ValExpr).get();
  8299. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8300. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8301. HelperValStmt = buildPreInits(Context, Captures);
  8302. }
  8303. return new (Context) OMPNumThreadsClause(
  8304. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  8305. }
  8306. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  8307. OpenMPClauseKind CKind,
  8308. bool StrictlyPositive) {
  8309. if (!E)
  8310. return ExprError();
  8311. if (E->isValueDependent() || E->isTypeDependent() ||
  8312. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  8313. return E;
  8314. llvm::APSInt Result;
  8315. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  8316. if (ICE.isInvalid())
  8317. return ExprError();
  8318. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  8319. (!StrictlyPositive && !Result.isNonNegative())) {
  8320. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  8321. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8322. << E->getSourceRange();
  8323. return ExprError();
  8324. }
  8325. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  8326. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  8327. << E->getSourceRange();
  8328. return ExprError();
  8329. }
  8330. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  8331. DSAStack->setAssociatedLoops(Result.getExtValue());
  8332. else if (CKind == OMPC_ordered)
  8333. DSAStack->setAssociatedLoops(Result.getExtValue());
  8334. return ICE;
  8335. }
  8336. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  8337. SourceLocation LParenLoc,
  8338. SourceLocation EndLoc) {
  8339. // OpenMP [2.8.1, simd construct, Description]
  8340. // The parameter of the safelen clause must be a constant
  8341. // positive integer expression.
  8342. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  8343. if (Safelen.isInvalid())
  8344. return nullptr;
  8345. return new (Context)
  8346. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  8347. }
  8348. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8349. SourceLocation LParenLoc,
  8350. SourceLocation EndLoc) {
  8351. // OpenMP [2.8.1, simd construct, Description]
  8352. // The parameter of the simdlen clause must be a constant
  8353. // positive integer expression.
  8354. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8355. if (Simdlen.isInvalid())
  8356. return nullptr;
  8357. return new (Context)
  8358. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8359. }
  8360. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  8361. SourceLocation StartLoc,
  8362. SourceLocation LParenLoc,
  8363. SourceLocation EndLoc) {
  8364. // OpenMP [2.7.1, loop construct, Description]
  8365. // OpenMP [2.8.1, simd construct, Description]
  8366. // OpenMP [2.9.6, distribute construct, Description]
  8367. // The parameter of the collapse clause must be a constant
  8368. // positive integer expression.
  8369. ExprResult NumForLoopsResult =
  8370. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  8371. if (NumForLoopsResult.isInvalid())
  8372. return nullptr;
  8373. return new (Context)
  8374. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  8375. }
  8376. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  8377. SourceLocation EndLoc,
  8378. SourceLocation LParenLoc,
  8379. Expr *NumForLoops) {
  8380. // OpenMP [2.7.1, loop construct, Description]
  8381. // OpenMP [2.8.1, simd construct, Description]
  8382. // OpenMP [2.9.6, distribute construct, Description]
  8383. // The parameter of the ordered clause must be a constant
  8384. // positive integer expression if any.
  8385. if (NumForLoops && LParenLoc.isValid()) {
  8386. ExprResult NumForLoopsResult =
  8387. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  8388. if (NumForLoopsResult.isInvalid())
  8389. return nullptr;
  8390. NumForLoops = NumForLoopsResult.get();
  8391. } else {
  8392. NumForLoops = nullptr;
  8393. }
  8394. auto *Clause = OMPOrderedClause::Create(
  8395. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  8396. StartLoc, LParenLoc, EndLoc);
  8397. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  8398. return Clause;
  8399. }
  8400. OMPClause *Sema::ActOnOpenMPSimpleClause(
  8401. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  8402. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8403. OMPClause *Res = nullptr;
  8404. switch (Kind) {
  8405. case OMPC_default:
  8406. Res =
  8407. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  8408. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8409. break;
  8410. case OMPC_proc_bind:
  8411. Res = ActOnOpenMPProcBindClause(
  8412. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  8413. LParenLoc, EndLoc);
  8414. break;
  8415. case OMPC_atomic_default_mem_order:
  8416. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  8417. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  8418. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8419. break;
  8420. case OMPC_if:
  8421. case OMPC_final:
  8422. case OMPC_num_threads:
  8423. case OMPC_safelen:
  8424. case OMPC_simdlen:
  8425. case OMPC_collapse:
  8426. case OMPC_schedule:
  8427. case OMPC_private:
  8428. case OMPC_firstprivate:
  8429. case OMPC_lastprivate:
  8430. case OMPC_shared:
  8431. case OMPC_reduction:
  8432. case OMPC_task_reduction:
  8433. case OMPC_in_reduction:
  8434. case OMPC_linear:
  8435. case OMPC_aligned:
  8436. case OMPC_copyin:
  8437. case OMPC_copyprivate:
  8438. case OMPC_ordered:
  8439. case OMPC_nowait:
  8440. case OMPC_untied:
  8441. case OMPC_mergeable:
  8442. case OMPC_threadprivate:
  8443. case OMPC_flush:
  8444. case OMPC_read:
  8445. case OMPC_write:
  8446. case OMPC_update:
  8447. case OMPC_capture:
  8448. case OMPC_seq_cst:
  8449. case OMPC_depend:
  8450. case OMPC_device:
  8451. case OMPC_threads:
  8452. case OMPC_simd:
  8453. case OMPC_map:
  8454. case OMPC_num_teams:
  8455. case OMPC_thread_limit:
  8456. case OMPC_priority:
  8457. case OMPC_grainsize:
  8458. case OMPC_nogroup:
  8459. case OMPC_num_tasks:
  8460. case OMPC_hint:
  8461. case OMPC_dist_schedule:
  8462. case OMPC_defaultmap:
  8463. case OMPC_unknown:
  8464. case OMPC_uniform:
  8465. case OMPC_to:
  8466. case OMPC_from:
  8467. case OMPC_use_device_ptr:
  8468. case OMPC_is_device_ptr:
  8469. case OMPC_unified_address:
  8470. case OMPC_unified_shared_memory:
  8471. case OMPC_reverse_offload:
  8472. case OMPC_dynamic_allocators:
  8473. llvm_unreachable("Clause is not allowed.");
  8474. }
  8475. return Res;
  8476. }
  8477. static std::string
  8478. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  8479. ArrayRef<unsigned> Exclude = llvm::None) {
  8480. SmallString<256> Buffer;
  8481. llvm::raw_svector_ostream Out(Buffer);
  8482. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  8483. unsigned Skipped = Exclude.size();
  8484. auto S = Exclude.begin(), E = Exclude.end();
  8485. for (unsigned I = First; I < Last; ++I) {
  8486. if (std::find(S, E, I) != E) {
  8487. --Skipped;
  8488. continue;
  8489. }
  8490. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  8491. if (I == Bound - Skipped)
  8492. Out << " or ";
  8493. else if (I != Bound + 1 - Skipped)
  8494. Out << ", ";
  8495. }
  8496. return Out.str();
  8497. }
  8498. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  8499. SourceLocation KindKwLoc,
  8500. SourceLocation StartLoc,
  8501. SourceLocation LParenLoc,
  8502. SourceLocation EndLoc) {
  8503. if (Kind == OMPC_DEFAULT_unknown) {
  8504. static_assert(OMPC_DEFAULT_unknown > 0,
  8505. "OMPC_DEFAULT_unknown not greater than 0");
  8506. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8507. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  8508. /*Last=*/OMPC_DEFAULT_unknown)
  8509. << getOpenMPClauseName(OMPC_default);
  8510. return nullptr;
  8511. }
  8512. switch (Kind) {
  8513. case OMPC_DEFAULT_none:
  8514. DSAStack->setDefaultDSANone(KindKwLoc);
  8515. break;
  8516. case OMPC_DEFAULT_shared:
  8517. DSAStack->setDefaultDSAShared(KindKwLoc);
  8518. break;
  8519. case OMPC_DEFAULT_unknown:
  8520. llvm_unreachable("Clause kind is not allowed.");
  8521. break;
  8522. }
  8523. return new (Context)
  8524. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8525. }
  8526. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  8527. SourceLocation KindKwLoc,
  8528. SourceLocation StartLoc,
  8529. SourceLocation LParenLoc,
  8530. SourceLocation EndLoc) {
  8531. if (Kind == OMPC_PROC_BIND_unknown) {
  8532. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8533. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  8534. /*Last=*/OMPC_PROC_BIND_unknown)
  8535. << getOpenMPClauseName(OMPC_proc_bind);
  8536. return nullptr;
  8537. }
  8538. return new (Context)
  8539. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8540. }
  8541. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  8542. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  8543. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8544. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  8545. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8546. << getListOfPossibleValues(
  8547. OMPC_atomic_default_mem_order, /*First=*/0,
  8548. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  8549. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  8550. return nullptr;
  8551. }
  8552. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  8553. LParenLoc, EndLoc);
  8554. }
  8555. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  8556. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  8557. SourceLocation StartLoc, SourceLocation LParenLoc,
  8558. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  8559. SourceLocation EndLoc) {
  8560. OMPClause *Res = nullptr;
  8561. switch (Kind) {
  8562. case OMPC_schedule:
  8563. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  8564. assert(Argument.size() == NumberOfElements &&
  8565. ArgumentLoc.size() == NumberOfElements);
  8566. Res = ActOnOpenMPScheduleClause(
  8567. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  8568. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  8569. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  8570. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  8571. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  8572. break;
  8573. case OMPC_if:
  8574. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  8575. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  8576. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  8577. DelimLoc, EndLoc);
  8578. break;
  8579. case OMPC_dist_schedule:
  8580. Res = ActOnOpenMPDistScheduleClause(
  8581. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  8582. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  8583. break;
  8584. case OMPC_defaultmap:
  8585. enum { Modifier, DefaultmapKind };
  8586. Res = ActOnOpenMPDefaultmapClause(
  8587. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  8588. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  8589. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  8590. EndLoc);
  8591. break;
  8592. case OMPC_final:
  8593. case OMPC_num_threads:
  8594. case OMPC_safelen:
  8595. case OMPC_simdlen:
  8596. case OMPC_collapse:
  8597. case OMPC_default:
  8598. case OMPC_proc_bind:
  8599. case OMPC_private:
  8600. case OMPC_firstprivate:
  8601. case OMPC_lastprivate:
  8602. case OMPC_shared:
  8603. case OMPC_reduction:
  8604. case OMPC_task_reduction:
  8605. case OMPC_in_reduction:
  8606. case OMPC_linear:
  8607. case OMPC_aligned:
  8608. case OMPC_copyin:
  8609. case OMPC_copyprivate:
  8610. case OMPC_ordered:
  8611. case OMPC_nowait:
  8612. case OMPC_untied:
  8613. case OMPC_mergeable:
  8614. case OMPC_threadprivate:
  8615. case OMPC_flush:
  8616. case OMPC_read:
  8617. case OMPC_write:
  8618. case OMPC_update:
  8619. case OMPC_capture:
  8620. case OMPC_seq_cst:
  8621. case OMPC_depend:
  8622. case OMPC_device:
  8623. case OMPC_threads:
  8624. case OMPC_simd:
  8625. case OMPC_map:
  8626. case OMPC_num_teams:
  8627. case OMPC_thread_limit:
  8628. case OMPC_priority:
  8629. case OMPC_grainsize:
  8630. case OMPC_nogroup:
  8631. case OMPC_num_tasks:
  8632. case OMPC_hint:
  8633. case OMPC_unknown:
  8634. case OMPC_uniform:
  8635. case OMPC_to:
  8636. case OMPC_from:
  8637. case OMPC_use_device_ptr:
  8638. case OMPC_is_device_ptr:
  8639. case OMPC_unified_address:
  8640. case OMPC_unified_shared_memory:
  8641. case OMPC_reverse_offload:
  8642. case OMPC_dynamic_allocators:
  8643. case OMPC_atomic_default_mem_order:
  8644. llvm_unreachable("Clause is not allowed.");
  8645. }
  8646. return Res;
  8647. }
  8648. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8649. OpenMPScheduleClauseModifier M2,
  8650. SourceLocation M1Loc, SourceLocation M2Loc) {
  8651. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8652. SmallVector<unsigned, 2> Excluded;
  8653. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8654. Excluded.push_back(M2);
  8655. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8656. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8657. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8658. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8659. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8660. << getListOfPossibleValues(OMPC_schedule,
  8661. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8662. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8663. Excluded)
  8664. << getOpenMPClauseName(OMPC_schedule);
  8665. return true;
  8666. }
  8667. return false;
  8668. }
  8669. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8670. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8671. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8672. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8673. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8674. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8675. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8676. return nullptr;
  8677. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8678. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8679. // but not both.
  8680. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8681. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8682. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8683. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8684. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8685. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8686. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8687. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8688. return nullptr;
  8689. }
  8690. if (Kind == OMPC_SCHEDULE_unknown) {
  8691. std::string Values;
  8692. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8693. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8694. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8695. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8696. Exclude);
  8697. } else {
  8698. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8699. /*Last=*/OMPC_SCHEDULE_unknown);
  8700. }
  8701. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8702. << Values << getOpenMPClauseName(OMPC_schedule);
  8703. return nullptr;
  8704. }
  8705. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8706. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8707. // schedule(guided).
  8708. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8709. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8710. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8711. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8712. diag::err_omp_schedule_nonmonotonic_static);
  8713. return nullptr;
  8714. }
  8715. Expr *ValExpr = ChunkSize;
  8716. Stmt *HelperValStmt = nullptr;
  8717. if (ChunkSize) {
  8718. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8719. !ChunkSize->isInstantiationDependent() &&
  8720. !ChunkSize->containsUnexpandedParameterPack()) {
  8721. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  8722. ExprResult Val =
  8723. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8724. if (Val.isInvalid())
  8725. return nullptr;
  8726. ValExpr = Val.get();
  8727. // OpenMP [2.7.1, Restrictions]
  8728. // chunk_size must be a loop invariant integer expression with a positive
  8729. // value.
  8730. llvm::APSInt Result;
  8731. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8732. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8733. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8734. << "schedule" << 1 << ChunkSize->getSourceRange();
  8735. return nullptr;
  8736. }
  8737. } else if (getOpenMPCaptureRegionForClause(
  8738. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8739. OMPD_unknown &&
  8740. !CurContext->isDependentContext()) {
  8741. ValExpr = MakeFullExpr(ValExpr).get();
  8742. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8743. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8744. HelperValStmt = buildPreInits(Context, Captures);
  8745. }
  8746. }
  8747. }
  8748. return new (Context)
  8749. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8750. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8751. }
  8752. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8753. SourceLocation StartLoc,
  8754. SourceLocation EndLoc) {
  8755. OMPClause *Res = nullptr;
  8756. switch (Kind) {
  8757. case OMPC_ordered:
  8758. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8759. break;
  8760. case OMPC_nowait:
  8761. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8762. break;
  8763. case OMPC_untied:
  8764. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8765. break;
  8766. case OMPC_mergeable:
  8767. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8768. break;
  8769. case OMPC_read:
  8770. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8771. break;
  8772. case OMPC_write:
  8773. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8774. break;
  8775. case OMPC_update:
  8776. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8777. break;
  8778. case OMPC_capture:
  8779. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8780. break;
  8781. case OMPC_seq_cst:
  8782. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8783. break;
  8784. case OMPC_threads:
  8785. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8786. break;
  8787. case OMPC_simd:
  8788. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8789. break;
  8790. case OMPC_nogroup:
  8791. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8792. break;
  8793. case OMPC_unified_address:
  8794. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  8795. break;
  8796. case OMPC_unified_shared_memory:
  8797. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8798. break;
  8799. case OMPC_reverse_offload:
  8800. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  8801. break;
  8802. case OMPC_dynamic_allocators:
  8803. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8804. break;
  8805. case OMPC_if:
  8806. case OMPC_final:
  8807. case OMPC_num_threads:
  8808. case OMPC_safelen:
  8809. case OMPC_simdlen:
  8810. case OMPC_collapse:
  8811. case OMPC_schedule:
  8812. case OMPC_private:
  8813. case OMPC_firstprivate:
  8814. case OMPC_lastprivate:
  8815. case OMPC_shared:
  8816. case OMPC_reduction:
  8817. case OMPC_task_reduction:
  8818. case OMPC_in_reduction:
  8819. case OMPC_linear:
  8820. case OMPC_aligned:
  8821. case OMPC_copyin:
  8822. case OMPC_copyprivate:
  8823. case OMPC_default:
  8824. case OMPC_proc_bind:
  8825. case OMPC_threadprivate:
  8826. case OMPC_flush:
  8827. case OMPC_depend:
  8828. case OMPC_device:
  8829. case OMPC_map:
  8830. case OMPC_num_teams:
  8831. case OMPC_thread_limit:
  8832. case OMPC_priority:
  8833. case OMPC_grainsize:
  8834. case OMPC_num_tasks:
  8835. case OMPC_hint:
  8836. case OMPC_dist_schedule:
  8837. case OMPC_defaultmap:
  8838. case OMPC_unknown:
  8839. case OMPC_uniform:
  8840. case OMPC_to:
  8841. case OMPC_from:
  8842. case OMPC_use_device_ptr:
  8843. case OMPC_is_device_ptr:
  8844. case OMPC_atomic_default_mem_order:
  8845. llvm_unreachable("Clause is not allowed.");
  8846. }
  8847. return Res;
  8848. }
  8849. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8850. SourceLocation EndLoc) {
  8851. DSAStack->setNowaitRegion();
  8852. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8853. }
  8854. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8855. SourceLocation EndLoc) {
  8856. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8857. }
  8858. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8859. SourceLocation EndLoc) {
  8860. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8861. }
  8862. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8863. SourceLocation EndLoc) {
  8864. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8865. }
  8866. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8867. SourceLocation EndLoc) {
  8868. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8869. }
  8870. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8871. SourceLocation EndLoc) {
  8872. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8873. }
  8874. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8875. SourceLocation EndLoc) {
  8876. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8877. }
  8878. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8879. SourceLocation EndLoc) {
  8880. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8881. }
  8882. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8883. SourceLocation EndLoc) {
  8884. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8885. }
  8886. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8887. SourceLocation EndLoc) {
  8888. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8889. }
  8890. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8891. SourceLocation EndLoc) {
  8892. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8893. }
  8894. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  8895. SourceLocation EndLoc) {
  8896. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  8897. }
  8898. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  8899. SourceLocation EndLoc) {
  8900. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8901. }
  8902. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  8903. SourceLocation EndLoc) {
  8904. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  8905. }
  8906. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  8907. SourceLocation EndLoc) {
  8908. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8909. }
  8910. OMPClause *Sema::ActOnOpenMPVarListClause(
  8911. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8912. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8913. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8914. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8915. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8916. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8917. SourceLocation DepLinMapLoc) {
  8918. OMPClause *Res = nullptr;
  8919. switch (Kind) {
  8920. case OMPC_private:
  8921. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8922. break;
  8923. case OMPC_firstprivate:
  8924. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8925. break;
  8926. case OMPC_lastprivate:
  8927. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8928. break;
  8929. case OMPC_shared:
  8930. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8931. break;
  8932. case OMPC_reduction:
  8933. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8934. EndLoc, ReductionIdScopeSpec, ReductionId);
  8935. break;
  8936. case OMPC_task_reduction:
  8937. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8938. EndLoc, ReductionIdScopeSpec,
  8939. ReductionId);
  8940. break;
  8941. case OMPC_in_reduction:
  8942. Res =
  8943. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8944. EndLoc, ReductionIdScopeSpec, ReductionId);
  8945. break;
  8946. case OMPC_linear:
  8947. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8948. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8949. break;
  8950. case OMPC_aligned:
  8951. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8952. ColonLoc, EndLoc);
  8953. break;
  8954. case OMPC_copyin:
  8955. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8956. break;
  8957. case OMPC_copyprivate:
  8958. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8959. break;
  8960. case OMPC_flush:
  8961. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8962. break;
  8963. case OMPC_depend:
  8964. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8965. StartLoc, LParenLoc, EndLoc);
  8966. break;
  8967. case OMPC_map:
  8968. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8969. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8970. LParenLoc, EndLoc);
  8971. break;
  8972. case OMPC_to:
  8973. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8974. break;
  8975. case OMPC_from:
  8976. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8977. break;
  8978. case OMPC_use_device_ptr:
  8979. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8980. break;
  8981. case OMPC_is_device_ptr:
  8982. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8983. break;
  8984. case OMPC_if:
  8985. case OMPC_final:
  8986. case OMPC_num_threads:
  8987. case OMPC_safelen:
  8988. case OMPC_simdlen:
  8989. case OMPC_collapse:
  8990. case OMPC_default:
  8991. case OMPC_proc_bind:
  8992. case OMPC_schedule:
  8993. case OMPC_ordered:
  8994. case OMPC_nowait:
  8995. case OMPC_untied:
  8996. case OMPC_mergeable:
  8997. case OMPC_threadprivate:
  8998. case OMPC_read:
  8999. case OMPC_write:
  9000. case OMPC_update:
  9001. case OMPC_capture:
  9002. case OMPC_seq_cst:
  9003. case OMPC_device:
  9004. case OMPC_threads:
  9005. case OMPC_simd:
  9006. case OMPC_num_teams:
  9007. case OMPC_thread_limit:
  9008. case OMPC_priority:
  9009. case OMPC_grainsize:
  9010. case OMPC_nogroup:
  9011. case OMPC_num_tasks:
  9012. case OMPC_hint:
  9013. case OMPC_dist_schedule:
  9014. case OMPC_defaultmap:
  9015. case OMPC_unknown:
  9016. case OMPC_uniform:
  9017. case OMPC_unified_address:
  9018. case OMPC_unified_shared_memory:
  9019. case OMPC_reverse_offload:
  9020. case OMPC_dynamic_allocators:
  9021. case OMPC_atomic_default_mem_order:
  9022. llvm_unreachable("Clause is not allowed.");
  9023. }
  9024. return Res;
  9025. }
  9026. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  9027. ExprObjectKind OK, SourceLocation Loc) {
  9028. ExprResult Res = BuildDeclRefExpr(
  9029. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  9030. if (!Res.isUsable())
  9031. return ExprError();
  9032. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  9033. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  9034. if (!Res.isUsable())
  9035. return ExprError();
  9036. }
  9037. if (VK != VK_LValue && Res.get()->isGLValue()) {
  9038. Res = DefaultLvalueConversion(Res.get());
  9039. if (!Res.isUsable())
  9040. return ExprError();
  9041. }
  9042. return Res;
  9043. }
  9044. static std::pair<ValueDecl *, bool>
  9045. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  9046. SourceRange &ERange, bool AllowArraySection = false) {
  9047. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  9048. RefExpr->containsUnexpandedParameterPack())
  9049. return std::make_pair(nullptr, true);
  9050. // OpenMP [3.1, C/C++]
  9051. // A list item is a variable name.
  9052. // OpenMP [2.9.3.3, Restrictions, p.1]
  9053. // A variable that is part of another variable (as an array or
  9054. // structure element) cannot appear in a private clause.
  9055. RefExpr = RefExpr->IgnoreParens();
  9056. enum {
  9057. NoArrayExpr = -1,
  9058. ArraySubscript = 0,
  9059. OMPArraySection = 1
  9060. } IsArrayExpr = NoArrayExpr;
  9061. if (AllowArraySection) {
  9062. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  9063. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  9064. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9065. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9066. RefExpr = Base;
  9067. IsArrayExpr = ArraySubscript;
  9068. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  9069. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9070. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  9071. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9072. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9073. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9074. RefExpr = Base;
  9075. IsArrayExpr = OMPArraySection;
  9076. }
  9077. }
  9078. ELoc = RefExpr->getExprLoc();
  9079. ERange = RefExpr->getSourceRange();
  9080. RefExpr = RefExpr->IgnoreParenImpCasts();
  9081. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  9082. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  9083. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  9084. (S.getCurrentThisType().isNull() || !ME ||
  9085. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  9086. !isa<FieldDecl>(ME->getMemberDecl()))) {
  9087. if (IsArrayExpr != NoArrayExpr) {
  9088. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  9089. << ERange;
  9090. } else {
  9091. S.Diag(ELoc,
  9092. AllowArraySection
  9093. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  9094. : diag::err_omp_expected_var_name_member_expr)
  9095. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  9096. }
  9097. return std::make_pair(nullptr, false);
  9098. }
  9099. return std::make_pair(
  9100. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  9101. }
  9102. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  9103. SourceLocation StartLoc,
  9104. SourceLocation LParenLoc,
  9105. SourceLocation EndLoc) {
  9106. SmallVector<Expr *, 8> Vars;
  9107. SmallVector<Expr *, 8> PrivateCopies;
  9108. for (Expr *RefExpr : VarList) {
  9109. assert(RefExpr && "NULL expr in OpenMP private clause.");
  9110. SourceLocation ELoc;
  9111. SourceRange ERange;
  9112. Expr *SimpleRefExpr = RefExpr;
  9113. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9114. if (Res.second) {
  9115. // It will be analyzed later.
  9116. Vars.push_back(RefExpr);
  9117. PrivateCopies.push_back(nullptr);
  9118. }
  9119. ValueDecl *D = Res.first;
  9120. if (!D)
  9121. continue;
  9122. QualType Type = D->getType();
  9123. auto *VD = dyn_cast<VarDecl>(D);
  9124. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9125. // A variable that appears in a private clause must not have an incomplete
  9126. // type or a reference type.
  9127. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  9128. continue;
  9129. Type = Type.getNonReferenceType();
  9130. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9131. // in a Construct]
  9132. // Variables with the predetermined data-sharing attributes may not be
  9133. // listed in data-sharing attributes clauses, except for the cases
  9134. // listed below. For these exceptions only, listing a predetermined
  9135. // variable in a data-sharing attribute clause is allowed and overrides
  9136. // the variable's predetermined data-sharing attributes.
  9137. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9138. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  9139. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9140. << getOpenMPClauseName(OMPC_private);
  9141. reportOriginalDsa(*this, DSAStack, D, DVar);
  9142. continue;
  9143. }
  9144. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9145. // Variably modified types are not supported for tasks.
  9146. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9147. isOpenMPTaskingDirective(CurrDir)) {
  9148. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9149. << getOpenMPClauseName(OMPC_private) << Type
  9150. << getOpenMPDirectiveName(CurrDir);
  9151. bool IsDecl =
  9152. !VD ||
  9153. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9154. Diag(D->getLocation(),
  9155. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9156. << D;
  9157. continue;
  9158. }
  9159. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9160. // A list item cannot appear in both a map clause and a data-sharing
  9161. // attribute clause on the same construct
  9162. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9163. OpenMPClauseKind ConflictKind;
  9164. if (DSAStack->checkMappableExprComponentListsForDecl(
  9165. VD, /*CurrentRegionOnly=*/true,
  9166. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9167. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  9168. ConflictKind = WhereFoundClauseKind;
  9169. return true;
  9170. })) {
  9171. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9172. << getOpenMPClauseName(OMPC_private)
  9173. << getOpenMPClauseName(ConflictKind)
  9174. << getOpenMPDirectiveName(CurrDir);
  9175. reportOriginalDsa(*this, DSAStack, D, DVar);
  9176. continue;
  9177. }
  9178. }
  9179. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  9180. // A variable of class type (or array thereof) that appears in a private
  9181. // clause requires an accessible, unambiguous default constructor for the
  9182. // class type.
  9183. // Generate helper private variable and initialize it with the default
  9184. // value. The address of the original variable is replaced by the address of
  9185. // the new private variable in CodeGen. This new variable is not added to
  9186. // IdResolver, so the code in the OpenMP region uses original variable for
  9187. // proper diagnostics.
  9188. Type = Type.getUnqualifiedType();
  9189. VarDecl *VDPrivate =
  9190. buildVarDecl(*this, ELoc, Type, D->getName(),
  9191. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9192. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9193. ActOnUninitializedDecl(VDPrivate);
  9194. if (VDPrivate->isInvalidDecl())
  9195. continue;
  9196. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9197. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  9198. DeclRefExpr *Ref = nullptr;
  9199. if (!VD && !CurContext->isDependentContext())
  9200. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9201. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  9202. Vars.push_back((VD || CurContext->isDependentContext())
  9203. ? RefExpr->IgnoreParens()
  9204. : Ref);
  9205. PrivateCopies.push_back(VDPrivateRefExpr);
  9206. }
  9207. if (Vars.empty())
  9208. return nullptr;
  9209. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9210. PrivateCopies);
  9211. }
  9212. namespace {
  9213. class DiagsUninitializedSeveretyRAII {
  9214. private:
  9215. DiagnosticsEngine &Diags;
  9216. SourceLocation SavedLoc;
  9217. bool IsIgnored = false;
  9218. public:
  9219. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  9220. bool IsIgnored)
  9221. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  9222. if (!IsIgnored) {
  9223. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  9224. /*Map*/ diag::Severity::Ignored, Loc);
  9225. }
  9226. }
  9227. ~DiagsUninitializedSeveretyRAII() {
  9228. if (!IsIgnored)
  9229. Diags.popMappings(SavedLoc);
  9230. }
  9231. };
  9232. }
  9233. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  9234. SourceLocation StartLoc,
  9235. SourceLocation LParenLoc,
  9236. SourceLocation EndLoc) {
  9237. SmallVector<Expr *, 8> Vars;
  9238. SmallVector<Expr *, 8> PrivateCopies;
  9239. SmallVector<Expr *, 8> Inits;
  9240. SmallVector<Decl *, 4> ExprCaptures;
  9241. bool IsImplicitClause =
  9242. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  9243. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  9244. for (Expr *RefExpr : VarList) {
  9245. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  9246. SourceLocation ELoc;
  9247. SourceRange ERange;
  9248. Expr *SimpleRefExpr = RefExpr;
  9249. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9250. if (Res.second) {
  9251. // It will be analyzed later.
  9252. Vars.push_back(RefExpr);
  9253. PrivateCopies.push_back(nullptr);
  9254. Inits.push_back(nullptr);
  9255. }
  9256. ValueDecl *D = Res.first;
  9257. if (!D)
  9258. continue;
  9259. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  9260. QualType Type = D->getType();
  9261. auto *VD = dyn_cast<VarDecl>(D);
  9262. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9263. // A variable that appears in a private clause must not have an incomplete
  9264. // type or a reference type.
  9265. if (RequireCompleteType(ELoc, Type,
  9266. diag::err_omp_firstprivate_incomplete_type))
  9267. continue;
  9268. Type = Type.getNonReferenceType();
  9269. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  9270. // A variable of class type (or array thereof) that appears in a private
  9271. // clause requires an accessible, unambiguous copy constructor for the
  9272. // class type.
  9273. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9274. // If an implicit firstprivate variable found it was checked already.
  9275. DSAStackTy::DSAVarData TopDVar;
  9276. if (!IsImplicitClause) {
  9277. DSAStackTy::DSAVarData DVar =
  9278. DSAStack->getTopDSA(D, /*FromParent=*/false);
  9279. TopDVar = DVar;
  9280. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9281. bool IsConstant = ElemType.isConstant(Context);
  9282. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  9283. // A list item that specifies a given variable may not appear in more
  9284. // than one clause on the same directive, except that a variable may be
  9285. // specified in both firstprivate and lastprivate clauses.
  9286. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9287. // A list item may appear in a firstprivate or lastprivate clause but not
  9288. // both.
  9289. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  9290. (isOpenMPDistributeDirective(CurrDir) ||
  9291. DVar.CKind != OMPC_lastprivate) &&
  9292. DVar.RefExpr) {
  9293. Diag(ELoc, diag::err_omp_wrong_dsa)
  9294. << getOpenMPClauseName(DVar.CKind)
  9295. << getOpenMPClauseName(OMPC_firstprivate);
  9296. reportOriginalDsa(*this, DSAStack, D, DVar);
  9297. continue;
  9298. }
  9299. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9300. // in a Construct]
  9301. // Variables with the predetermined data-sharing attributes may not be
  9302. // listed in data-sharing attributes clauses, except for the cases
  9303. // listed below. For these exceptions only, listing a predetermined
  9304. // variable in a data-sharing attribute clause is allowed and overrides
  9305. // the variable's predetermined data-sharing attributes.
  9306. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9307. // in a Construct, C/C++, p.2]
  9308. // Variables with const-qualified type having no mutable member may be
  9309. // listed in a firstprivate clause, even if they are static data members.
  9310. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  9311. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  9312. Diag(ELoc, diag::err_omp_wrong_dsa)
  9313. << getOpenMPClauseName(DVar.CKind)
  9314. << getOpenMPClauseName(OMPC_firstprivate);
  9315. reportOriginalDsa(*this, DSAStack, D, DVar);
  9316. continue;
  9317. }
  9318. // OpenMP [2.9.3.4, Restrictions, p.2]
  9319. // A list item that is private within a parallel region must not appear
  9320. // in a firstprivate clause on a worksharing construct if any of the
  9321. // worksharing regions arising from the worksharing construct ever bind
  9322. // to any of the parallel regions arising from the parallel construct.
  9323. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9324. // A list item that is private within a teams region must not appear in a
  9325. // firstprivate clause on a distribute construct if any of the distribute
  9326. // regions arising from the distribute construct ever bind to any of the
  9327. // teams regions arising from the teams construct.
  9328. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9329. // A list item that appears in a reduction clause of a teams construct
  9330. // must not appear in a firstprivate clause on a distribute construct if
  9331. // any of the distribute regions arising from the distribute construct
  9332. // ever bind to any of the teams regions arising from the teams construct.
  9333. if ((isOpenMPWorksharingDirective(CurrDir) ||
  9334. isOpenMPDistributeDirective(CurrDir)) &&
  9335. !isOpenMPParallelDirective(CurrDir) &&
  9336. !isOpenMPTeamsDirective(CurrDir)) {
  9337. DVar = DSAStack->getImplicitDSA(D, true);
  9338. if (DVar.CKind != OMPC_shared &&
  9339. (isOpenMPParallelDirective(DVar.DKind) ||
  9340. isOpenMPTeamsDirective(DVar.DKind) ||
  9341. DVar.DKind == OMPD_unknown)) {
  9342. Diag(ELoc, diag::err_omp_required_access)
  9343. << getOpenMPClauseName(OMPC_firstprivate)
  9344. << getOpenMPClauseName(OMPC_shared);
  9345. reportOriginalDsa(*this, DSAStack, D, DVar);
  9346. continue;
  9347. }
  9348. }
  9349. // OpenMP [2.9.3.4, Restrictions, p.3]
  9350. // A list item that appears in a reduction clause of a parallel construct
  9351. // must not appear in a firstprivate clause on a worksharing or task
  9352. // construct if any of the worksharing or task regions arising from the
  9353. // worksharing or task construct ever bind to any of the parallel regions
  9354. // arising from the parallel construct.
  9355. // OpenMP [2.9.3.4, Restrictions, p.4]
  9356. // A list item that appears in a reduction clause in worksharing
  9357. // construct must not appear in a firstprivate clause in a task construct
  9358. // encountered during execution of any of the worksharing regions arising
  9359. // from the worksharing construct.
  9360. if (isOpenMPTaskingDirective(CurrDir)) {
  9361. DVar = DSAStack->hasInnermostDSA(
  9362. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  9363. [](OpenMPDirectiveKind K) {
  9364. return isOpenMPParallelDirective(K) ||
  9365. isOpenMPWorksharingDirective(K) ||
  9366. isOpenMPTeamsDirective(K);
  9367. },
  9368. /*FromParent=*/true);
  9369. if (DVar.CKind == OMPC_reduction &&
  9370. (isOpenMPParallelDirective(DVar.DKind) ||
  9371. isOpenMPWorksharingDirective(DVar.DKind) ||
  9372. isOpenMPTeamsDirective(DVar.DKind))) {
  9373. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  9374. << getOpenMPDirectiveName(DVar.DKind);
  9375. reportOriginalDsa(*this, DSAStack, D, DVar);
  9376. continue;
  9377. }
  9378. }
  9379. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9380. // A list item cannot appear in both a map clause and a data-sharing
  9381. // attribute clause on the same construct
  9382. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9383. OpenMPClauseKind ConflictKind;
  9384. if (DSAStack->checkMappableExprComponentListsForDecl(
  9385. VD, /*CurrentRegionOnly=*/true,
  9386. [&ConflictKind](
  9387. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9388. OpenMPClauseKind WhereFoundClauseKind) {
  9389. ConflictKind = WhereFoundClauseKind;
  9390. return true;
  9391. })) {
  9392. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9393. << getOpenMPClauseName(OMPC_firstprivate)
  9394. << getOpenMPClauseName(ConflictKind)
  9395. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9396. reportOriginalDsa(*this, DSAStack, D, DVar);
  9397. continue;
  9398. }
  9399. }
  9400. }
  9401. // Variably modified types are not supported for tasks.
  9402. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9403. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  9404. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9405. << getOpenMPClauseName(OMPC_firstprivate) << Type
  9406. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9407. bool IsDecl =
  9408. !VD ||
  9409. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9410. Diag(D->getLocation(),
  9411. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9412. << D;
  9413. continue;
  9414. }
  9415. Type = Type.getUnqualifiedType();
  9416. VarDecl *VDPrivate =
  9417. buildVarDecl(*this, ELoc, Type, D->getName(),
  9418. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9419. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9420. // Generate helper private variable and initialize it with the value of the
  9421. // original variable. The address of the original variable is replaced by
  9422. // the address of the new private variable in the CodeGen. This new variable
  9423. // is not added to IdResolver, so the code in the OpenMP region uses
  9424. // original variable for proper diagnostics and variable capturing.
  9425. Expr *VDInitRefExpr = nullptr;
  9426. // For arrays generate initializer for single element and replace it by the
  9427. // original array element in CodeGen.
  9428. if (Type->isArrayType()) {
  9429. VarDecl *VDInit =
  9430. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  9431. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  9432. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  9433. ElemType = ElemType.getUnqualifiedType();
  9434. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  9435. ".firstprivate.temp");
  9436. InitializedEntity Entity =
  9437. InitializedEntity::InitializeVariable(VDInitTemp);
  9438. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  9439. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  9440. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  9441. if (Result.isInvalid())
  9442. VDPrivate->setInvalidDecl();
  9443. else
  9444. VDPrivate->setInit(Result.getAs<Expr>());
  9445. // Remove temp variable declaration.
  9446. Context.Deallocate(VDInitTemp);
  9447. } else {
  9448. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  9449. ".firstprivate.temp");
  9450. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  9451. RefExpr->getExprLoc());
  9452. AddInitializerToDecl(VDPrivate,
  9453. DefaultLvalueConversion(VDInitRefExpr).get(),
  9454. /*DirectInit=*/false);
  9455. }
  9456. if (VDPrivate->isInvalidDecl()) {
  9457. if (IsImplicitClause) {
  9458. Diag(RefExpr->getExprLoc(),
  9459. diag::note_omp_task_predetermined_firstprivate_here);
  9460. }
  9461. continue;
  9462. }
  9463. CurContext->addDecl(VDPrivate);
  9464. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9465. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  9466. RefExpr->getExprLoc());
  9467. DeclRefExpr *Ref = nullptr;
  9468. if (!VD && !CurContext->isDependentContext()) {
  9469. if (TopDVar.CKind == OMPC_lastprivate) {
  9470. Ref = TopDVar.PrivateCopy;
  9471. } else {
  9472. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9473. if (!isOpenMPCapturedDecl(D))
  9474. ExprCaptures.push_back(Ref->getDecl());
  9475. }
  9476. }
  9477. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  9478. Vars.push_back((VD || CurContext->isDependentContext())
  9479. ? RefExpr->IgnoreParens()
  9480. : Ref);
  9481. PrivateCopies.push_back(VDPrivateRefExpr);
  9482. Inits.push_back(VDInitRefExpr);
  9483. }
  9484. if (Vars.empty())
  9485. return nullptr;
  9486. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9487. Vars, PrivateCopies, Inits,
  9488. buildPreInits(Context, ExprCaptures));
  9489. }
  9490. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  9491. SourceLocation StartLoc,
  9492. SourceLocation LParenLoc,
  9493. SourceLocation EndLoc) {
  9494. SmallVector<Expr *, 8> Vars;
  9495. SmallVector<Expr *, 8> SrcExprs;
  9496. SmallVector<Expr *, 8> DstExprs;
  9497. SmallVector<Expr *, 8> AssignmentOps;
  9498. SmallVector<Decl *, 4> ExprCaptures;
  9499. SmallVector<Expr *, 4> ExprPostUpdates;
  9500. for (Expr *RefExpr : VarList) {
  9501. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9502. SourceLocation ELoc;
  9503. SourceRange ERange;
  9504. Expr *SimpleRefExpr = RefExpr;
  9505. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9506. if (Res.second) {
  9507. // It will be analyzed later.
  9508. Vars.push_back(RefExpr);
  9509. SrcExprs.push_back(nullptr);
  9510. DstExprs.push_back(nullptr);
  9511. AssignmentOps.push_back(nullptr);
  9512. }
  9513. ValueDecl *D = Res.first;
  9514. if (!D)
  9515. continue;
  9516. QualType Type = D->getType();
  9517. auto *VD = dyn_cast<VarDecl>(D);
  9518. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  9519. // A variable that appears in a lastprivate clause must not have an
  9520. // incomplete type or a reference type.
  9521. if (RequireCompleteType(ELoc, Type,
  9522. diag::err_omp_lastprivate_incomplete_type))
  9523. continue;
  9524. Type = Type.getNonReferenceType();
  9525. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9526. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9527. // in a Construct]
  9528. // Variables with the predetermined data-sharing attributes may not be
  9529. // listed in data-sharing attributes clauses, except for the cases
  9530. // listed below.
  9531. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9532. // A list item may appear in a firstprivate or lastprivate clause but not
  9533. // both.
  9534. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9535. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  9536. (isOpenMPDistributeDirective(CurrDir) ||
  9537. DVar.CKind != OMPC_firstprivate) &&
  9538. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  9539. Diag(ELoc, diag::err_omp_wrong_dsa)
  9540. << getOpenMPClauseName(DVar.CKind)
  9541. << getOpenMPClauseName(OMPC_lastprivate);
  9542. reportOriginalDsa(*this, DSAStack, D, DVar);
  9543. continue;
  9544. }
  9545. // OpenMP [2.14.3.5, Restrictions, p.2]
  9546. // A list item that is private within a parallel region, or that appears in
  9547. // the reduction clause of a parallel construct, must not appear in a
  9548. // lastprivate clause on a worksharing construct if any of the corresponding
  9549. // worksharing regions ever binds to any of the corresponding parallel
  9550. // regions.
  9551. DSAStackTy::DSAVarData TopDVar = DVar;
  9552. if (isOpenMPWorksharingDirective(CurrDir) &&
  9553. !isOpenMPParallelDirective(CurrDir) &&
  9554. !isOpenMPTeamsDirective(CurrDir)) {
  9555. DVar = DSAStack->getImplicitDSA(D, true);
  9556. if (DVar.CKind != OMPC_shared) {
  9557. Diag(ELoc, diag::err_omp_required_access)
  9558. << getOpenMPClauseName(OMPC_lastprivate)
  9559. << getOpenMPClauseName(OMPC_shared);
  9560. reportOriginalDsa(*this, DSAStack, D, DVar);
  9561. continue;
  9562. }
  9563. }
  9564. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  9565. // A variable of class type (or array thereof) that appears in a
  9566. // lastprivate clause requires an accessible, unambiguous default
  9567. // constructor for the class type, unless the list item is also specified
  9568. // in a firstprivate clause.
  9569. // A variable of class type (or array thereof) that appears in a
  9570. // lastprivate clause requires an accessible, unambiguous copy assignment
  9571. // operator for the class type.
  9572. Type = Context.getBaseElementType(Type).getNonReferenceType();
  9573. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  9574. Type.getUnqualifiedType(), ".lastprivate.src",
  9575. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9576. DeclRefExpr *PseudoSrcExpr =
  9577. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  9578. VarDecl *DstVD =
  9579. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  9580. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9581. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9582. // For arrays generate assignment operation for single element and replace
  9583. // it by the original array element in CodeGen.
  9584. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  9585. PseudoDstExpr, PseudoSrcExpr);
  9586. if (AssignmentOp.isInvalid())
  9587. continue;
  9588. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  9589. /*DiscardedValue=*/true);
  9590. if (AssignmentOp.isInvalid())
  9591. continue;
  9592. DeclRefExpr *Ref = nullptr;
  9593. if (!VD && !CurContext->isDependentContext()) {
  9594. if (TopDVar.CKind == OMPC_firstprivate) {
  9595. Ref = TopDVar.PrivateCopy;
  9596. } else {
  9597. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9598. if (!isOpenMPCapturedDecl(D))
  9599. ExprCaptures.push_back(Ref->getDecl());
  9600. }
  9601. if (TopDVar.CKind == OMPC_firstprivate ||
  9602. (!isOpenMPCapturedDecl(D) &&
  9603. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  9604. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9605. if (!RefRes.isUsable())
  9606. continue;
  9607. ExprResult PostUpdateRes =
  9608. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9609. RefRes.get());
  9610. if (!PostUpdateRes.isUsable())
  9611. continue;
  9612. ExprPostUpdates.push_back(
  9613. IgnoredValueConversions(PostUpdateRes.get()).get());
  9614. }
  9615. }
  9616. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  9617. Vars.push_back((VD || CurContext->isDependentContext())
  9618. ? RefExpr->IgnoreParens()
  9619. : Ref);
  9620. SrcExprs.push_back(PseudoSrcExpr);
  9621. DstExprs.push_back(PseudoDstExpr);
  9622. AssignmentOps.push_back(AssignmentOp.get());
  9623. }
  9624. if (Vars.empty())
  9625. return nullptr;
  9626. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9627. Vars, SrcExprs, DstExprs, AssignmentOps,
  9628. buildPreInits(Context, ExprCaptures),
  9629. buildPostUpdate(*this, ExprPostUpdates));
  9630. }
  9631. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  9632. SourceLocation StartLoc,
  9633. SourceLocation LParenLoc,
  9634. SourceLocation EndLoc) {
  9635. SmallVector<Expr *, 8> Vars;
  9636. for (Expr *RefExpr : VarList) {
  9637. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9638. SourceLocation ELoc;
  9639. SourceRange ERange;
  9640. Expr *SimpleRefExpr = RefExpr;
  9641. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9642. if (Res.second) {
  9643. // It will be analyzed later.
  9644. Vars.push_back(RefExpr);
  9645. }
  9646. ValueDecl *D = Res.first;
  9647. if (!D)
  9648. continue;
  9649. auto *VD = dyn_cast<VarDecl>(D);
  9650. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9651. // in a Construct]
  9652. // Variables with the predetermined data-sharing attributes may not be
  9653. // listed in data-sharing attributes clauses, except for the cases
  9654. // listed below. For these exceptions only, listing a predetermined
  9655. // variable in a data-sharing attribute clause is allowed and overrides
  9656. // the variable's predetermined data-sharing attributes.
  9657. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9658. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  9659. DVar.RefExpr) {
  9660. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9661. << getOpenMPClauseName(OMPC_shared);
  9662. reportOriginalDsa(*this, DSAStack, D, DVar);
  9663. continue;
  9664. }
  9665. DeclRefExpr *Ref = nullptr;
  9666. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  9667. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9668. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  9669. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  9670. ? RefExpr->IgnoreParens()
  9671. : Ref);
  9672. }
  9673. if (Vars.empty())
  9674. return nullptr;
  9675. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  9676. }
  9677. namespace {
  9678. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  9679. DSAStackTy *Stack;
  9680. public:
  9681. bool VisitDeclRefExpr(DeclRefExpr *E) {
  9682. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9683. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  9684. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9685. return false;
  9686. if (DVar.CKind != OMPC_unknown)
  9687. return true;
  9688. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9689. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  9690. /*FromParent=*/true);
  9691. return DVarPrivate.CKind != OMPC_unknown;
  9692. }
  9693. return false;
  9694. }
  9695. bool VisitStmt(Stmt *S) {
  9696. for (Stmt *Child : S->children()) {
  9697. if (Child && Visit(Child))
  9698. return true;
  9699. }
  9700. return false;
  9701. }
  9702. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9703. };
  9704. } // namespace
  9705. namespace {
  9706. // Transform MemberExpression for specified FieldDecl of current class to
  9707. // DeclRefExpr to specified OMPCapturedExprDecl.
  9708. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9709. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9710. ValueDecl *Field = nullptr;
  9711. DeclRefExpr *CapturedExpr = nullptr;
  9712. public:
  9713. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9714. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9715. ExprResult TransformMemberExpr(MemberExpr *E) {
  9716. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9717. E->getMemberDecl() == Field) {
  9718. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9719. return CapturedExpr;
  9720. }
  9721. return BaseTransform::TransformMemberExpr(E);
  9722. }
  9723. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9724. };
  9725. } // namespace
  9726. template <typename T, typename U>
  9727. static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
  9728. const llvm::function_ref<T(ValueDecl *)> Gen) {
  9729. for (U &Set : Lookups) {
  9730. for (auto *D : Set) {
  9731. if (T Res = Gen(cast<ValueDecl>(D)))
  9732. return Res;
  9733. }
  9734. }
  9735. return T();
  9736. }
  9737. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  9738. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  9739. for (auto RD : D->redecls()) {
  9740. // Don't bother with extra checks if we already know this one isn't visible.
  9741. if (RD == D)
  9742. continue;
  9743. auto ND = cast<NamedDecl>(RD);
  9744. if (LookupResult::isVisible(SemaRef, ND))
  9745. return ND;
  9746. }
  9747. return nullptr;
  9748. }
  9749. static void
  9750. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
  9751. SourceLocation Loc, QualType Ty,
  9752. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  9753. // Find all of the associated namespaces and classes based on the
  9754. // arguments we have.
  9755. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9756. Sema::AssociatedClassSet AssociatedClasses;
  9757. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  9758. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  9759. AssociatedClasses);
  9760. // C++ [basic.lookup.argdep]p3:
  9761. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9762. // and let Y be the lookup set produced by argument dependent
  9763. // lookup (defined as follows). If X contains [...] then Y is
  9764. // empty. Otherwise Y is the set of declarations found in the
  9765. // namespaces associated with the argument types as described
  9766. // below. The set of declarations found by the lookup of the name
  9767. // is the union of X and Y.
  9768. //
  9769. // Here, we compute Y and add its members to the overloaded
  9770. // candidate set.
  9771. for (auto *NS : AssociatedNamespaces) {
  9772. // When considering an associated namespace, the lookup is the
  9773. // same as the lookup performed when the associated namespace is
  9774. // used as a qualifier (3.4.3.2) except that:
  9775. //
  9776. // -- Any using-directives in the associated namespace are
  9777. // ignored.
  9778. //
  9779. // -- Any namespace-scope friend functions declared in
  9780. // associated classes are visible within their respective
  9781. // namespaces even if they are not visible during an ordinary
  9782. // lookup (11.4).
  9783. DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
  9784. for (auto *D : R) {
  9785. auto *Underlying = D;
  9786. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  9787. Underlying = USD->getTargetDecl();
  9788. if (!isa<OMPDeclareReductionDecl>(Underlying))
  9789. continue;
  9790. if (!SemaRef.isVisible(D)) {
  9791. D = findAcceptableDecl(SemaRef, D);
  9792. if (!D)
  9793. continue;
  9794. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  9795. Underlying = USD->getTargetDecl();
  9796. }
  9797. Lookups.emplace_back();
  9798. Lookups.back().addDecl(Underlying);
  9799. }
  9800. }
  9801. }
  9802. static ExprResult
  9803. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9804. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9805. const DeclarationNameInfo &ReductionId, QualType Ty,
  9806. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9807. if (ReductionIdScopeSpec.isInvalid())
  9808. return ExprError();
  9809. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9810. if (S) {
  9811. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9812. Lookup.suppressDiagnostics();
  9813. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9814. NamedDecl *D = Lookup.getRepresentativeDecl();
  9815. do {
  9816. S = S->getParent();
  9817. } while (S && !S->isDeclScope(D));
  9818. if (S)
  9819. S = S->getParent();
  9820. Lookups.emplace_back();
  9821. Lookups.back().append(Lookup.begin(), Lookup.end());
  9822. Lookup.clear();
  9823. }
  9824. } else if (auto *ULE =
  9825. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9826. Lookups.push_back(UnresolvedSet<8>());
  9827. Decl *PrevD = nullptr;
  9828. for (NamedDecl *D : ULE->decls()) {
  9829. if (D == PrevD)
  9830. Lookups.push_back(UnresolvedSet<8>());
  9831. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9832. Lookups.back().addDecl(DRD);
  9833. PrevD = D;
  9834. }
  9835. }
  9836. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9837. Ty->isInstantiationDependentType() ||
  9838. Ty->containsUnexpandedParameterPack() ||
  9839. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
  9840. return !D->isInvalidDecl() &&
  9841. (D->getType()->isDependentType() ||
  9842. D->getType()->isInstantiationDependentType() ||
  9843. D->getType()->containsUnexpandedParameterPack());
  9844. })) {
  9845. UnresolvedSet<8> ResSet;
  9846. for (const UnresolvedSet<8> &Set : Lookups) {
  9847. if (Set.empty())
  9848. continue;
  9849. ResSet.append(Set.begin(), Set.end());
  9850. // The last item marks the end of all declarations at the specified scope.
  9851. ResSet.addDecl(Set[Set.size() - 1]);
  9852. }
  9853. return UnresolvedLookupExpr::Create(
  9854. SemaRef.Context, /*NamingClass=*/nullptr,
  9855. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9856. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9857. }
  9858. // Lookup inside the classes.
  9859. // C++ [over.match.oper]p3:
  9860. // For a unary operator @ with an operand of a type whose
  9861. // cv-unqualified version is T1, and for a binary operator @ with
  9862. // a left operand of a type whose cv-unqualified version is T1 and
  9863. // a right operand of a type whose cv-unqualified version is T2,
  9864. // three sets of candidate functions, designated member
  9865. // candidates, non-member candidates and built-in candidates, are
  9866. // constructed as follows:
  9867. // -- If T1 is a complete class type or a class currently being
  9868. // defined, the set of member candidates is the result of the
  9869. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  9870. // the set of member candidates is empty.
  9871. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9872. Lookup.suppressDiagnostics();
  9873. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  9874. // Complete the type if it can be completed.
  9875. // If the type is neither complete nor being defined, bail out now.
  9876. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  9877. TyRec->getDecl()->getDefinition()) {
  9878. Lookup.clear();
  9879. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  9880. if (Lookup.empty()) {
  9881. Lookups.emplace_back();
  9882. Lookups.back().append(Lookup.begin(), Lookup.end());
  9883. }
  9884. }
  9885. }
  9886. // Perform ADL.
  9887. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  9888. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9889. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9890. if (!D->isInvalidDecl() &&
  9891. SemaRef.Context.hasSameType(D->getType(), Ty))
  9892. return D;
  9893. return nullptr;
  9894. }))
  9895. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9896. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9897. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9898. if (!D->isInvalidDecl() &&
  9899. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9900. !Ty.isMoreQualifiedThan(D->getType()))
  9901. return D;
  9902. return nullptr;
  9903. })) {
  9904. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9905. /*DetectVirtual=*/false);
  9906. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9907. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9908. VD->getType().getUnqualifiedType()))) {
  9909. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9910. /*DiagID=*/0) !=
  9911. Sema::AR_inaccessible) {
  9912. SemaRef.BuildBasePathArray(Paths, BasePath);
  9913. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9914. }
  9915. }
  9916. }
  9917. }
  9918. if (ReductionIdScopeSpec.isSet()) {
  9919. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9920. return ExprError();
  9921. }
  9922. return ExprEmpty();
  9923. }
  9924. namespace {
  9925. /// Data for the reduction-based clauses.
  9926. struct ReductionData {
  9927. /// List of original reduction items.
  9928. SmallVector<Expr *, 8> Vars;
  9929. /// List of private copies of the reduction items.
  9930. SmallVector<Expr *, 8> Privates;
  9931. /// LHS expressions for the reduction_op expressions.
  9932. SmallVector<Expr *, 8> LHSs;
  9933. /// RHS expressions for the reduction_op expressions.
  9934. SmallVector<Expr *, 8> RHSs;
  9935. /// Reduction operation expression.
  9936. SmallVector<Expr *, 8> ReductionOps;
  9937. /// Taskgroup descriptors for the corresponding reduction items in
  9938. /// in_reduction clauses.
  9939. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9940. /// List of captures for clause.
  9941. SmallVector<Decl *, 4> ExprCaptures;
  9942. /// List of postupdate expressions.
  9943. SmallVector<Expr *, 4> ExprPostUpdates;
  9944. ReductionData() = delete;
  9945. /// Reserves required memory for the reduction data.
  9946. ReductionData(unsigned Size) {
  9947. Vars.reserve(Size);
  9948. Privates.reserve(Size);
  9949. LHSs.reserve(Size);
  9950. RHSs.reserve(Size);
  9951. ReductionOps.reserve(Size);
  9952. TaskgroupDescriptors.reserve(Size);
  9953. ExprCaptures.reserve(Size);
  9954. ExprPostUpdates.reserve(Size);
  9955. }
  9956. /// Stores reduction item and reduction operation only (required for dependent
  9957. /// reduction item).
  9958. void push(Expr *Item, Expr *ReductionOp) {
  9959. Vars.emplace_back(Item);
  9960. Privates.emplace_back(nullptr);
  9961. LHSs.emplace_back(nullptr);
  9962. RHSs.emplace_back(nullptr);
  9963. ReductionOps.emplace_back(ReductionOp);
  9964. TaskgroupDescriptors.emplace_back(nullptr);
  9965. }
  9966. /// Stores reduction data.
  9967. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9968. Expr *TaskgroupDescriptor) {
  9969. Vars.emplace_back(Item);
  9970. Privates.emplace_back(Private);
  9971. LHSs.emplace_back(LHS);
  9972. RHSs.emplace_back(RHS);
  9973. ReductionOps.emplace_back(ReductionOp);
  9974. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9975. }
  9976. };
  9977. } // namespace
  9978. static bool checkOMPArraySectionConstantForReduction(
  9979. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9980. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9981. const Expr *Length = OASE->getLength();
  9982. if (Length == nullptr) {
  9983. // For array sections of the form [1:] or [:], we would need to analyze
  9984. // the lower bound...
  9985. if (OASE->getColonLoc().isValid())
  9986. return false;
  9987. // This is an array subscript which has implicit length 1!
  9988. SingleElement = true;
  9989. ArraySizes.push_back(llvm::APSInt::get(1));
  9990. } else {
  9991. llvm::APSInt ConstantLengthValue;
  9992. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9993. return false;
  9994. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9995. ArraySizes.push_back(ConstantLengthValue);
  9996. }
  9997. // Get the base of this array section and walk up from there.
  9998. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9999. // We require length = 1 for all array sections except the right-most to
  10000. // guarantee that the memory region is contiguous and has no holes in it.
  10001. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  10002. Length = TempOASE->getLength();
  10003. if (Length == nullptr) {
  10004. // For array sections of the form [1:] or [:], we would need to analyze
  10005. // the lower bound...
  10006. if (OASE->getColonLoc().isValid())
  10007. return false;
  10008. // This is an array subscript which has implicit length 1!
  10009. ArraySizes.push_back(llvm::APSInt::get(1));
  10010. } else {
  10011. llvm::APSInt ConstantLengthValue;
  10012. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  10013. ConstantLengthValue.getSExtValue() != 1)
  10014. return false;
  10015. ArraySizes.push_back(ConstantLengthValue);
  10016. }
  10017. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  10018. }
  10019. // If we have a single element, we don't need to add the implicit lengths.
  10020. if (!SingleElement) {
  10021. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  10022. // Has implicit length 1!
  10023. ArraySizes.push_back(llvm::APSInt::get(1));
  10024. Base = TempASE->getBase()->IgnoreParenImpCasts();
  10025. }
  10026. }
  10027. // This array section can be privatized as a single value or as a constant
  10028. // sized array.
  10029. return true;
  10030. }
  10031. static bool actOnOMPReductionKindClause(
  10032. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  10033. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10034. SourceLocation ColonLoc, SourceLocation EndLoc,
  10035. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10036. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  10037. DeclarationName DN = ReductionId.getName();
  10038. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  10039. BinaryOperatorKind BOK = BO_Comma;
  10040. ASTContext &Context = S.Context;
  10041. // OpenMP [2.14.3.6, reduction clause]
  10042. // C
  10043. // reduction-identifier is either an identifier or one of the following
  10044. // operators: +, -, *, &, |, ^, && and ||
  10045. // C++
  10046. // reduction-identifier is either an id-expression or one of the following
  10047. // operators: +, -, *, &, |, ^, && and ||
  10048. switch (OOK) {
  10049. case OO_Plus:
  10050. case OO_Minus:
  10051. BOK = BO_Add;
  10052. break;
  10053. case OO_Star:
  10054. BOK = BO_Mul;
  10055. break;
  10056. case OO_Amp:
  10057. BOK = BO_And;
  10058. break;
  10059. case OO_Pipe:
  10060. BOK = BO_Or;
  10061. break;
  10062. case OO_Caret:
  10063. BOK = BO_Xor;
  10064. break;
  10065. case OO_AmpAmp:
  10066. BOK = BO_LAnd;
  10067. break;
  10068. case OO_PipePipe:
  10069. BOK = BO_LOr;
  10070. break;
  10071. case OO_New:
  10072. case OO_Delete:
  10073. case OO_Array_New:
  10074. case OO_Array_Delete:
  10075. case OO_Slash:
  10076. case OO_Percent:
  10077. case OO_Tilde:
  10078. case OO_Exclaim:
  10079. case OO_Equal:
  10080. case OO_Less:
  10081. case OO_Greater:
  10082. case OO_LessEqual:
  10083. case OO_GreaterEqual:
  10084. case OO_PlusEqual:
  10085. case OO_MinusEqual:
  10086. case OO_StarEqual:
  10087. case OO_SlashEqual:
  10088. case OO_PercentEqual:
  10089. case OO_CaretEqual:
  10090. case OO_AmpEqual:
  10091. case OO_PipeEqual:
  10092. case OO_LessLess:
  10093. case OO_GreaterGreater:
  10094. case OO_LessLessEqual:
  10095. case OO_GreaterGreaterEqual:
  10096. case OO_EqualEqual:
  10097. case OO_ExclaimEqual:
  10098. case OO_Spaceship:
  10099. case OO_PlusPlus:
  10100. case OO_MinusMinus:
  10101. case OO_Comma:
  10102. case OO_ArrowStar:
  10103. case OO_Arrow:
  10104. case OO_Call:
  10105. case OO_Subscript:
  10106. case OO_Conditional:
  10107. case OO_Coawait:
  10108. case NUM_OVERLOADED_OPERATORS:
  10109. llvm_unreachable("Unexpected reduction identifier");
  10110. case OO_None:
  10111. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  10112. if (II->isStr("max"))
  10113. BOK = BO_GT;
  10114. else if (II->isStr("min"))
  10115. BOK = BO_LT;
  10116. }
  10117. break;
  10118. }
  10119. SourceRange ReductionIdRange;
  10120. if (ReductionIdScopeSpec.isValid())
  10121. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  10122. else
  10123. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  10124. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  10125. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  10126. bool FirstIter = true;
  10127. for (Expr *RefExpr : VarList) {
  10128. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  10129. // OpenMP [2.1, C/C++]
  10130. // A list item is a variable or array section, subject to the restrictions
  10131. // specified in Section 2.4 on page 42 and in each of the sections
  10132. // describing clauses and directives for which a list appears.
  10133. // OpenMP [2.14.3.3, Restrictions, p.1]
  10134. // A variable that is part of another variable (as an array or
  10135. // structure element) cannot appear in a private clause.
  10136. if (!FirstIter && IR != ER)
  10137. ++IR;
  10138. FirstIter = false;
  10139. SourceLocation ELoc;
  10140. SourceRange ERange;
  10141. Expr *SimpleRefExpr = RefExpr;
  10142. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  10143. /*AllowArraySection=*/true);
  10144. if (Res.second) {
  10145. // Try to find 'declare reduction' corresponding construct before using
  10146. // builtin/overloaded operators.
  10147. QualType Type = Context.DependentTy;
  10148. CXXCastPath BasePath;
  10149. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10150. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10151. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10152. Expr *ReductionOp = nullptr;
  10153. if (S.CurContext->isDependentContext() &&
  10154. (DeclareReductionRef.isUnset() ||
  10155. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  10156. ReductionOp = DeclareReductionRef.get();
  10157. // It will be analyzed later.
  10158. RD.push(RefExpr, ReductionOp);
  10159. }
  10160. ValueDecl *D = Res.first;
  10161. if (!D)
  10162. continue;
  10163. Expr *TaskgroupDescriptor = nullptr;
  10164. QualType Type;
  10165. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  10166. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  10167. if (ASE) {
  10168. Type = ASE->getType().getNonReferenceType();
  10169. } else if (OASE) {
  10170. QualType BaseType =
  10171. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  10172. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  10173. Type = ATy->getElementType();
  10174. else
  10175. Type = BaseType->getPointeeType();
  10176. Type = Type.getNonReferenceType();
  10177. } else {
  10178. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  10179. }
  10180. auto *VD = dyn_cast<VarDecl>(D);
  10181. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10182. // A variable that appears in a private clause must not have an incomplete
  10183. // type or a reference type.
  10184. if (S.RequireCompleteType(ELoc, D->getType(),
  10185. diag::err_omp_reduction_incomplete_type))
  10186. continue;
  10187. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10188. // A list item that appears in a reduction clause must not be
  10189. // const-qualified.
  10190. if (Type.getNonReferenceType().isConstant(Context)) {
  10191. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  10192. if (!ASE && !OASE) {
  10193. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10194. VarDecl::DeclarationOnly;
  10195. S.Diag(D->getLocation(),
  10196. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10197. << D;
  10198. }
  10199. continue;
  10200. }
  10201. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  10202. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  10203. // If a list-item is a reference type then it must bind to the same object
  10204. // for all threads of the team.
  10205. if (!ASE && !OASE) {
  10206. if (VD) {
  10207. VarDecl *VDDef = VD->getDefinition();
  10208. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  10209. DSARefChecker Check(Stack);
  10210. if (Check.Visit(VDDef->getInit())) {
  10211. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  10212. << getOpenMPClauseName(ClauseKind) << ERange;
  10213. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  10214. continue;
  10215. }
  10216. }
  10217. }
  10218. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10219. // in a Construct]
  10220. // Variables with the predetermined data-sharing attributes may not be
  10221. // listed in data-sharing attributes clauses, except for the cases
  10222. // listed below. For these exceptions only, listing a predetermined
  10223. // variable in a data-sharing attribute clause is allowed and overrides
  10224. // the variable's predetermined data-sharing attributes.
  10225. // OpenMP [2.14.3.6, Restrictions, p.3]
  10226. // Any number of reduction clauses can be specified on the directive,
  10227. // but a list item can appear only once in the reduction clauses for that
  10228. // directive.
  10229. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  10230. if (DVar.CKind == OMPC_reduction) {
  10231. S.Diag(ELoc, diag::err_omp_once_referenced)
  10232. << getOpenMPClauseName(ClauseKind);
  10233. if (DVar.RefExpr)
  10234. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  10235. continue;
  10236. }
  10237. if (DVar.CKind != OMPC_unknown) {
  10238. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  10239. << getOpenMPClauseName(DVar.CKind)
  10240. << getOpenMPClauseName(OMPC_reduction);
  10241. reportOriginalDsa(S, Stack, D, DVar);
  10242. continue;
  10243. }
  10244. // OpenMP [2.14.3.6, Restrictions, p.1]
  10245. // A list item that appears in a reduction clause of a worksharing
  10246. // construct must be shared in the parallel regions to which any of the
  10247. // worksharing regions arising from the worksharing construct bind.
  10248. if (isOpenMPWorksharingDirective(CurrDir) &&
  10249. !isOpenMPParallelDirective(CurrDir) &&
  10250. !isOpenMPTeamsDirective(CurrDir)) {
  10251. DVar = Stack->getImplicitDSA(D, true);
  10252. if (DVar.CKind != OMPC_shared) {
  10253. S.Diag(ELoc, diag::err_omp_required_access)
  10254. << getOpenMPClauseName(OMPC_reduction)
  10255. << getOpenMPClauseName(OMPC_shared);
  10256. reportOriginalDsa(S, Stack, D, DVar);
  10257. continue;
  10258. }
  10259. }
  10260. }
  10261. // Try to find 'declare reduction' corresponding construct before using
  10262. // builtin/overloaded operators.
  10263. CXXCastPath BasePath;
  10264. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10265. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10266. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10267. if (DeclareReductionRef.isInvalid())
  10268. continue;
  10269. if (S.CurContext->isDependentContext() &&
  10270. (DeclareReductionRef.isUnset() ||
  10271. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  10272. RD.push(RefExpr, DeclareReductionRef.get());
  10273. continue;
  10274. }
  10275. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  10276. // Not allowed reduction identifier is found.
  10277. S.Diag(ReductionId.getBeginLoc(),
  10278. diag::err_omp_unknown_reduction_identifier)
  10279. << Type << ReductionIdRange;
  10280. continue;
  10281. }
  10282. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10283. // The type of a list item that appears in a reduction clause must be valid
  10284. // for the reduction-identifier. For a max or min reduction in C, the type
  10285. // of the list item must be an allowed arithmetic data type: char, int,
  10286. // float, double, or _Bool, possibly modified with long, short, signed, or
  10287. // unsigned. For a max or min reduction in C++, the type of the list item
  10288. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  10289. // double, or bool, possibly modified with long, short, signed, or unsigned.
  10290. if (DeclareReductionRef.isUnset()) {
  10291. if ((BOK == BO_GT || BOK == BO_LT) &&
  10292. !(Type->isScalarType() ||
  10293. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  10294. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  10295. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  10296. if (!ASE && !OASE) {
  10297. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10298. VarDecl::DeclarationOnly;
  10299. S.Diag(D->getLocation(),
  10300. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10301. << D;
  10302. }
  10303. continue;
  10304. }
  10305. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  10306. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  10307. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  10308. << getOpenMPClauseName(ClauseKind);
  10309. if (!ASE && !OASE) {
  10310. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10311. VarDecl::DeclarationOnly;
  10312. S.Diag(D->getLocation(),
  10313. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10314. << D;
  10315. }
  10316. continue;
  10317. }
  10318. }
  10319. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  10320. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  10321. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10322. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  10323. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10324. QualType PrivateTy = Type;
  10325. // Try if we can determine constant lengths for all array sections and avoid
  10326. // the VLA.
  10327. bool ConstantLengthOASE = false;
  10328. if (OASE) {
  10329. bool SingleElement;
  10330. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  10331. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  10332. Context, OASE, SingleElement, ArraySizes);
  10333. // If we don't have a single element, we must emit a constant array type.
  10334. if (ConstantLengthOASE && !SingleElement) {
  10335. for (llvm::APSInt &Size : ArraySizes)
  10336. PrivateTy = Context.getConstantArrayType(
  10337. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  10338. }
  10339. }
  10340. if ((OASE && !ConstantLengthOASE) ||
  10341. (!OASE && !ASE &&
  10342. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  10343. if (!Context.getTargetInfo().isVLASupported() &&
  10344. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  10345. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  10346. S.Diag(ELoc, diag::note_vla_unsupported);
  10347. continue;
  10348. }
  10349. // For arrays/array sections only:
  10350. // Create pseudo array type for private copy. The size for this array will
  10351. // be generated during codegen.
  10352. // For array subscripts or single variables Private Ty is the same as Type
  10353. // (type of the variable or single array element).
  10354. PrivateTy = Context.getVariableArrayType(
  10355. Type,
  10356. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  10357. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  10358. } else if (!ASE && !OASE &&
  10359. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  10360. PrivateTy = D->getType().getNonReferenceType();
  10361. }
  10362. // Private copy.
  10363. VarDecl *PrivateVD =
  10364. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  10365. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10366. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10367. // Add initializer for private variable.
  10368. Expr *Init = nullptr;
  10369. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  10370. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  10371. if (DeclareReductionRef.isUsable()) {
  10372. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  10373. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  10374. if (DRD->getInitializer()) {
  10375. Init = DRDRef;
  10376. RHSVD->setInit(DRDRef);
  10377. RHSVD->setInitStyle(VarDecl::CallInit);
  10378. }
  10379. } else {
  10380. switch (BOK) {
  10381. case BO_Add:
  10382. case BO_Xor:
  10383. case BO_Or:
  10384. case BO_LOr:
  10385. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  10386. if (Type->isScalarType() || Type->isAnyComplexType())
  10387. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  10388. break;
  10389. case BO_Mul:
  10390. case BO_LAnd:
  10391. if (Type->isScalarType() || Type->isAnyComplexType()) {
  10392. // '*' and '&&' reduction ops - initializer is '1'.
  10393. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  10394. }
  10395. break;
  10396. case BO_And: {
  10397. // '&' reduction op - initializer is '~0'.
  10398. QualType OrigType = Type;
  10399. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  10400. Type = ComplexTy->getElementType();
  10401. if (Type->isRealFloatingType()) {
  10402. llvm::APFloat InitValue =
  10403. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  10404. /*isIEEE=*/true);
  10405. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10406. Type, ELoc);
  10407. } else if (Type->isScalarType()) {
  10408. uint64_t Size = Context.getTypeSize(Type);
  10409. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  10410. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  10411. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10412. }
  10413. if (Init && OrigType->isAnyComplexType()) {
  10414. // Init = 0xFFFF + 0xFFFFi;
  10415. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  10416. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  10417. }
  10418. Type = OrigType;
  10419. break;
  10420. }
  10421. case BO_LT:
  10422. case BO_GT: {
  10423. // 'min' reduction op - initializer is 'Largest representable number in
  10424. // the reduction list item type'.
  10425. // 'max' reduction op - initializer is 'Least representable number in
  10426. // the reduction list item type'.
  10427. if (Type->isIntegerType() || Type->isPointerType()) {
  10428. bool IsSigned = Type->hasSignedIntegerRepresentation();
  10429. uint64_t Size = Context.getTypeSize(Type);
  10430. QualType IntTy =
  10431. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  10432. llvm::APInt InitValue =
  10433. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  10434. : llvm::APInt::getMinValue(Size)
  10435. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  10436. : llvm::APInt::getMaxValue(Size);
  10437. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10438. if (Type->isPointerType()) {
  10439. // Cast to pointer type.
  10440. ExprResult CastExpr = S.BuildCStyleCastExpr(
  10441. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  10442. if (CastExpr.isInvalid())
  10443. continue;
  10444. Init = CastExpr.get();
  10445. }
  10446. } else if (Type->isRealFloatingType()) {
  10447. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  10448. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  10449. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10450. Type, ELoc);
  10451. }
  10452. break;
  10453. }
  10454. case BO_PtrMemD:
  10455. case BO_PtrMemI:
  10456. case BO_MulAssign:
  10457. case BO_Div:
  10458. case BO_Rem:
  10459. case BO_Sub:
  10460. case BO_Shl:
  10461. case BO_Shr:
  10462. case BO_LE:
  10463. case BO_GE:
  10464. case BO_EQ:
  10465. case BO_NE:
  10466. case BO_Cmp:
  10467. case BO_AndAssign:
  10468. case BO_XorAssign:
  10469. case BO_OrAssign:
  10470. case BO_Assign:
  10471. case BO_AddAssign:
  10472. case BO_SubAssign:
  10473. case BO_DivAssign:
  10474. case BO_RemAssign:
  10475. case BO_ShlAssign:
  10476. case BO_ShrAssign:
  10477. case BO_Comma:
  10478. llvm_unreachable("Unexpected reduction operation");
  10479. }
  10480. }
  10481. if (Init && DeclareReductionRef.isUnset())
  10482. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  10483. else if (!Init)
  10484. S.ActOnUninitializedDecl(RHSVD);
  10485. if (RHSVD->isInvalidDecl())
  10486. continue;
  10487. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  10488. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  10489. << Type << ReductionIdRange;
  10490. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10491. VarDecl::DeclarationOnly;
  10492. S.Diag(D->getLocation(),
  10493. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10494. << D;
  10495. continue;
  10496. }
  10497. // Store initializer for single element in private copy. Will be used during
  10498. // codegen.
  10499. PrivateVD->setInit(RHSVD->getInit());
  10500. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  10501. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  10502. ExprResult ReductionOp;
  10503. if (DeclareReductionRef.isUsable()) {
  10504. QualType RedTy = DeclareReductionRef.get()->getType();
  10505. QualType PtrRedTy = Context.getPointerType(RedTy);
  10506. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  10507. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  10508. if (!BasePath.empty()) {
  10509. LHS = S.DefaultLvalueConversion(LHS.get());
  10510. RHS = S.DefaultLvalueConversion(RHS.get());
  10511. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10512. CK_UncheckedDerivedToBase, LHS.get(),
  10513. &BasePath, LHS.get()->getValueKind());
  10514. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10515. CK_UncheckedDerivedToBase, RHS.get(),
  10516. &BasePath, RHS.get()->getValueKind());
  10517. }
  10518. FunctionProtoType::ExtProtoInfo EPI;
  10519. QualType Params[] = {PtrRedTy, PtrRedTy};
  10520. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  10521. auto *OVE = new (Context) OpaqueValueExpr(
  10522. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  10523. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  10524. Expr *Args[] = {LHS.get(), RHS.get()};
  10525. ReductionOp = new (Context)
  10526. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  10527. } else {
  10528. ReductionOp = S.BuildBinOp(
  10529. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  10530. if (ReductionOp.isUsable()) {
  10531. if (BOK != BO_LT && BOK != BO_GT) {
  10532. ReductionOp =
  10533. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10534. BO_Assign, LHSDRE, ReductionOp.get());
  10535. } else {
  10536. auto *ConditionalOp = new (Context)
  10537. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  10538. Type, VK_LValue, OK_Ordinary);
  10539. ReductionOp =
  10540. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10541. BO_Assign, LHSDRE, ConditionalOp);
  10542. }
  10543. if (ReductionOp.isUsable())
  10544. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  10545. }
  10546. if (!ReductionOp.isUsable())
  10547. continue;
  10548. }
  10549. // OpenMP [2.15.4.6, Restrictions, p.2]
  10550. // A list item that appears in an in_reduction clause of a task construct
  10551. // must appear in a task_reduction clause of a construct associated with a
  10552. // taskgroup region that includes the participating task in its taskgroup
  10553. // set. The construct associated with the innermost region that meets this
  10554. // condition must specify the same reduction-identifier as the in_reduction
  10555. // clause.
  10556. if (ClauseKind == OMPC_in_reduction) {
  10557. SourceRange ParentSR;
  10558. BinaryOperatorKind ParentBOK;
  10559. const Expr *ParentReductionOp;
  10560. Expr *ParentBOKTD, *ParentReductionOpTD;
  10561. DSAStackTy::DSAVarData ParentBOKDSA =
  10562. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  10563. ParentBOKTD);
  10564. DSAStackTy::DSAVarData ParentReductionOpDSA =
  10565. Stack->getTopMostTaskgroupReductionData(
  10566. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  10567. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  10568. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  10569. if (!IsParentBOK && !IsParentReductionOp) {
  10570. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  10571. continue;
  10572. }
  10573. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  10574. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  10575. IsParentReductionOp) {
  10576. bool EmitError = true;
  10577. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  10578. llvm::FoldingSetNodeID RedId, ParentRedId;
  10579. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  10580. DeclareReductionRef.get()->Profile(RedId, Context,
  10581. /*Canonical=*/true);
  10582. EmitError = RedId != ParentRedId;
  10583. }
  10584. if (EmitError) {
  10585. S.Diag(ReductionId.getBeginLoc(),
  10586. diag::err_omp_reduction_identifier_mismatch)
  10587. << ReductionIdRange << RefExpr->getSourceRange();
  10588. S.Diag(ParentSR.getBegin(),
  10589. diag::note_omp_previous_reduction_identifier)
  10590. << ParentSR
  10591. << (IsParentBOK ? ParentBOKDSA.RefExpr
  10592. : ParentReductionOpDSA.RefExpr)
  10593. ->getSourceRange();
  10594. continue;
  10595. }
  10596. }
  10597. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  10598. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  10599. }
  10600. DeclRefExpr *Ref = nullptr;
  10601. Expr *VarsExpr = RefExpr->IgnoreParens();
  10602. if (!VD && !S.CurContext->isDependentContext()) {
  10603. if (ASE || OASE) {
  10604. TransformExprToCaptures RebuildToCapture(S, D);
  10605. VarsExpr =
  10606. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  10607. Ref = RebuildToCapture.getCapturedExpr();
  10608. } else {
  10609. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  10610. }
  10611. if (!S.isOpenMPCapturedDecl(D)) {
  10612. RD.ExprCaptures.emplace_back(Ref->getDecl());
  10613. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10614. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  10615. if (!RefRes.isUsable())
  10616. continue;
  10617. ExprResult PostUpdateRes =
  10618. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10619. RefRes.get());
  10620. if (!PostUpdateRes.isUsable())
  10621. continue;
  10622. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  10623. Stack->getCurrentDirective() == OMPD_taskgroup) {
  10624. S.Diag(RefExpr->getExprLoc(),
  10625. diag::err_omp_reduction_non_addressable_expression)
  10626. << RefExpr->getSourceRange();
  10627. continue;
  10628. }
  10629. RD.ExprPostUpdates.emplace_back(
  10630. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  10631. }
  10632. }
  10633. }
  10634. // All reduction items are still marked as reduction (to do not increase
  10635. // code base size).
  10636. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  10637. if (CurrDir == OMPD_taskgroup) {
  10638. if (DeclareReductionRef.isUsable())
  10639. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  10640. DeclareReductionRef.get());
  10641. else
  10642. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  10643. }
  10644. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  10645. TaskgroupDescriptor);
  10646. }
  10647. return RD.Vars.empty();
  10648. }
  10649. OMPClause *Sema::ActOnOpenMPReductionClause(
  10650. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10651. SourceLocation ColonLoc, SourceLocation EndLoc,
  10652. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10653. ArrayRef<Expr *> UnresolvedReductions) {
  10654. ReductionData RD(VarList.size());
  10655. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  10656. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10657. ReductionIdScopeSpec, ReductionId,
  10658. UnresolvedReductions, RD))
  10659. return nullptr;
  10660. return OMPReductionClause::Create(
  10661. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10662. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10663. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10664. buildPreInits(Context, RD.ExprCaptures),
  10665. buildPostUpdate(*this, RD.ExprPostUpdates));
  10666. }
  10667. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  10668. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10669. SourceLocation ColonLoc, SourceLocation EndLoc,
  10670. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10671. ArrayRef<Expr *> UnresolvedReductions) {
  10672. ReductionData RD(VarList.size());
  10673. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  10674. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10675. ReductionIdScopeSpec, ReductionId,
  10676. UnresolvedReductions, RD))
  10677. return nullptr;
  10678. return OMPTaskReductionClause::Create(
  10679. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10680. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10681. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10682. buildPreInits(Context, RD.ExprCaptures),
  10683. buildPostUpdate(*this, RD.ExprPostUpdates));
  10684. }
  10685. OMPClause *Sema::ActOnOpenMPInReductionClause(
  10686. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10687. SourceLocation ColonLoc, SourceLocation EndLoc,
  10688. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10689. ArrayRef<Expr *> UnresolvedReductions) {
  10690. ReductionData RD(VarList.size());
  10691. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  10692. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10693. ReductionIdScopeSpec, ReductionId,
  10694. UnresolvedReductions, RD))
  10695. return nullptr;
  10696. return OMPInReductionClause::Create(
  10697. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10698. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10699. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  10700. buildPreInits(Context, RD.ExprCaptures),
  10701. buildPostUpdate(*this, RD.ExprPostUpdates));
  10702. }
  10703. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  10704. SourceLocation LinLoc) {
  10705. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  10706. LinKind == OMPC_LINEAR_unknown) {
  10707. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  10708. return true;
  10709. }
  10710. return false;
  10711. }
  10712. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  10713. OpenMPLinearClauseKind LinKind,
  10714. QualType Type) {
  10715. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  10716. // A variable must not have an incomplete type or a reference type.
  10717. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  10718. return true;
  10719. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  10720. !Type->isReferenceType()) {
  10721. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  10722. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  10723. return true;
  10724. }
  10725. Type = Type.getNonReferenceType();
  10726. // A list item must not be const-qualified.
  10727. if (Type.isConstant(Context)) {
  10728. Diag(ELoc, diag::err_omp_const_variable)
  10729. << getOpenMPClauseName(OMPC_linear);
  10730. if (D) {
  10731. bool IsDecl =
  10732. !VD ||
  10733. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10734. Diag(D->getLocation(),
  10735. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10736. << D;
  10737. }
  10738. return true;
  10739. }
  10740. // A list item must be of integral or pointer type.
  10741. Type = Type.getUnqualifiedType().getCanonicalType();
  10742. const auto *Ty = Type.getTypePtrOrNull();
  10743. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  10744. !Ty->isPointerType())) {
  10745. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  10746. if (D) {
  10747. bool IsDecl =
  10748. !VD ||
  10749. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10750. Diag(D->getLocation(),
  10751. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10752. << D;
  10753. }
  10754. return true;
  10755. }
  10756. return false;
  10757. }
  10758. OMPClause *Sema::ActOnOpenMPLinearClause(
  10759. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  10760. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  10761. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10762. SmallVector<Expr *, 8> Vars;
  10763. SmallVector<Expr *, 8> Privates;
  10764. SmallVector<Expr *, 8> Inits;
  10765. SmallVector<Decl *, 4> ExprCaptures;
  10766. SmallVector<Expr *, 4> ExprPostUpdates;
  10767. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  10768. LinKind = OMPC_LINEAR_val;
  10769. for (Expr *RefExpr : VarList) {
  10770. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10771. SourceLocation ELoc;
  10772. SourceRange ERange;
  10773. Expr *SimpleRefExpr = RefExpr;
  10774. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10775. if (Res.second) {
  10776. // It will be analyzed later.
  10777. Vars.push_back(RefExpr);
  10778. Privates.push_back(nullptr);
  10779. Inits.push_back(nullptr);
  10780. }
  10781. ValueDecl *D = Res.first;
  10782. if (!D)
  10783. continue;
  10784. QualType Type = D->getType();
  10785. auto *VD = dyn_cast<VarDecl>(D);
  10786. // OpenMP [2.14.3.7, linear clause]
  10787. // A list-item cannot appear in more than one linear clause.
  10788. // A list-item that appears in a linear clause cannot appear in any
  10789. // other data-sharing attribute clause.
  10790. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10791. if (DVar.RefExpr) {
  10792. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10793. << getOpenMPClauseName(OMPC_linear);
  10794. reportOriginalDsa(*this, DSAStack, D, DVar);
  10795. continue;
  10796. }
  10797. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  10798. continue;
  10799. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10800. // Build private copy of original var.
  10801. VarDecl *Private =
  10802. buildVarDecl(*this, ELoc, Type, D->getName(),
  10803. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10804. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10805. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  10806. // Build var to save initial value.
  10807. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  10808. Expr *InitExpr;
  10809. DeclRefExpr *Ref = nullptr;
  10810. if (!VD && !CurContext->isDependentContext()) {
  10811. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10812. if (!isOpenMPCapturedDecl(D)) {
  10813. ExprCaptures.push_back(Ref->getDecl());
  10814. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10815. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10816. if (!RefRes.isUsable())
  10817. continue;
  10818. ExprResult PostUpdateRes =
  10819. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10820. SimpleRefExpr, RefRes.get());
  10821. if (!PostUpdateRes.isUsable())
  10822. continue;
  10823. ExprPostUpdates.push_back(
  10824. IgnoredValueConversions(PostUpdateRes.get()).get());
  10825. }
  10826. }
  10827. }
  10828. if (LinKind == OMPC_LINEAR_uval)
  10829. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  10830. else
  10831. InitExpr = VD ? SimpleRefExpr : Ref;
  10832. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  10833. /*DirectInit=*/false);
  10834. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10835. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10836. Vars.push_back((VD || CurContext->isDependentContext())
  10837. ? RefExpr->IgnoreParens()
  10838. : Ref);
  10839. Privates.push_back(PrivateRef);
  10840. Inits.push_back(InitRef);
  10841. }
  10842. if (Vars.empty())
  10843. return nullptr;
  10844. Expr *StepExpr = Step;
  10845. Expr *CalcStepExpr = nullptr;
  10846. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10847. !Step->isInstantiationDependent() &&
  10848. !Step->containsUnexpandedParameterPack()) {
  10849. SourceLocation StepLoc = Step->getBeginLoc();
  10850. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10851. if (Val.isInvalid())
  10852. return nullptr;
  10853. StepExpr = Val.get();
  10854. // Build var to save the step value.
  10855. VarDecl *SaveVar =
  10856. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10857. ExprResult SaveRef =
  10858. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10859. ExprResult CalcStep =
  10860. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10861. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10862. // Warn about zero linear step (it would be probably better specified as
  10863. // making corresponding variables 'const').
  10864. llvm::APSInt Result;
  10865. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10866. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10867. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10868. << (Vars.size() > 1);
  10869. if (!IsConstant && CalcStep.isUsable()) {
  10870. // Calculate the step beforehand instead of doing this on each iteration.
  10871. // (This is not used if the number of iterations may be kfold-ed).
  10872. CalcStepExpr = CalcStep.get();
  10873. }
  10874. }
  10875. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10876. ColonLoc, EndLoc, Vars, Privates, Inits,
  10877. StepExpr, CalcStepExpr,
  10878. buildPreInits(Context, ExprCaptures),
  10879. buildPostUpdate(*this, ExprPostUpdates));
  10880. }
  10881. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10882. Expr *NumIterations, Sema &SemaRef,
  10883. Scope *S, DSAStackTy *Stack) {
  10884. // Walk the vars and build update/final expressions for the CodeGen.
  10885. SmallVector<Expr *, 8> Updates;
  10886. SmallVector<Expr *, 8> Finals;
  10887. Expr *Step = Clause.getStep();
  10888. Expr *CalcStep = Clause.getCalcStep();
  10889. // OpenMP [2.14.3.7, linear clause]
  10890. // If linear-step is not specified it is assumed to be 1.
  10891. if (!Step)
  10892. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10893. else if (CalcStep)
  10894. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10895. bool HasErrors = false;
  10896. auto CurInit = Clause.inits().begin();
  10897. auto CurPrivate = Clause.privates().begin();
  10898. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  10899. for (Expr *RefExpr : Clause.varlists()) {
  10900. SourceLocation ELoc;
  10901. SourceRange ERange;
  10902. Expr *SimpleRefExpr = RefExpr;
  10903. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  10904. ValueDecl *D = Res.first;
  10905. if (Res.second || !D) {
  10906. Updates.push_back(nullptr);
  10907. Finals.push_back(nullptr);
  10908. HasErrors = true;
  10909. continue;
  10910. }
  10911. auto &&Info = Stack->isLoopControlVariable(D);
  10912. // OpenMP [2.15.11, distribute simd Construct]
  10913. // A list item may not appear in a linear clause, unless it is the loop
  10914. // iteration variable.
  10915. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10916. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10917. SemaRef.Diag(ELoc,
  10918. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10919. Updates.push_back(nullptr);
  10920. Finals.push_back(nullptr);
  10921. HasErrors = true;
  10922. continue;
  10923. }
  10924. Expr *InitExpr = *CurInit;
  10925. // Build privatized reference to the current linear var.
  10926. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10927. Expr *CapturedRef;
  10928. if (LinKind == OMPC_LINEAR_uval)
  10929. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10930. else
  10931. CapturedRef =
  10932. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10933. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10934. /*RefersToCapture=*/true);
  10935. // Build update: Var = InitExpr + IV * Step
  10936. ExprResult Update;
  10937. if (!Info.first)
  10938. Update =
  10939. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10940. InitExpr, IV, Step, /* Subtract */ false);
  10941. else
  10942. Update = *CurPrivate;
  10943. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  10944. /*DiscardedValue=*/true);
  10945. // Build final: Var = InitExpr + NumIterations * Step
  10946. ExprResult Final;
  10947. if (!Info.first)
  10948. Final =
  10949. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10950. InitExpr, NumIterations, Step, /*Subtract=*/false);
  10951. else
  10952. Final = *CurPrivate;
  10953. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  10954. /*DiscardedValue=*/true);
  10955. if (!Update.isUsable() || !Final.isUsable()) {
  10956. Updates.push_back(nullptr);
  10957. Finals.push_back(nullptr);
  10958. HasErrors = true;
  10959. } else {
  10960. Updates.push_back(Update.get());
  10961. Finals.push_back(Final.get());
  10962. }
  10963. ++CurInit;
  10964. ++CurPrivate;
  10965. }
  10966. Clause.setUpdates(Updates);
  10967. Clause.setFinals(Finals);
  10968. return HasErrors;
  10969. }
  10970. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10971. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10972. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10973. SmallVector<Expr *, 8> Vars;
  10974. for (Expr *RefExpr : VarList) {
  10975. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10976. SourceLocation ELoc;
  10977. SourceRange ERange;
  10978. Expr *SimpleRefExpr = RefExpr;
  10979. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10980. if (Res.second) {
  10981. // It will be analyzed later.
  10982. Vars.push_back(RefExpr);
  10983. }
  10984. ValueDecl *D = Res.first;
  10985. if (!D)
  10986. continue;
  10987. QualType QType = D->getType();
  10988. auto *VD = dyn_cast<VarDecl>(D);
  10989. // OpenMP [2.8.1, simd construct, Restrictions]
  10990. // The type of list items appearing in the aligned clause must be
  10991. // array, pointer, reference to array, or reference to pointer.
  10992. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10993. const Type *Ty = QType.getTypePtrOrNull();
  10994. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10995. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10996. << QType << getLangOpts().CPlusPlus << ERange;
  10997. bool IsDecl =
  10998. !VD ||
  10999. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11000. Diag(D->getLocation(),
  11001. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11002. << D;
  11003. continue;
  11004. }
  11005. // OpenMP [2.8.1, simd construct, Restrictions]
  11006. // A list-item cannot appear in more than one aligned clause.
  11007. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  11008. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  11009. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  11010. << getOpenMPClauseName(OMPC_aligned);
  11011. continue;
  11012. }
  11013. DeclRefExpr *Ref = nullptr;
  11014. if (!VD && isOpenMPCapturedDecl(D))
  11015. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11016. Vars.push_back(DefaultFunctionArrayConversion(
  11017. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  11018. .get());
  11019. }
  11020. // OpenMP [2.8.1, simd construct, Description]
  11021. // The parameter of the aligned clause, alignment, must be a constant
  11022. // positive integer expression.
  11023. // If no optional parameter is specified, implementation-defined default
  11024. // alignments for SIMD instructions on the target platforms are assumed.
  11025. if (Alignment != nullptr) {
  11026. ExprResult AlignResult =
  11027. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  11028. if (AlignResult.isInvalid())
  11029. return nullptr;
  11030. Alignment = AlignResult.get();
  11031. }
  11032. if (Vars.empty())
  11033. return nullptr;
  11034. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  11035. EndLoc, Vars, Alignment);
  11036. }
  11037. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  11038. SourceLocation StartLoc,
  11039. SourceLocation LParenLoc,
  11040. SourceLocation EndLoc) {
  11041. SmallVector<Expr *, 8> Vars;
  11042. SmallVector<Expr *, 8> SrcExprs;
  11043. SmallVector<Expr *, 8> DstExprs;
  11044. SmallVector<Expr *, 8> AssignmentOps;
  11045. for (Expr *RefExpr : VarList) {
  11046. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  11047. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11048. // It will be analyzed later.
  11049. Vars.push_back(RefExpr);
  11050. SrcExprs.push_back(nullptr);
  11051. DstExprs.push_back(nullptr);
  11052. AssignmentOps.push_back(nullptr);
  11053. continue;
  11054. }
  11055. SourceLocation ELoc = RefExpr->getExprLoc();
  11056. // OpenMP [2.1, C/C++]
  11057. // A list item is a variable name.
  11058. // OpenMP [2.14.4.1, Restrictions, p.1]
  11059. // A list item that appears in a copyin clause must be threadprivate.
  11060. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  11061. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  11062. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  11063. << 0 << RefExpr->getSourceRange();
  11064. continue;
  11065. }
  11066. Decl *D = DE->getDecl();
  11067. auto *VD = cast<VarDecl>(D);
  11068. QualType Type = VD->getType();
  11069. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  11070. // It will be analyzed later.
  11071. Vars.push_back(DE);
  11072. SrcExprs.push_back(nullptr);
  11073. DstExprs.push_back(nullptr);
  11074. AssignmentOps.push_back(nullptr);
  11075. continue;
  11076. }
  11077. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  11078. // A list item that appears in a copyin clause must be threadprivate.
  11079. if (!DSAStack->isThreadPrivate(VD)) {
  11080. Diag(ELoc, diag::err_omp_required_access)
  11081. << getOpenMPClauseName(OMPC_copyin)
  11082. << getOpenMPDirectiveName(OMPD_threadprivate);
  11083. continue;
  11084. }
  11085. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11086. // A variable of class type (or array thereof) that appears in a
  11087. // copyin clause requires an accessible, unambiguous copy assignment
  11088. // operator for the class type.
  11089. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11090. VarDecl *SrcVD =
  11091. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  11092. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11093. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  11094. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  11095. VarDecl *DstVD =
  11096. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  11097. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11098. DeclRefExpr *PseudoDstExpr =
  11099. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  11100. // For arrays generate assignment operation for single element and replace
  11101. // it by the original array element in CodeGen.
  11102. ExprResult AssignmentOp =
  11103. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  11104. PseudoSrcExpr);
  11105. if (AssignmentOp.isInvalid())
  11106. continue;
  11107. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  11108. /*DiscardedValue=*/true);
  11109. if (AssignmentOp.isInvalid())
  11110. continue;
  11111. DSAStack->addDSA(VD, DE, OMPC_copyin);
  11112. Vars.push_back(DE);
  11113. SrcExprs.push_back(PseudoSrcExpr);
  11114. DstExprs.push_back(PseudoDstExpr);
  11115. AssignmentOps.push_back(AssignmentOp.get());
  11116. }
  11117. if (Vars.empty())
  11118. return nullptr;
  11119. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11120. SrcExprs, DstExprs, AssignmentOps);
  11121. }
  11122. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  11123. SourceLocation StartLoc,
  11124. SourceLocation LParenLoc,
  11125. SourceLocation EndLoc) {
  11126. SmallVector<Expr *, 8> Vars;
  11127. SmallVector<Expr *, 8> SrcExprs;
  11128. SmallVector<Expr *, 8> DstExprs;
  11129. SmallVector<Expr *, 8> AssignmentOps;
  11130. for (Expr *RefExpr : VarList) {
  11131. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11132. SourceLocation ELoc;
  11133. SourceRange ERange;
  11134. Expr *SimpleRefExpr = RefExpr;
  11135. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11136. if (Res.second) {
  11137. // It will be analyzed later.
  11138. Vars.push_back(RefExpr);
  11139. SrcExprs.push_back(nullptr);
  11140. DstExprs.push_back(nullptr);
  11141. AssignmentOps.push_back(nullptr);
  11142. }
  11143. ValueDecl *D = Res.first;
  11144. if (!D)
  11145. continue;
  11146. QualType Type = D->getType();
  11147. auto *VD = dyn_cast<VarDecl>(D);
  11148. // OpenMP [2.14.4.2, Restrictions, p.2]
  11149. // A list item that appears in a copyprivate clause may not appear in a
  11150. // private or firstprivate clause on the single construct.
  11151. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  11152. DSAStackTy::DSAVarData DVar =
  11153. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11154. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  11155. DVar.RefExpr) {
  11156. Diag(ELoc, diag::err_omp_wrong_dsa)
  11157. << getOpenMPClauseName(DVar.CKind)
  11158. << getOpenMPClauseName(OMPC_copyprivate);
  11159. reportOriginalDsa(*this, DSAStack, D, DVar);
  11160. continue;
  11161. }
  11162. // OpenMP [2.11.4.2, Restrictions, p.1]
  11163. // All list items that appear in a copyprivate clause must be either
  11164. // threadprivate or private in the enclosing context.
  11165. if (DVar.CKind == OMPC_unknown) {
  11166. DVar = DSAStack->getImplicitDSA(D, false);
  11167. if (DVar.CKind == OMPC_shared) {
  11168. Diag(ELoc, diag::err_omp_required_access)
  11169. << getOpenMPClauseName(OMPC_copyprivate)
  11170. << "threadprivate or private in the enclosing context";
  11171. reportOriginalDsa(*this, DSAStack, D, DVar);
  11172. continue;
  11173. }
  11174. }
  11175. }
  11176. // Variably modified types are not supported.
  11177. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  11178. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11179. << getOpenMPClauseName(OMPC_copyprivate) << Type
  11180. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11181. bool IsDecl =
  11182. !VD ||
  11183. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11184. Diag(D->getLocation(),
  11185. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11186. << D;
  11187. continue;
  11188. }
  11189. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11190. // A variable of class type (or array thereof) that appears in a
  11191. // copyin clause requires an accessible, unambiguous copy assignment
  11192. // operator for the class type.
  11193. Type = Context.getBaseElementType(Type.getNonReferenceType())
  11194. .getUnqualifiedType();
  11195. VarDecl *SrcVD =
  11196. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  11197. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11198. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  11199. VarDecl *DstVD =
  11200. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  11201. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11202. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11203. ExprResult AssignmentOp = BuildBinOp(
  11204. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  11205. if (AssignmentOp.isInvalid())
  11206. continue;
  11207. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  11208. /*DiscardedValue=*/true);
  11209. if (AssignmentOp.isInvalid())
  11210. continue;
  11211. // No need to mark vars as copyprivate, they are already threadprivate or
  11212. // implicitly private.
  11213. assert(VD || isOpenMPCapturedDecl(D));
  11214. Vars.push_back(
  11215. VD ? RefExpr->IgnoreParens()
  11216. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  11217. SrcExprs.push_back(PseudoSrcExpr);
  11218. DstExprs.push_back(PseudoDstExpr);
  11219. AssignmentOps.push_back(AssignmentOp.get());
  11220. }
  11221. if (Vars.empty())
  11222. return nullptr;
  11223. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11224. Vars, SrcExprs, DstExprs, AssignmentOps);
  11225. }
  11226. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  11227. SourceLocation StartLoc,
  11228. SourceLocation LParenLoc,
  11229. SourceLocation EndLoc) {
  11230. if (VarList.empty())
  11231. return nullptr;
  11232. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  11233. }
  11234. OMPClause *
  11235. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  11236. SourceLocation DepLoc, SourceLocation ColonLoc,
  11237. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11238. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11239. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  11240. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  11241. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11242. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  11243. return nullptr;
  11244. }
  11245. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  11246. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  11247. DepKind == OMPC_DEPEND_sink)) {
  11248. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  11249. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11250. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  11251. /*Last=*/OMPC_DEPEND_unknown, Except)
  11252. << getOpenMPClauseName(OMPC_depend);
  11253. return nullptr;
  11254. }
  11255. SmallVector<Expr *, 8> Vars;
  11256. DSAStackTy::OperatorOffsetTy OpsOffs;
  11257. llvm::APSInt DepCounter(/*BitWidth=*/32);
  11258. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  11259. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  11260. if (const Expr *OrderedCountExpr =
  11261. DSAStack->getParentOrderedRegionParam().first) {
  11262. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  11263. TotalDepCount.setIsUnsigned(/*Val=*/true);
  11264. }
  11265. }
  11266. for (Expr *RefExpr : VarList) {
  11267. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  11268. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11269. // It will be analyzed later.
  11270. Vars.push_back(RefExpr);
  11271. continue;
  11272. }
  11273. SourceLocation ELoc = RefExpr->getExprLoc();
  11274. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  11275. if (DepKind == OMPC_DEPEND_sink) {
  11276. if (DSAStack->getParentOrderedRegionParam().first &&
  11277. DepCounter >= TotalDepCount) {
  11278. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  11279. continue;
  11280. }
  11281. ++DepCounter;
  11282. // OpenMP [2.13.9, Summary]
  11283. // depend(dependence-type : vec), where dependence-type is:
  11284. // 'sink' and where vec is the iteration vector, which has the form:
  11285. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  11286. // where n is the value specified by the ordered clause in the loop
  11287. // directive, xi denotes the loop iteration variable of the i-th nested
  11288. // loop associated with the loop directive, and di is a constant
  11289. // non-negative integer.
  11290. if (CurContext->isDependentContext()) {
  11291. // It will be analyzed later.
  11292. Vars.push_back(RefExpr);
  11293. continue;
  11294. }
  11295. SimpleExpr = SimpleExpr->IgnoreImplicit();
  11296. OverloadedOperatorKind OOK = OO_None;
  11297. SourceLocation OOLoc;
  11298. Expr *LHS = SimpleExpr;
  11299. Expr *RHS = nullptr;
  11300. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  11301. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  11302. OOLoc = BO->getOperatorLoc();
  11303. LHS = BO->getLHS()->IgnoreParenImpCasts();
  11304. RHS = BO->getRHS()->IgnoreParenImpCasts();
  11305. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  11306. OOK = OCE->getOperator();
  11307. OOLoc = OCE->getOperatorLoc();
  11308. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11309. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  11310. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  11311. OOK = MCE->getMethodDecl()
  11312. ->getNameInfo()
  11313. .getName()
  11314. .getCXXOverloadedOperator();
  11315. OOLoc = MCE->getCallee()->getExprLoc();
  11316. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  11317. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11318. }
  11319. SourceLocation ELoc;
  11320. SourceRange ERange;
  11321. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  11322. if (Res.second) {
  11323. // It will be analyzed later.
  11324. Vars.push_back(RefExpr);
  11325. }
  11326. ValueDecl *D = Res.first;
  11327. if (!D)
  11328. continue;
  11329. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  11330. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  11331. continue;
  11332. }
  11333. if (RHS) {
  11334. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  11335. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  11336. if (RHSRes.isInvalid())
  11337. continue;
  11338. }
  11339. if (!CurContext->isDependentContext() &&
  11340. DSAStack->getParentOrderedRegionParam().first &&
  11341. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  11342. const ValueDecl *VD =
  11343. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  11344. if (VD)
  11345. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11346. << 1 << VD;
  11347. else
  11348. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  11349. continue;
  11350. }
  11351. OpsOffs.emplace_back(RHS, OOK);
  11352. } else {
  11353. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  11354. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  11355. (ASE &&
  11356. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  11357. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  11358. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11359. << RefExpr->getSourceRange();
  11360. continue;
  11361. }
  11362. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  11363. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  11364. ExprResult Res =
  11365. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  11366. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  11367. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  11368. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11369. << RefExpr->getSourceRange();
  11370. continue;
  11371. }
  11372. }
  11373. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  11374. }
  11375. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  11376. TotalDepCount > VarList.size() &&
  11377. DSAStack->getParentOrderedRegionParam().first &&
  11378. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  11379. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11380. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  11381. }
  11382. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  11383. Vars.empty())
  11384. return nullptr;
  11385. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11386. DepKind, DepLoc, ColonLoc, Vars,
  11387. TotalDepCount.getZExtValue());
  11388. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  11389. DSAStack->isParentOrderedRegion())
  11390. DSAStack->addDoacrossDependClause(C, OpsOffs);
  11391. return C;
  11392. }
  11393. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  11394. SourceLocation LParenLoc,
  11395. SourceLocation EndLoc) {
  11396. Expr *ValExpr = Device;
  11397. Stmt *HelperValStmt = nullptr;
  11398. // OpenMP [2.9.1, Restrictions]
  11399. // The device expression must evaluate to a non-negative integer value.
  11400. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  11401. /*StrictlyPositive=*/false))
  11402. return nullptr;
  11403. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11404. OpenMPDirectiveKind CaptureRegion =
  11405. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  11406. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11407. ValExpr = MakeFullExpr(ValExpr).get();
  11408. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11409. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11410. HelperValStmt = buildPreInits(Context, Captures);
  11411. }
  11412. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  11413. StartLoc, LParenLoc, EndLoc);
  11414. }
  11415. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  11416. DSAStackTy *Stack, QualType QTy,
  11417. bool FullCheck = true) {
  11418. NamedDecl *ND;
  11419. if (QTy->isIncompleteType(&ND)) {
  11420. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  11421. return false;
  11422. }
  11423. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  11424. !QTy.isTrivialType(SemaRef.Context))
  11425. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  11426. return true;
  11427. }
  11428. /// Return true if it can be proven that the provided array expression
  11429. /// (array section or array subscript) does NOT specify the whole size of the
  11430. /// array whose base type is \a BaseQTy.
  11431. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  11432. const Expr *E,
  11433. QualType BaseQTy) {
  11434. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11435. // If this is an array subscript, it refers to the whole size if the size of
  11436. // the dimension is constant and equals 1. Also, an array section assumes the
  11437. // format of an array subscript if no colon is used.
  11438. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  11439. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11440. return ATy->getSize().getSExtValue() != 1;
  11441. // Size can't be evaluated statically.
  11442. return false;
  11443. }
  11444. assert(OASE && "Expecting array section if not an array subscript.");
  11445. const Expr *LowerBound = OASE->getLowerBound();
  11446. const Expr *Length = OASE->getLength();
  11447. // If there is a lower bound that does not evaluates to zero, we are not
  11448. // covering the whole dimension.
  11449. if (LowerBound) {
  11450. llvm::APSInt ConstLowerBound;
  11451. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  11452. return false; // Can't get the integer value as a constant.
  11453. if (ConstLowerBound.getSExtValue())
  11454. return true;
  11455. }
  11456. // If we don't have a length we covering the whole dimension.
  11457. if (!Length)
  11458. return false;
  11459. // If the base is a pointer, we don't have a way to get the size of the
  11460. // pointee.
  11461. if (BaseQTy->isPointerType())
  11462. return false;
  11463. // We can only check if the length is the same as the size of the dimension
  11464. // if we have a constant array.
  11465. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  11466. if (!CATy)
  11467. return false;
  11468. llvm::APSInt ConstLength;
  11469. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  11470. return false; // Can't get the integer value as a constant.
  11471. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  11472. }
  11473. // Return true if it can be proven that the provided array expression (array
  11474. // section or array subscript) does NOT specify a single element of the array
  11475. // whose base type is \a BaseQTy.
  11476. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  11477. const Expr *E,
  11478. QualType BaseQTy) {
  11479. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11480. // An array subscript always refer to a single element. Also, an array section
  11481. // assumes the format of an array subscript if no colon is used.
  11482. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  11483. return false;
  11484. assert(OASE && "Expecting array section if not an array subscript.");
  11485. const Expr *Length = OASE->getLength();
  11486. // If we don't have a length we have to check if the array has unitary size
  11487. // for this dimension. Also, we should always expect a length if the base type
  11488. // is pointer.
  11489. if (!Length) {
  11490. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11491. return ATy->getSize().getSExtValue() != 1;
  11492. // We cannot assume anything.
  11493. return false;
  11494. }
  11495. // Check if the length evaluates to 1.
  11496. llvm::APSInt ConstLength;
  11497. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  11498. return false; // Can't get the integer value as a constant.
  11499. return ConstLength.getSExtValue() != 1;
  11500. }
  11501. // Return the expression of the base of the mappable expression or null if it
  11502. // cannot be determined and do all the necessary checks to see if the expression
  11503. // is valid as a standalone mappable expression. In the process, record all the
  11504. // components of the expression.
  11505. static const Expr *checkMapClauseExpressionBase(
  11506. Sema &SemaRef, Expr *E,
  11507. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  11508. OpenMPClauseKind CKind, bool NoDiagnose) {
  11509. SourceLocation ELoc = E->getExprLoc();
  11510. SourceRange ERange = E->getSourceRange();
  11511. // The base of elements of list in a map clause have to be either:
  11512. // - a reference to variable or field.
  11513. // - a member expression.
  11514. // - an array expression.
  11515. //
  11516. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  11517. // reference to 'r'.
  11518. //
  11519. // If we have:
  11520. //
  11521. // struct SS {
  11522. // Bla S;
  11523. // foo() {
  11524. // #pragma omp target map (S.Arr[:12]);
  11525. // }
  11526. // }
  11527. //
  11528. // We want to retrieve the member expression 'this->S';
  11529. const Expr *RelevantExpr = nullptr;
  11530. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  11531. // If a list item is an array section, it must specify contiguous storage.
  11532. //
  11533. // For this restriction it is sufficient that we make sure only references
  11534. // to variables or fields and array expressions, and that no array sections
  11535. // exist except in the rightmost expression (unless they cover the whole
  11536. // dimension of the array). E.g. these would be invalid:
  11537. //
  11538. // r.ArrS[3:5].Arr[6:7]
  11539. //
  11540. // r.ArrS[3:5].x
  11541. //
  11542. // but these would be valid:
  11543. // r.ArrS[3].Arr[6:7]
  11544. //
  11545. // r.ArrS[3].x
  11546. bool AllowUnitySizeArraySection = true;
  11547. bool AllowWholeSizeArraySection = true;
  11548. while (!RelevantExpr) {
  11549. E = E->IgnoreParenImpCasts();
  11550. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  11551. if (!isa<VarDecl>(CurE->getDecl()))
  11552. return nullptr;
  11553. RelevantExpr = CurE;
  11554. // If we got a reference to a declaration, we should not expect any array
  11555. // section before that.
  11556. AllowUnitySizeArraySection = false;
  11557. AllowWholeSizeArraySection = false;
  11558. // Record the component.
  11559. CurComponents.emplace_back(CurE, CurE->getDecl());
  11560. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  11561. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  11562. if (isa<CXXThisExpr>(BaseE))
  11563. // We found a base expression: this->Val.
  11564. RelevantExpr = CurE;
  11565. else
  11566. E = BaseE;
  11567. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  11568. if (!NoDiagnose) {
  11569. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  11570. << CurE->getSourceRange();
  11571. return nullptr;
  11572. }
  11573. if (RelevantExpr)
  11574. return nullptr;
  11575. continue;
  11576. }
  11577. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  11578. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  11579. // A bit-field cannot appear in a map clause.
  11580. //
  11581. if (FD->isBitField()) {
  11582. if (!NoDiagnose) {
  11583. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  11584. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  11585. return nullptr;
  11586. }
  11587. if (RelevantExpr)
  11588. return nullptr;
  11589. continue;
  11590. }
  11591. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11592. // If the type of a list item is a reference to a type T then the type
  11593. // will be considered to be T for all purposes of this clause.
  11594. QualType CurType = BaseE->getType().getNonReferenceType();
  11595. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  11596. // A list item cannot be a variable that is a member of a structure with
  11597. // a union type.
  11598. //
  11599. if (CurType->isUnionType()) {
  11600. if (!NoDiagnose) {
  11601. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  11602. << CurE->getSourceRange();
  11603. return nullptr;
  11604. }
  11605. continue;
  11606. }
  11607. // If we got a member expression, we should not expect any array section
  11608. // before that:
  11609. //
  11610. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  11611. // If a list item is an element of a structure, only the rightmost symbol
  11612. // of the variable reference can be an array section.
  11613. //
  11614. AllowUnitySizeArraySection = false;
  11615. AllowWholeSizeArraySection = false;
  11616. // Record the component.
  11617. CurComponents.emplace_back(CurE, FD);
  11618. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  11619. E = CurE->getBase()->IgnoreParenImpCasts();
  11620. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  11621. if (!NoDiagnose) {
  11622. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11623. << 0 << CurE->getSourceRange();
  11624. return nullptr;
  11625. }
  11626. continue;
  11627. }
  11628. // If we got an array subscript that express the whole dimension we
  11629. // can have any array expressions before. If it only expressing part of
  11630. // the dimension, we can only have unitary-size array expressions.
  11631. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  11632. E->getType()))
  11633. AllowWholeSizeArraySection = false;
  11634. // Record the component - we don't have any declaration associated.
  11635. CurComponents.emplace_back(CurE, nullptr);
  11636. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  11637. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  11638. E = CurE->getBase()->IgnoreParenImpCasts();
  11639. QualType CurType =
  11640. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11641. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11642. // If the type of a list item is a reference to a type T then the type
  11643. // will be considered to be T for all purposes of this clause.
  11644. if (CurType->isReferenceType())
  11645. CurType = CurType->getPointeeType();
  11646. bool IsPointer = CurType->isAnyPointerType();
  11647. if (!IsPointer && !CurType->isArrayType()) {
  11648. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11649. << 0 << CurE->getSourceRange();
  11650. return nullptr;
  11651. }
  11652. bool NotWhole =
  11653. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  11654. bool NotUnity =
  11655. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  11656. if (AllowWholeSizeArraySection) {
  11657. // Any array section is currently allowed. Allowing a whole size array
  11658. // section implies allowing a unity array section as well.
  11659. //
  11660. // If this array section refers to the whole dimension we can still
  11661. // accept other array sections before this one, except if the base is a
  11662. // pointer. Otherwise, only unitary sections are accepted.
  11663. if (NotWhole || IsPointer)
  11664. AllowWholeSizeArraySection = false;
  11665. } else if (AllowUnitySizeArraySection && NotUnity) {
  11666. // A unity or whole array section is not allowed and that is not
  11667. // compatible with the properties of the current array section.
  11668. SemaRef.Diag(
  11669. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  11670. << CurE->getSourceRange();
  11671. return nullptr;
  11672. }
  11673. // Record the component - we don't have any declaration associated.
  11674. CurComponents.emplace_back(CurE, nullptr);
  11675. } else {
  11676. if (!NoDiagnose) {
  11677. // If nothing else worked, this is not a valid map clause expression.
  11678. SemaRef.Diag(
  11679. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  11680. << ERange;
  11681. }
  11682. return nullptr;
  11683. }
  11684. }
  11685. return RelevantExpr;
  11686. }
  11687. // Return true if expression E associated with value VD has conflicts with other
  11688. // map information.
  11689. static bool checkMapConflicts(
  11690. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  11691. bool CurrentRegionOnly,
  11692. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  11693. OpenMPClauseKind CKind) {
  11694. assert(VD && E);
  11695. SourceLocation ELoc = E->getExprLoc();
  11696. SourceRange ERange = E->getSourceRange();
  11697. // In order to easily check the conflicts we need to match each component of
  11698. // the expression under test with the components of the expressions that are
  11699. // already in the stack.
  11700. assert(!CurComponents.empty() && "Map clause expression with no components!");
  11701. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  11702. "Map clause expression with unexpected base!");
  11703. // Variables to help detecting enclosing problems in data environment nests.
  11704. bool IsEnclosedByDataEnvironmentExpr = false;
  11705. const Expr *EnclosingExpr = nullptr;
  11706. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  11707. VD, CurrentRegionOnly,
  11708. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  11709. ERange, CKind, &EnclosingExpr,
  11710. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  11711. StackComponents,
  11712. OpenMPClauseKind) {
  11713. assert(!StackComponents.empty() &&
  11714. "Map clause expression with no components!");
  11715. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  11716. "Map clause expression with unexpected base!");
  11717. (void)VD;
  11718. // The whole expression in the stack.
  11719. const Expr *RE = StackComponents.front().getAssociatedExpression();
  11720. // Expressions must start from the same base. Here we detect at which
  11721. // point both expressions diverge from each other and see if we can
  11722. // detect if the memory referred to both expressions is contiguous and
  11723. // do not overlap.
  11724. auto CI = CurComponents.rbegin();
  11725. auto CE = CurComponents.rend();
  11726. auto SI = StackComponents.rbegin();
  11727. auto SE = StackComponents.rend();
  11728. for (; CI != CE && SI != SE; ++CI, ++SI) {
  11729. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  11730. // At most one list item can be an array item derived from a given
  11731. // variable in map clauses of the same construct.
  11732. if (CurrentRegionOnly &&
  11733. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  11734. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  11735. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  11736. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  11737. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  11738. diag::err_omp_multiple_array_items_in_map_clause)
  11739. << CI->getAssociatedExpression()->getSourceRange();
  11740. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  11741. diag::note_used_here)
  11742. << SI->getAssociatedExpression()->getSourceRange();
  11743. return true;
  11744. }
  11745. // Do both expressions have the same kind?
  11746. if (CI->getAssociatedExpression()->getStmtClass() !=
  11747. SI->getAssociatedExpression()->getStmtClass())
  11748. break;
  11749. // Are we dealing with different variables/fields?
  11750. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  11751. break;
  11752. }
  11753. // Check if the extra components of the expressions in the enclosing
  11754. // data environment are redundant for the current base declaration.
  11755. // If they are, the maps completely overlap, which is legal.
  11756. for (; SI != SE; ++SI) {
  11757. QualType Type;
  11758. if (const auto *ASE =
  11759. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  11760. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  11761. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  11762. SI->getAssociatedExpression())) {
  11763. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  11764. Type =
  11765. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11766. }
  11767. if (Type.isNull() || Type->isAnyPointerType() ||
  11768. checkArrayExpressionDoesNotReferToWholeSize(
  11769. SemaRef, SI->getAssociatedExpression(), Type))
  11770. break;
  11771. }
  11772. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11773. // List items of map clauses in the same construct must not share
  11774. // original storage.
  11775. //
  11776. // If the expressions are exactly the same or one is a subset of the
  11777. // other, it means they are sharing storage.
  11778. if (CI == CE && SI == SE) {
  11779. if (CurrentRegionOnly) {
  11780. if (CKind == OMPC_map) {
  11781. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11782. } else {
  11783. assert(CKind == OMPC_to || CKind == OMPC_from);
  11784. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11785. << ERange;
  11786. }
  11787. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11788. << RE->getSourceRange();
  11789. return true;
  11790. }
  11791. // If we find the same expression in the enclosing data environment,
  11792. // that is legal.
  11793. IsEnclosedByDataEnvironmentExpr = true;
  11794. return false;
  11795. }
  11796. QualType DerivedType =
  11797. std::prev(CI)->getAssociatedDeclaration()->getType();
  11798. SourceLocation DerivedLoc =
  11799. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  11800. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11801. // If the type of a list item is a reference to a type T then the type
  11802. // will be considered to be T for all purposes of this clause.
  11803. DerivedType = DerivedType.getNonReferenceType();
  11804. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  11805. // A variable for which the type is pointer and an array section
  11806. // derived from that variable must not appear as list items of map
  11807. // clauses of the same construct.
  11808. //
  11809. // Also, cover one of the cases in:
  11810. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11811. // If any part of the original storage of a list item has corresponding
  11812. // storage in the device data environment, all of the original storage
  11813. // must have corresponding storage in the device data environment.
  11814. //
  11815. if (DerivedType->isAnyPointerType()) {
  11816. if (CI == CE || SI == SE) {
  11817. SemaRef.Diag(
  11818. DerivedLoc,
  11819. diag::err_omp_pointer_mapped_along_with_derived_section)
  11820. << DerivedLoc;
  11821. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11822. << RE->getSourceRange();
  11823. return true;
  11824. }
  11825. if (CI->getAssociatedExpression()->getStmtClass() !=
  11826. SI->getAssociatedExpression()->getStmtClass() ||
  11827. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  11828. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  11829. assert(CI != CE && SI != SE);
  11830. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  11831. << DerivedLoc;
  11832. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11833. << RE->getSourceRange();
  11834. return true;
  11835. }
  11836. }
  11837. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  11838. // List items of map clauses in the same construct must not share
  11839. // original storage.
  11840. //
  11841. // An expression is a subset of the other.
  11842. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  11843. if (CKind == OMPC_map) {
  11844. if (CI != CE || SI != SE) {
  11845. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  11846. // a pointer.
  11847. auto Begin =
  11848. CI != CE ? CurComponents.begin() : StackComponents.begin();
  11849. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  11850. auto It = Begin;
  11851. while (It != End && !It->getAssociatedDeclaration())
  11852. std::advance(It, 1);
  11853. assert(It != End &&
  11854. "Expected at least one component with the declaration.");
  11855. if (It != Begin && It->getAssociatedDeclaration()
  11856. ->getType()
  11857. .getCanonicalType()
  11858. ->isAnyPointerType()) {
  11859. IsEnclosedByDataEnvironmentExpr = false;
  11860. EnclosingExpr = nullptr;
  11861. return false;
  11862. }
  11863. }
  11864. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  11865. } else {
  11866. assert(CKind == OMPC_to || CKind == OMPC_from);
  11867. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  11868. << ERange;
  11869. }
  11870. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11871. << RE->getSourceRange();
  11872. return true;
  11873. }
  11874. // The current expression uses the same base as other expression in the
  11875. // data environment but does not contain it completely.
  11876. if (!CurrentRegionOnly && SI != SE)
  11877. EnclosingExpr = RE;
  11878. // The current expression is a subset of the expression in the data
  11879. // environment.
  11880. IsEnclosedByDataEnvironmentExpr |=
  11881. (!CurrentRegionOnly && CI != CE && SI == SE);
  11882. return false;
  11883. });
  11884. if (CurrentRegionOnly)
  11885. return FoundError;
  11886. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11887. // If any part of the original storage of a list item has corresponding
  11888. // storage in the device data environment, all of the original storage must
  11889. // have corresponding storage in the device data environment.
  11890. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11891. // If a list item is an element of a structure, and a different element of
  11892. // the structure has a corresponding list item in the device data environment
  11893. // prior to a task encountering the construct associated with the map clause,
  11894. // then the list item must also have a corresponding list item in the device
  11895. // data environment prior to the task encountering the construct.
  11896. //
  11897. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11898. SemaRef.Diag(ELoc,
  11899. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11900. << ERange;
  11901. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11902. << EnclosingExpr->getSourceRange();
  11903. return true;
  11904. }
  11905. return FoundError;
  11906. }
  11907. namespace {
  11908. // Utility struct that gathers all the related lists associated with a mappable
  11909. // expression.
  11910. struct MappableVarListInfo {
  11911. // The list of expressions.
  11912. ArrayRef<Expr *> VarList;
  11913. // The list of processed expressions.
  11914. SmallVector<Expr *, 16> ProcessedVarList;
  11915. // The mappble components for each expression.
  11916. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11917. // The base declaration of the variable.
  11918. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11919. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11920. // We have a list of components and base declarations for each entry in the
  11921. // variable list.
  11922. VarComponents.reserve(VarList.size());
  11923. VarBaseDeclarations.reserve(VarList.size());
  11924. }
  11925. };
  11926. }
  11927. // Check the validity of the provided variable list for the provided clause kind
  11928. // \a CKind. In the check process the valid expressions, and mappable expression
  11929. // components and variables are extracted and used to fill \a Vars,
  11930. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11931. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11932. static void
  11933. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11934. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11935. SourceLocation StartLoc,
  11936. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11937. bool IsMapTypeImplicit = false) {
  11938. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11939. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11940. "Unexpected clause kind with mappable expressions!");
  11941. // Keep track of the mappable components and base declarations in this clause.
  11942. // Each entry in the list is going to have a list of components associated. We
  11943. // record each set of the components so that we can build the clause later on.
  11944. // In the end we should have the same amount of declarations and component
  11945. // lists.
  11946. for (Expr *RE : MVLI.VarList) {
  11947. assert(RE && "Null expr in omp to/from/map clause");
  11948. SourceLocation ELoc = RE->getExprLoc();
  11949. const Expr *VE = RE->IgnoreParenLValueCasts();
  11950. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11951. VE->isInstantiationDependent() ||
  11952. VE->containsUnexpandedParameterPack()) {
  11953. // We can only analyze this information once the missing information is
  11954. // resolved.
  11955. MVLI.ProcessedVarList.push_back(RE);
  11956. continue;
  11957. }
  11958. Expr *SimpleExpr = RE->IgnoreParenCasts();
  11959. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11960. SemaRef.Diag(ELoc,
  11961. diag::err_omp_expected_named_var_member_or_array_expression)
  11962. << RE->getSourceRange();
  11963. continue;
  11964. }
  11965. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11966. ValueDecl *CurDeclaration = nullptr;
  11967. // Obtain the array or member expression bases if required. Also, fill the
  11968. // components array with all the components identified in the process.
  11969. const Expr *BE = checkMapClauseExpressionBase(
  11970. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  11971. if (!BE)
  11972. continue;
  11973. assert(!CurComponents.empty() &&
  11974. "Invalid mappable expression information.");
  11975. // For the following checks, we rely on the base declaration which is
  11976. // expected to be associated with the last component. The declaration is
  11977. // expected to be a variable or a field (if 'this' is being mapped).
  11978. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11979. assert(CurDeclaration && "Null decl on map clause.");
  11980. assert(
  11981. CurDeclaration->isCanonicalDecl() &&
  11982. "Expecting components to have associated only canonical declarations.");
  11983. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11984. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11985. assert((VD || FD) && "Only variables or fields are expected here!");
  11986. (void)FD;
  11987. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11988. // threadprivate variables cannot appear in a map clause.
  11989. // OpenMP 4.5 [2.10.5, target update Construct]
  11990. // threadprivate variables cannot appear in a from clause.
  11991. if (VD && DSAS->isThreadPrivate(VD)) {
  11992. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  11993. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11994. << getOpenMPClauseName(CKind);
  11995. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  11996. continue;
  11997. }
  11998. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11999. // A list item cannot appear in both a map clause and a data-sharing
  12000. // attribute clause on the same construct.
  12001. // Check conflicts with other map clause expressions. We check the conflicts
  12002. // with the current construct separately from the enclosing data
  12003. // environment, because the restrictions are different. We only have to
  12004. // check conflicts across regions for the map clauses.
  12005. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12006. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  12007. break;
  12008. if (CKind == OMPC_map &&
  12009. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12010. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  12011. break;
  12012. // OpenMP 4.5 [2.10.5, target update Construct]
  12013. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12014. // If the type of a list item is a reference to a type T then the type will
  12015. // be considered to be T for all purposes of this clause.
  12016. auto I = llvm::find_if(
  12017. CurComponents,
  12018. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  12019. return MC.getAssociatedDeclaration();
  12020. });
  12021. assert(I != CurComponents.end() && "Null decl on map clause.");
  12022. QualType Type =
  12023. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  12024. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  12025. // A list item in a to or from clause must have a mappable type.
  12026. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12027. // A list item must have a mappable type.
  12028. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  12029. DSAS, Type))
  12030. continue;
  12031. if (CKind == OMPC_map) {
  12032. // target enter data
  12033. // OpenMP [2.10.2, Restrictions, p. 99]
  12034. // A map-type must be specified in all map clauses and must be either
  12035. // to or alloc.
  12036. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  12037. if (DKind == OMPD_target_enter_data &&
  12038. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  12039. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12040. << (IsMapTypeImplicit ? 1 : 0)
  12041. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12042. << getOpenMPDirectiveName(DKind);
  12043. continue;
  12044. }
  12045. // target exit_data
  12046. // OpenMP [2.10.3, Restrictions, p. 102]
  12047. // A map-type must be specified in all map clauses and must be either
  12048. // from, release, or delete.
  12049. if (DKind == OMPD_target_exit_data &&
  12050. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  12051. MapType == OMPC_MAP_delete)) {
  12052. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12053. << (IsMapTypeImplicit ? 1 : 0)
  12054. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12055. << getOpenMPDirectiveName(DKind);
  12056. continue;
  12057. }
  12058. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  12059. // A list item cannot appear in both a map clause and a data-sharing
  12060. // attribute clause on the same construct
  12061. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  12062. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12063. if (isOpenMPPrivate(DVar.CKind)) {
  12064. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12065. << getOpenMPClauseName(DVar.CKind)
  12066. << getOpenMPClauseName(OMPC_map)
  12067. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  12068. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  12069. continue;
  12070. }
  12071. }
  12072. }
  12073. // Save the current expression.
  12074. MVLI.ProcessedVarList.push_back(RE);
  12075. // Store the components in the stack so that they can be used to check
  12076. // against other clauses later on.
  12077. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  12078. /*WhereFoundClauseKind=*/OMPC_map);
  12079. // Save the components and declaration to create the clause. For purposes of
  12080. // the clause creation, any component list that has has base 'this' uses
  12081. // null as base declaration.
  12082. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12083. MVLI.VarComponents.back().append(CurComponents.begin(),
  12084. CurComponents.end());
  12085. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  12086. : CurDeclaration);
  12087. }
  12088. }
  12089. OMPClause *
  12090. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  12091. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  12092. SourceLocation MapLoc, SourceLocation ColonLoc,
  12093. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  12094. SourceLocation LParenLoc, SourceLocation EndLoc) {
  12095. MappableVarListInfo MVLI(VarList);
  12096. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  12097. MapType, IsMapTypeImplicit);
  12098. // We need to produce a map clause even if we don't have variables so that
  12099. // other diagnostics related with non-existing map clauses are accurate.
  12100. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12101. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12102. MVLI.VarComponents, MapTypeModifier, MapType,
  12103. IsMapTypeImplicit, MapLoc);
  12104. }
  12105. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  12106. TypeResult ParsedType) {
  12107. assert(ParsedType.isUsable());
  12108. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  12109. if (ReductionType.isNull())
  12110. return QualType();
  12111. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  12112. // A type name in a declare reduction directive cannot be a function type, an
  12113. // array type, a reference type, or a type qualified with const, volatile or
  12114. // restrict.
  12115. if (ReductionType.hasQualifiers()) {
  12116. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  12117. return QualType();
  12118. }
  12119. if (ReductionType->isFunctionType()) {
  12120. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  12121. return QualType();
  12122. }
  12123. if (ReductionType->isReferenceType()) {
  12124. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  12125. return QualType();
  12126. }
  12127. if (ReductionType->isArrayType()) {
  12128. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  12129. return QualType();
  12130. }
  12131. return ReductionType;
  12132. }
  12133. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  12134. Scope *S, DeclContext *DC, DeclarationName Name,
  12135. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  12136. AccessSpecifier AS, Decl *PrevDeclInScope) {
  12137. SmallVector<Decl *, 8> Decls;
  12138. Decls.reserve(ReductionTypes.size());
  12139. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  12140. forRedeclarationInCurContext());
  12141. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  12142. // A reduction-identifier may not be re-declared in the current scope for the
  12143. // same type or for a type that is compatible according to the base language
  12144. // rules.
  12145. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12146. OMPDeclareReductionDecl *PrevDRD = nullptr;
  12147. bool InCompoundScope = true;
  12148. if (S != nullptr) {
  12149. // Find previous declaration with the same name not referenced in other
  12150. // declarations.
  12151. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12152. InCompoundScope =
  12153. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12154. LookupName(Lookup, S);
  12155. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12156. /*AllowInlineNamespace=*/false);
  12157. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  12158. LookupResult::Filter Filter = Lookup.makeFilter();
  12159. while (Filter.hasNext()) {
  12160. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  12161. if (InCompoundScope) {
  12162. auto I = UsedAsPrevious.find(PrevDecl);
  12163. if (I == UsedAsPrevious.end())
  12164. UsedAsPrevious[PrevDecl] = false;
  12165. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  12166. UsedAsPrevious[D] = true;
  12167. }
  12168. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12169. PrevDecl->getLocation();
  12170. }
  12171. Filter.done();
  12172. if (InCompoundScope) {
  12173. for (const auto &PrevData : UsedAsPrevious) {
  12174. if (!PrevData.second) {
  12175. PrevDRD = PrevData.first;
  12176. break;
  12177. }
  12178. }
  12179. }
  12180. } else if (PrevDeclInScope != nullptr) {
  12181. auto *PrevDRDInScope = PrevDRD =
  12182. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  12183. do {
  12184. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  12185. PrevDRDInScope->getLocation();
  12186. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  12187. } while (PrevDRDInScope != nullptr);
  12188. }
  12189. for (const auto &TyData : ReductionTypes) {
  12190. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  12191. bool Invalid = false;
  12192. if (I != PreviousRedeclTypes.end()) {
  12193. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  12194. << TyData.first;
  12195. Diag(I->second, diag::note_previous_definition);
  12196. Invalid = true;
  12197. }
  12198. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  12199. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  12200. Name, TyData.first, PrevDRD);
  12201. DC->addDecl(DRD);
  12202. DRD->setAccess(AS);
  12203. Decls.push_back(DRD);
  12204. if (Invalid)
  12205. DRD->setInvalidDecl();
  12206. else
  12207. PrevDRD = DRD;
  12208. }
  12209. return DeclGroupPtrTy::make(
  12210. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  12211. }
  12212. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  12213. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12214. // Enter new function scope.
  12215. PushFunctionScope();
  12216. setFunctionHasBranchProtectedScope();
  12217. getCurFunction()->setHasOMPDeclareReductionCombiner();
  12218. if (S != nullptr)
  12219. PushDeclContext(S, DRD);
  12220. else
  12221. CurContext = DRD;
  12222. PushExpressionEvaluationContext(
  12223. ExpressionEvaluationContext::PotentiallyEvaluated);
  12224. QualType ReductionType = DRD->getType();
  12225. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  12226. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  12227. // uses semantics of argument handles by value, but it should be passed by
  12228. // reference. C lang does not support references, so pass all parameters as
  12229. // pointers.
  12230. // Create 'T omp_in;' variable.
  12231. VarDecl *OmpInParm =
  12232. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  12233. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  12234. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  12235. // uses semantics of argument handles by value, but it should be passed by
  12236. // reference. C lang does not support references, so pass all parameters as
  12237. // pointers.
  12238. // Create 'T omp_out;' variable.
  12239. VarDecl *OmpOutParm =
  12240. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  12241. if (S != nullptr) {
  12242. PushOnScopeChains(OmpInParm, S);
  12243. PushOnScopeChains(OmpOutParm, S);
  12244. } else {
  12245. DRD->addDecl(OmpInParm);
  12246. DRD->addDecl(OmpOutParm);
  12247. }
  12248. Expr *InE =
  12249. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  12250. Expr *OutE =
  12251. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  12252. DRD->setCombinerData(InE, OutE);
  12253. }
  12254. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  12255. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12256. DiscardCleanupsInEvaluationContext();
  12257. PopExpressionEvaluationContext();
  12258. PopDeclContext();
  12259. PopFunctionScopeInfo();
  12260. if (Combiner != nullptr)
  12261. DRD->setCombiner(Combiner);
  12262. else
  12263. DRD->setInvalidDecl();
  12264. }
  12265. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  12266. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12267. // Enter new function scope.
  12268. PushFunctionScope();
  12269. setFunctionHasBranchProtectedScope();
  12270. if (S != nullptr)
  12271. PushDeclContext(S, DRD);
  12272. else
  12273. CurContext = DRD;
  12274. PushExpressionEvaluationContext(
  12275. ExpressionEvaluationContext::PotentiallyEvaluated);
  12276. QualType ReductionType = DRD->getType();
  12277. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  12278. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  12279. // uses semantics of argument handles by value, but it should be passed by
  12280. // reference. C lang does not support references, so pass all parameters as
  12281. // pointers.
  12282. // Create 'T omp_priv;' variable.
  12283. VarDecl *OmpPrivParm =
  12284. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  12285. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  12286. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  12287. // uses semantics of argument handles by value, but it should be passed by
  12288. // reference. C lang does not support references, so pass all parameters as
  12289. // pointers.
  12290. // Create 'T omp_orig;' variable.
  12291. VarDecl *OmpOrigParm =
  12292. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  12293. if (S != nullptr) {
  12294. PushOnScopeChains(OmpPrivParm, S);
  12295. PushOnScopeChains(OmpOrigParm, S);
  12296. } else {
  12297. DRD->addDecl(OmpPrivParm);
  12298. DRD->addDecl(OmpOrigParm);
  12299. }
  12300. Expr *OrigE =
  12301. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  12302. Expr *PrivE =
  12303. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  12304. DRD->setInitializerData(OrigE, PrivE);
  12305. return OmpPrivParm;
  12306. }
  12307. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  12308. VarDecl *OmpPrivParm) {
  12309. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12310. DiscardCleanupsInEvaluationContext();
  12311. PopExpressionEvaluationContext();
  12312. PopDeclContext();
  12313. PopFunctionScopeInfo();
  12314. if (Initializer != nullptr) {
  12315. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  12316. } else if (OmpPrivParm->hasInit()) {
  12317. DRD->setInitializer(OmpPrivParm->getInit(),
  12318. OmpPrivParm->isDirectInit()
  12319. ? OMPDeclareReductionDecl::DirectInit
  12320. : OMPDeclareReductionDecl::CopyInit);
  12321. } else {
  12322. DRD->setInvalidDecl();
  12323. }
  12324. }
  12325. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  12326. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  12327. for (Decl *D : DeclReductions.get()) {
  12328. if (IsValid) {
  12329. if (S)
  12330. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  12331. /*AddToContext=*/false);
  12332. } else {
  12333. D->setInvalidDecl();
  12334. }
  12335. }
  12336. return DeclReductions;
  12337. }
  12338. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  12339. SourceLocation StartLoc,
  12340. SourceLocation LParenLoc,
  12341. SourceLocation EndLoc) {
  12342. Expr *ValExpr = NumTeams;
  12343. Stmt *HelperValStmt = nullptr;
  12344. // OpenMP [teams Constrcut, Restrictions]
  12345. // The num_teams expression must evaluate to a positive integer value.
  12346. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  12347. /*StrictlyPositive=*/true))
  12348. return nullptr;
  12349. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12350. OpenMPDirectiveKind CaptureRegion =
  12351. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  12352. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12353. ValExpr = MakeFullExpr(ValExpr).get();
  12354. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12355. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12356. HelperValStmt = buildPreInits(Context, Captures);
  12357. }
  12358. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  12359. StartLoc, LParenLoc, EndLoc);
  12360. }
  12361. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  12362. SourceLocation StartLoc,
  12363. SourceLocation LParenLoc,
  12364. SourceLocation EndLoc) {
  12365. Expr *ValExpr = ThreadLimit;
  12366. Stmt *HelperValStmt = nullptr;
  12367. // OpenMP [teams Constrcut, Restrictions]
  12368. // The thread_limit expression must evaluate to a positive integer value.
  12369. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  12370. /*StrictlyPositive=*/true))
  12371. return nullptr;
  12372. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12373. OpenMPDirectiveKind CaptureRegion =
  12374. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  12375. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12376. ValExpr = MakeFullExpr(ValExpr).get();
  12377. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12378. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12379. HelperValStmt = buildPreInits(Context, Captures);
  12380. }
  12381. return new (Context) OMPThreadLimitClause(
  12382. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  12383. }
  12384. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  12385. SourceLocation StartLoc,
  12386. SourceLocation LParenLoc,
  12387. SourceLocation EndLoc) {
  12388. Expr *ValExpr = Priority;
  12389. // OpenMP [2.9.1, task Constrcut]
  12390. // The priority-value is a non-negative numerical scalar expression.
  12391. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  12392. /*StrictlyPositive=*/false))
  12393. return nullptr;
  12394. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12395. }
  12396. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  12397. SourceLocation StartLoc,
  12398. SourceLocation LParenLoc,
  12399. SourceLocation EndLoc) {
  12400. Expr *ValExpr = Grainsize;
  12401. // OpenMP [2.9.2, taskloop Constrcut]
  12402. // The parameter of the grainsize clause must be a positive integer
  12403. // expression.
  12404. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  12405. /*StrictlyPositive=*/true))
  12406. return nullptr;
  12407. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12408. }
  12409. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  12410. SourceLocation StartLoc,
  12411. SourceLocation LParenLoc,
  12412. SourceLocation EndLoc) {
  12413. Expr *ValExpr = NumTasks;
  12414. // OpenMP [2.9.2, taskloop Constrcut]
  12415. // The parameter of the num_tasks clause must be a positive integer
  12416. // expression.
  12417. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  12418. /*StrictlyPositive=*/true))
  12419. return nullptr;
  12420. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12421. }
  12422. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  12423. SourceLocation LParenLoc,
  12424. SourceLocation EndLoc) {
  12425. // OpenMP [2.13.2, critical construct, Description]
  12426. // ... where hint-expression is an integer constant expression that evaluates
  12427. // to a valid lock hint.
  12428. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  12429. if (HintExpr.isInvalid())
  12430. return nullptr;
  12431. return new (Context)
  12432. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  12433. }
  12434. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  12435. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  12436. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  12437. SourceLocation EndLoc) {
  12438. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  12439. std::string Values;
  12440. Values += "'";
  12441. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  12442. Values += "'";
  12443. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  12444. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  12445. return nullptr;
  12446. }
  12447. Expr *ValExpr = ChunkSize;
  12448. Stmt *HelperValStmt = nullptr;
  12449. if (ChunkSize) {
  12450. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  12451. !ChunkSize->isInstantiationDependent() &&
  12452. !ChunkSize->containsUnexpandedParameterPack()) {
  12453. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  12454. ExprResult Val =
  12455. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  12456. if (Val.isInvalid())
  12457. return nullptr;
  12458. ValExpr = Val.get();
  12459. // OpenMP [2.7.1, Restrictions]
  12460. // chunk_size must be a loop invariant integer expression with a positive
  12461. // value.
  12462. llvm::APSInt Result;
  12463. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  12464. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  12465. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  12466. << "dist_schedule" << ChunkSize->getSourceRange();
  12467. return nullptr;
  12468. }
  12469. } else if (getOpenMPCaptureRegionForClause(
  12470. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  12471. OMPD_unknown &&
  12472. !CurContext->isDependentContext()) {
  12473. ValExpr = MakeFullExpr(ValExpr).get();
  12474. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12475. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12476. HelperValStmt = buildPreInits(Context, Captures);
  12477. }
  12478. }
  12479. }
  12480. return new (Context)
  12481. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  12482. Kind, ValExpr, HelperValStmt);
  12483. }
  12484. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  12485. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  12486. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  12487. SourceLocation KindLoc, SourceLocation EndLoc) {
  12488. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  12489. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  12490. std::string Value;
  12491. SourceLocation Loc;
  12492. Value += "'";
  12493. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  12494. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  12495. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  12496. Loc = MLoc;
  12497. } else {
  12498. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  12499. OMPC_DEFAULTMAP_scalar);
  12500. Loc = KindLoc;
  12501. }
  12502. Value += "'";
  12503. Diag(Loc, diag::err_omp_unexpected_clause_value)
  12504. << Value << getOpenMPClauseName(OMPC_defaultmap);
  12505. return nullptr;
  12506. }
  12507. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  12508. return new (Context)
  12509. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  12510. }
  12511. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  12512. DeclContext *CurLexicalContext = getCurLexicalContext();
  12513. if (!CurLexicalContext->isFileContext() &&
  12514. !CurLexicalContext->isExternCContext() &&
  12515. !CurLexicalContext->isExternCXXContext() &&
  12516. !isa<CXXRecordDecl>(CurLexicalContext) &&
  12517. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  12518. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  12519. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  12520. Diag(Loc, diag::err_omp_region_not_file_context);
  12521. return false;
  12522. }
  12523. ++DeclareTargetNestingLevel;
  12524. return true;
  12525. }
  12526. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  12527. assert(DeclareTargetNestingLevel > 0 &&
  12528. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  12529. --DeclareTargetNestingLevel;
  12530. }
  12531. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  12532. CXXScopeSpec &ScopeSpec,
  12533. const DeclarationNameInfo &Id,
  12534. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  12535. NamedDeclSetType &SameDirectiveDecls) {
  12536. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  12537. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  12538. if (Lookup.isAmbiguous())
  12539. return;
  12540. Lookup.suppressDiagnostics();
  12541. if (!Lookup.isSingleResult()) {
  12542. if (TypoCorrection Corrected =
  12543. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  12544. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  12545. CTK_ErrorRecovery)) {
  12546. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  12547. << Id.getName());
  12548. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  12549. return;
  12550. }
  12551. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  12552. return;
  12553. }
  12554. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  12555. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  12556. isa<FunctionTemplateDecl>(ND)) {
  12557. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  12558. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  12559. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  12560. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  12561. cast<ValueDecl>(ND));
  12562. if (!Res) {
  12563. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  12564. ND->addAttr(A);
  12565. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12566. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  12567. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  12568. } else if (*Res != MT) {
  12569. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  12570. << Id.getName();
  12571. }
  12572. } else {
  12573. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  12574. }
  12575. }
  12576. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  12577. Sema &SemaRef, Decl *D) {
  12578. if (!D || !isa<VarDecl>(D))
  12579. return;
  12580. auto *VD = cast<VarDecl>(D);
  12581. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  12582. return;
  12583. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  12584. SemaRef.Diag(SL, diag::note_used_here) << SR;
  12585. }
  12586. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  12587. Sema &SemaRef, DSAStackTy *Stack,
  12588. ValueDecl *VD) {
  12589. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  12590. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  12591. /*FullCheck=*/false);
  12592. }
  12593. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  12594. SourceLocation IdLoc) {
  12595. if (!D || D->isInvalidDecl())
  12596. return;
  12597. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  12598. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  12599. if (auto *VD = dyn_cast<VarDecl>(D)) {
  12600. // Only global variables can be marked as declare target.
  12601. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  12602. !VD->isStaticDataMember())
  12603. return;
  12604. // 2.10.6: threadprivate variable cannot appear in a declare target
  12605. // directive.
  12606. if (DSAStack->isThreadPrivate(VD)) {
  12607. Diag(SL, diag::err_omp_threadprivate_in_target);
  12608. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  12609. return;
  12610. }
  12611. }
  12612. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  12613. D = FTD->getTemplatedDecl();
  12614. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  12615. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  12616. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  12617. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  12618. assert(IdLoc.isValid() && "Source location is expected");
  12619. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  12620. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  12621. return;
  12622. }
  12623. }
  12624. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  12625. // Problem if any with var declared with incomplete type will be reported
  12626. // as normal, so no need to check it here.
  12627. if ((E || !VD->getType()->isIncompleteType()) &&
  12628. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  12629. return;
  12630. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  12631. // Checking declaration inside declare target region.
  12632. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  12633. isa<FunctionTemplateDecl>(D)) {
  12634. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  12635. Context, OMPDeclareTargetDeclAttr::MT_To);
  12636. D->addAttr(A);
  12637. if (ASTMutationListener *ML = Context.getASTMutationListener())
  12638. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  12639. }
  12640. return;
  12641. }
  12642. }
  12643. if (!E)
  12644. return;
  12645. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  12646. }
  12647. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  12648. SourceLocation StartLoc,
  12649. SourceLocation LParenLoc,
  12650. SourceLocation EndLoc) {
  12651. MappableVarListInfo MVLI(VarList);
  12652. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  12653. if (MVLI.ProcessedVarList.empty())
  12654. return nullptr;
  12655. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12656. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12657. MVLI.VarComponents);
  12658. }
  12659. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  12660. SourceLocation StartLoc,
  12661. SourceLocation LParenLoc,
  12662. SourceLocation EndLoc) {
  12663. MappableVarListInfo MVLI(VarList);
  12664. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  12665. if (MVLI.ProcessedVarList.empty())
  12666. return nullptr;
  12667. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12668. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  12669. MVLI.VarComponents);
  12670. }
  12671. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  12672. SourceLocation StartLoc,
  12673. SourceLocation LParenLoc,
  12674. SourceLocation EndLoc) {
  12675. MappableVarListInfo MVLI(VarList);
  12676. SmallVector<Expr *, 8> PrivateCopies;
  12677. SmallVector<Expr *, 8> Inits;
  12678. for (Expr *RefExpr : VarList) {
  12679. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  12680. SourceLocation ELoc;
  12681. SourceRange ERange;
  12682. Expr *SimpleRefExpr = RefExpr;
  12683. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12684. if (Res.second) {
  12685. // It will be analyzed later.
  12686. MVLI.ProcessedVarList.push_back(RefExpr);
  12687. PrivateCopies.push_back(nullptr);
  12688. Inits.push_back(nullptr);
  12689. }
  12690. ValueDecl *D = Res.first;
  12691. if (!D)
  12692. continue;
  12693. QualType Type = D->getType();
  12694. Type = Type.getNonReferenceType().getUnqualifiedType();
  12695. auto *VD = dyn_cast<VarDecl>(D);
  12696. // Item should be a pointer or reference to pointer.
  12697. if (!Type->isPointerType()) {
  12698. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  12699. << 0 << RefExpr->getSourceRange();
  12700. continue;
  12701. }
  12702. // Build the private variable and the expression that refers to it.
  12703. auto VDPrivate =
  12704. buildVarDecl(*this, ELoc, Type, D->getName(),
  12705. D->hasAttrs() ? &D->getAttrs() : nullptr,
  12706. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  12707. if (VDPrivate->isInvalidDecl())
  12708. continue;
  12709. CurContext->addDecl(VDPrivate);
  12710. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  12711. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  12712. // Add temporary variable to initialize the private copy of the pointer.
  12713. VarDecl *VDInit =
  12714. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  12715. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  12716. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  12717. AddInitializerToDecl(VDPrivate,
  12718. DefaultLvalueConversion(VDInitRefExpr).get(),
  12719. /*DirectInit=*/false);
  12720. // If required, build a capture to implement the privatization initialized
  12721. // with the current list item value.
  12722. DeclRefExpr *Ref = nullptr;
  12723. if (!VD)
  12724. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  12725. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  12726. PrivateCopies.push_back(VDPrivateRefExpr);
  12727. Inits.push_back(VDInitRefExpr);
  12728. // We need to add a data sharing attribute for this variable to make sure it
  12729. // is correctly captured. A variable that shows up in a use_device_ptr has
  12730. // similar properties of a first private variable.
  12731. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  12732. // Create a mappable component for the list item. List items in this clause
  12733. // only need a component.
  12734. MVLI.VarBaseDeclarations.push_back(D);
  12735. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12736. MVLI.VarComponents.back().push_back(
  12737. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  12738. }
  12739. if (MVLI.ProcessedVarList.empty())
  12740. return nullptr;
  12741. return OMPUseDevicePtrClause::Create(
  12742. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12743. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12744. }
  12745. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  12746. SourceLocation StartLoc,
  12747. SourceLocation LParenLoc,
  12748. SourceLocation EndLoc) {
  12749. MappableVarListInfo MVLI(VarList);
  12750. for (Expr *RefExpr : VarList) {
  12751. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  12752. SourceLocation ELoc;
  12753. SourceRange ERange;
  12754. Expr *SimpleRefExpr = RefExpr;
  12755. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  12756. if (Res.second) {
  12757. // It will be analyzed later.
  12758. MVLI.ProcessedVarList.push_back(RefExpr);
  12759. }
  12760. ValueDecl *D = Res.first;
  12761. if (!D)
  12762. continue;
  12763. QualType Type = D->getType();
  12764. // item should be a pointer or array or reference to pointer or array
  12765. if (!Type.getNonReferenceType()->isPointerType() &&
  12766. !Type.getNonReferenceType()->isArrayType()) {
  12767. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  12768. << 0 << RefExpr->getSourceRange();
  12769. continue;
  12770. }
  12771. // Check if the declaration in the clause does not show up in any data
  12772. // sharing attribute.
  12773. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  12774. if (isOpenMPPrivate(DVar.CKind)) {
  12775. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12776. << getOpenMPClauseName(DVar.CKind)
  12777. << getOpenMPClauseName(OMPC_is_device_ptr)
  12778. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  12779. reportOriginalDsa(*this, DSAStack, D, DVar);
  12780. continue;
  12781. }
  12782. const Expr *ConflictExpr;
  12783. if (DSAStack->checkMappableExprComponentListsForDecl(
  12784. D, /*CurrentRegionOnly=*/true,
  12785. [&ConflictExpr](
  12786. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  12787. OpenMPClauseKind) -> bool {
  12788. ConflictExpr = R.front().getAssociatedExpression();
  12789. return true;
  12790. })) {
  12791. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  12792. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  12793. << ConflictExpr->getSourceRange();
  12794. continue;
  12795. }
  12796. // Store the components in the stack so that they can be used to check
  12797. // against other clauses later on.
  12798. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  12799. DSAStack->addMappableExpressionComponents(
  12800. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  12801. // Record the expression we've just processed.
  12802. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  12803. // Create a mappable component for the list item. List items in this clause
  12804. // only need a component. We use a null declaration to signal fields in
  12805. // 'this'.
  12806. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  12807. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  12808. "Unexpected device pointer expression!");
  12809. MVLI.VarBaseDeclarations.push_back(
  12810. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  12811. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12812. MVLI.VarComponents.back().push_back(MC);
  12813. }
  12814. if (MVLI.ProcessedVarList.empty())
  12815. return nullptr;
  12816. return OMPIsDevicePtrClause::Create(
  12817. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  12818. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  12819. }