SemaOpenMP.cpp 509 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static Expr *CheckMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind);
  39. namespace {
  40. /// \brief Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
  45. };
  46. /// Attributes of the defaultmap clause.
  47. enum DefaultMapAttributes {
  48. DMA_unspecified, /// Default mapping is not specified.
  49. DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
  50. };
  51. /// \brief Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy final {
  54. public:
  55. struct DSAVarData final {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
  63. DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
  64. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  65. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  66. };
  67. typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
  68. OperatorOffsetTy;
  69. private:
  70. struct DSAInfo final {
  71. OpenMPClauseKind Attributes = OMPC_unknown;
  72. /// Pointer to a reference expression and a flag which shows that the
  73. /// variable is marked as lastprivate(true) or not (false).
  74. llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
  75. DeclRefExpr *PrivateCopy = nullptr;
  76. };
  77. typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
  78. typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
  79. typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
  80. typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
  81. /// Struct that associates a component with the clause kind where they are
  82. /// found.
  83. struct MappedExprComponentTy {
  84. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  85. OpenMPClauseKind Kind = OMPC_unknown;
  86. };
  87. typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
  88. MappedExprComponentsTy;
  89. typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
  90. CriticalsWithHintsTy;
  91. typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
  92. DoacrossDependMapTy;
  93. struct ReductionData {
  94. typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
  95. SourceRange ReductionRange;
  96. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  97. ReductionData() = default;
  98. void set(BinaryOperatorKind BO, SourceRange RR) {
  99. ReductionRange = RR;
  100. ReductionOp = BO;
  101. }
  102. void set(const Expr *RefExpr, SourceRange RR) {
  103. ReductionRange = RR;
  104. ReductionOp = RefExpr;
  105. }
  106. };
  107. typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
  108. struct SharingMapTy final {
  109. DeclSAMapTy SharingMap;
  110. DeclReductionMapTy ReductionMap;
  111. AlignedMapTy AlignedMap;
  112. MappedExprComponentsTy MappedExprComponents;
  113. LoopControlVariablesMapTy LCVMap;
  114. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  115. SourceLocation DefaultAttrLoc;
  116. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  117. SourceLocation DefaultMapAttrLoc;
  118. OpenMPDirectiveKind Directive = OMPD_unknown;
  119. DeclarationNameInfo DirectiveName;
  120. Scope *CurScope = nullptr;
  121. SourceLocation ConstructLoc;
  122. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  123. /// get the data (loop counters etc.) about enclosing loop-based construct.
  124. /// This data is required during codegen.
  125. DoacrossDependMapTy DoacrossDepends;
  126. /// \brief first argument (Expr *) contains optional argument of the
  127. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  128. /// clause, false otherwise.
  129. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
  130. bool NowaitRegion = false;
  131. bool CancelRegion = false;
  132. unsigned AssociatedLoops = 1;
  133. SourceLocation InnerTeamsRegionLoc;
  134. /// Reference to the taskgroup task_reduction reference expression.
  135. Expr *TaskgroupReductionRef = nullptr;
  136. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  137. Scope *CurScope, SourceLocation Loc)
  138. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  139. ConstructLoc(Loc) {}
  140. SharingMapTy() = default;
  141. };
  142. typedef SmallVector<SharingMapTy, 4> StackTy;
  143. /// \brief Stack of used declaration and their data-sharing attributes.
  144. DeclSAMapTy Threadprivates;
  145. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  146. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  147. /// \brief true, if check for DSA must be from parent directive, false, if
  148. /// from current directive.
  149. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  150. Sema &SemaRef;
  151. bool ForceCapturing = false;
  152. CriticalsWithHintsTy Criticals;
  153. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  154. DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
  155. /// \brief Checks if the variable is a local for OpenMP region.
  156. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  157. bool isStackEmpty() const {
  158. return Stack.empty() ||
  159. Stack.back().second != CurrentNonCapturingFunctionScope ||
  160. Stack.back().first.empty();
  161. }
  162. public:
  163. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  164. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  165. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  166. bool isForceVarCapturing() const { return ForceCapturing; }
  167. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  168. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  169. Scope *CurScope, SourceLocation Loc) {
  170. if (Stack.empty() ||
  171. Stack.back().second != CurrentNonCapturingFunctionScope)
  172. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  173. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  174. Stack.back().first.back().DefaultAttrLoc = Loc;
  175. }
  176. void pop() {
  177. assert(!Stack.back().first.empty() &&
  178. "Data-sharing attributes stack is empty!");
  179. Stack.back().first.pop_back();
  180. }
  181. /// Start new OpenMP region stack in new non-capturing function.
  182. void pushFunction() {
  183. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  184. assert(!isa<CapturingScopeInfo>(CurFnScope));
  185. CurrentNonCapturingFunctionScope = CurFnScope;
  186. }
  187. /// Pop region stack for non-capturing function.
  188. void popFunction(const FunctionScopeInfo *OldFSI) {
  189. if (!Stack.empty() && Stack.back().second == OldFSI) {
  190. assert(Stack.back().first.empty());
  191. Stack.pop_back();
  192. }
  193. CurrentNonCapturingFunctionScope = nullptr;
  194. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  195. if (!isa<CapturingScopeInfo>(FSI)) {
  196. CurrentNonCapturingFunctionScope = FSI;
  197. break;
  198. }
  199. }
  200. }
  201. void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
  202. Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
  203. }
  204. const std::pair<OMPCriticalDirective *, llvm::APSInt>
  205. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  206. auto I = Criticals.find(Name.getAsString());
  207. if (I != Criticals.end())
  208. return I->second;
  209. return std::make_pair(nullptr, llvm::APSInt());
  210. }
  211. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  212. /// add it and return NULL; otherwise return previous occurrence's expression
  213. /// for diagnostics.
  214. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
  215. /// \brief Register specified variable as loop control variable.
  216. void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
  217. /// \brief Check if the specified variable is a loop control variable for
  218. /// current region.
  219. /// \return The index of the loop control variable in the list of associated
  220. /// for-loops (from outer to inner).
  221. LCDeclInfo isLoopControlVariable(ValueDecl *D);
  222. /// \brief Check if the specified variable is a loop control variable for
  223. /// parent region.
  224. /// \return The index of the loop control variable in the list of associated
  225. /// for-loops (from outer to inner).
  226. LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
  227. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  228. /// parent directive.
  229. ValueDecl *getParentLoopControlVariable(unsigned I);
  230. /// \brief Adds explicit data sharing attribute to the specified declaration.
  231. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  232. DeclRefExpr *PrivateCopy = nullptr);
  233. /// Adds additional information for the reduction items with the reduction id
  234. /// represented as an operator.
  235. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  236. BinaryOperatorKind BOK);
  237. /// Adds additional information for the reduction items with the reduction id
  238. /// represented as reduction identifier.
  239. void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  240. const Expr *ReductionRef);
  241. /// Returns the location and reduction operation from the innermost parent
  242. /// region for the given \p D.
  243. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  244. BinaryOperatorKind &BOK,
  245. Expr *&TaskgroupDescriptor);
  246. /// Returns the location and reduction operation from the innermost parent
  247. /// region for the given \p D.
  248. DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  249. const Expr *&ReductionRef,
  250. Expr *&TaskgroupDescriptor);
  251. /// Return reduction reference expression for the current taskgroup.
  252. Expr *getTaskgroupReductionRef() const {
  253. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  254. "taskgroup reference expression requested for non taskgroup "
  255. "directive.");
  256. return Stack.back().first.back().TaskgroupReductionRef;
  257. }
  258. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  259. /// descriptor variable at the \p Level of OpenMP regions.
  260. bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
  261. return Stack.back().first[Level].TaskgroupReductionRef &&
  262. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  263. ->getDecl() == VD;
  264. }
  265. /// \brief Returns data sharing attributes from top of the stack for the
  266. /// specified declaration.
  267. DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  268. /// \brief Returns data-sharing attributes for the specified declaration.
  269. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
  270. /// \brief Checks if the specified variables has data-sharing attributes which
  271. /// match specified \a CPred predicate in any directive which matches \a DPred
  272. /// predicate.
  273. DSAVarData hasDSA(ValueDecl *D,
  274. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  275. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  276. bool FromParent);
  277. /// \brief Checks if the specified variables has data-sharing attributes which
  278. /// match specified \a CPred predicate in any innermost directive which
  279. /// matches \a DPred predicate.
  280. DSAVarData
  281. hasInnermostDSA(ValueDecl *D,
  282. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  283. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  284. bool FromParent);
  285. /// \brief Checks if the specified variables has explicit data-sharing
  286. /// attributes which match specified \a CPred predicate at the specified
  287. /// OpenMP region.
  288. bool hasExplicitDSA(ValueDecl *D,
  289. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  290. unsigned Level, bool NotLastprivate = false);
  291. /// \brief Returns true if the directive at level \Level matches in the
  292. /// specified \a DPred predicate.
  293. bool hasExplicitDirective(
  294. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  295. unsigned Level);
  296. /// \brief Finds a directive which matches specified \a DPred predicate.
  297. bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
  298. const DeclarationNameInfo &,
  299. SourceLocation)> &DPred,
  300. bool FromParent);
  301. /// \brief Returns currently analyzed directive.
  302. OpenMPDirectiveKind getCurrentDirective() const {
  303. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  304. }
  305. /// \brief Returns parent directive.
  306. OpenMPDirectiveKind getParentDirective() const {
  307. if (isStackEmpty() || Stack.back().first.size() == 1)
  308. return OMPD_unknown;
  309. return std::next(Stack.back().first.rbegin())->Directive;
  310. }
  311. /// \brief Set default data sharing attribute to none.
  312. void setDefaultDSANone(SourceLocation Loc) {
  313. assert(!isStackEmpty());
  314. Stack.back().first.back().DefaultAttr = DSA_none;
  315. Stack.back().first.back().DefaultAttrLoc = Loc;
  316. }
  317. /// \brief Set default data sharing attribute to shared.
  318. void setDefaultDSAShared(SourceLocation Loc) {
  319. assert(!isStackEmpty());
  320. Stack.back().first.back().DefaultAttr = DSA_shared;
  321. Stack.back().first.back().DefaultAttrLoc = Loc;
  322. }
  323. /// Set default data mapping attribute to 'tofrom:scalar'.
  324. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  325. assert(!isStackEmpty());
  326. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  327. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  328. }
  329. DefaultDataSharingAttributes getDefaultDSA() const {
  330. return isStackEmpty() ? DSA_unspecified
  331. : Stack.back().first.back().DefaultAttr;
  332. }
  333. SourceLocation getDefaultDSALocation() const {
  334. return isStackEmpty() ? SourceLocation()
  335. : Stack.back().first.back().DefaultAttrLoc;
  336. }
  337. DefaultMapAttributes getDefaultDMA() const {
  338. return isStackEmpty() ? DMA_unspecified
  339. : Stack.back().first.back().DefaultMapAttr;
  340. }
  341. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  342. return Stack.back().first[Level].DefaultMapAttr;
  343. }
  344. SourceLocation getDefaultDMALocation() const {
  345. return isStackEmpty() ? SourceLocation()
  346. : Stack.back().first.back().DefaultMapAttrLoc;
  347. }
  348. /// \brief Checks if the specified variable is a threadprivate.
  349. bool isThreadPrivate(VarDecl *D) {
  350. DSAVarData DVar = getTopDSA(D, false);
  351. return isOpenMPThreadPrivate(DVar.CKind);
  352. }
  353. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  354. void setOrderedRegion(bool IsOrdered, Expr *Param) {
  355. assert(!isStackEmpty());
  356. Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
  357. Stack.back().first.back().OrderedRegion.setPointer(Param);
  358. }
  359. /// \brief Returns true, if parent region is ordered (has associated
  360. /// 'ordered' clause), false - otherwise.
  361. bool isParentOrderedRegion() const {
  362. if (isStackEmpty() || Stack.back().first.size() == 1)
  363. return false;
  364. return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
  365. }
  366. /// \brief Returns optional parameter for the ordered region.
  367. Expr *getParentOrderedRegionParam() const {
  368. if (isStackEmpty() || Stack.back().first.size() == 1)
  369. return nullptr;
  370. return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
  371. }
  372. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  373. void setNowaitRegion(bool IsNowait = true) {
  374. assert(!isStackEmpty());
  375. Stack.back().first.back().NowaitRegion = IsNowait;
  376. }
  377. /// \brief Returns true, if parent region is nowait (has associated
  378. /// 'nowait' clause), false - otherwise.
  379. bool isParentNowaitRegion() const {
  380. if (isStackEmpty() || Stack.back().first.size() == 1)
  381. return false;
  382. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  383. }
  384. /// \brief Marks parent region as cancel region.
  385. void setParentCancelRegion(bool Cancel = true) {
  386. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  387. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  388. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  389. }
  390. }
  391. /// \brief Return true if current region has inner cancel construct.
  392. bool isCancelRegion() const {
  393. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  394. }
  395. /// \brief Set collapse value for the region.
  396. void setAssociatedLoops(unsigned Val) {
  397. assert(!isStackEmpty());
  398. Stack.back().first.back().AssociatedLoops = Val;
  399. }
  400. /// \brief Return collapse value for region.
  401. unsigned getAssociatedLoops() const {
  402. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  403. }
  404. /// \brief Marks current target region as one with closely nested teams
  405. /// region.
  406. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  407. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  408. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  409. TeamsRegionLoc;
  410. }
  411. }
  412. /// \brief Returns true, if current region has closely nested teams region.
  413. bool hasInnerTeamsRegion() const {
  414. return getInnerTeamsRegionLoc().isValid();
  415. }
  416. /// \brief Returns location of the nested teams region (if any).
  417. SourceLocation getInnerTeamsRegionLoc() const {
  418. return isStackEmpty() ? SourceLocation()
  419. : Stack.back().first.back().InnerTeamsRegionLoc;
  420. }
  421. Scope *getCurScope() const {
  422. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  423. }
  424. Scope *getCurScope() {
  425. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  426. }
  427. SourceLocation getConstructLoc() {
  428. return isStackEmpty() ? SourceLocation()
  429. : Stack.back().first.back().ConstructLoc;
  430. }
  431. /// Do the check specified in \a Check to all component lists and return true
  432. /// if any issue is found.
  433. bool checkMappableExprComponentListsForDecl(
  434. ValueDecl *VD, bool CurrentRegionOnly,
  435. const llvm::function_ref<
  436. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  437. OpenMPClauseKind)> &Check) {
  438. if (isStackEmpty())
  439. return false;
  440. auto SI = Stack.back().first.rbegin();
  441. auto SE = Stack.back().first.rend();
  442. if (SI == SE)
  443. return false;
  444. if (CurrentRegionOnly) {
  445. SE = std::next(SI);
  446. } else {
  447. ++SI;
  448. }
  449. for (; SI != SE; ++SI) {
  450. auto MI = SI->MappedExprComponents.find(VD);
  451. if (MI != SI->MappedExprComponents.end())
  452. for (auto &L : MI->second.Components)
  453. if (Check(L, MI->second.Kind))
  454. return true;
  455. }
  456. return false;
  457. }
  458. /// Do the check specified in \a Check to all component lists at a given level
  459. /// and return true if any issue is found.
  460. bool checkMappableExprComponentListsForDeclAtLevel(
  461. ValueDecl *VD, unsigned Level,
  462. const llvm::function_ref<
  463. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  464. OpenMPClauseKind)> &Check) {
  465. if (isStackEmpty())
  466. return false;
  467. auto StartI = Stack.back().first.begin();
  468. auto EndI = Stack.back().first.end();
  469. if (std::distance(StartI, EndI) <= (int)Level)
  470. return false;
  471. std::advance(StartI, Level);
  472. auto MI = StartI->MappedExprComponents.find(VD);
  473. if (MI != StartI->MappedExprComponents.end())
  474. for (auto &L : MI->second.Components)
  475. if (Check(L, MI->second.Kind))
  476. return true;
  477. return false;
  478. }
  479. /// Create a new mappable expression component list associated with a given
  480. /// declaration and initialize it with the provided list of components.
  481. void addMappableExpressionComponents(
  482. ValueDecl *VD,
  483. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  484. OpenMPClauseKind WhereFoundClauseKind) {
  485. assert(!isStackEmpty() &&
  486. "Not expecting to retrieve components from a empty stack!");
  487. auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
  488. // Create new entry and append the new components there.
  489. MEC.Components.resize(MEC.Components.size() + 1);
  490. MEC.Components.back().append(Components.begin(), Components.end());
  491. MEC.Kind = WhereFoundClauseKind;
  492. }
  493. unsigned getNestingLevel() const {
  494. assert(!isStackEmpty());
  495. return Stack.back().first.size() - 1;
  496. }
  497. void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
  498. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  499. auto &StackElem = *std::next(Stack.back().first.rbegin());
  500. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  501. StackElem.DoacrossDepends.insert({C, OpsOffs});
  502. }
  503. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  504. getDoacrossDependClauses() const {
  505. assert(!isStackEmpty());
  506. auto &StackElem = Stack.back().first.back();
  507. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  508. auto &Ref = StackElem.DoacrossDepends;
  509. return llvm::make_range(Ref.begin(), Ref.end());
  510. }
  511. return llvm::make_range(StackElem.DoacrossDepends.end(),
  512. StackElem.DoacrossDepends.end());
  513. }
  514. };
  515. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  516. return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
  517. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
  518. }
  519. } // namespace
  520. static Expr *getExprAsWritten(Expr *E) {
  521. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  522. E = ExprTemp->getSubExpr();
  523. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  524. E = MTE->GetTemporaryExpr();
  525. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  526. E = Binder->getSubExpr();
  527. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  528. E = ICE->getSubExprAsWritten();
  529. return E->IgnoreParens();
  530. }
  531. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  532. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  533. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  534. D = ME->getMemberDecl();
  535. auto *VD = dyn_cast<VarDecl>(D);
  536. auto *FD = dyn_cast<FieldDecl>(D);
  537. if (VD != nullptr) {
  538. VD = VD->getCanonicalDecl();
  539. D = VD;
  540. } else {
  541. assert(FD);
  542. FD = FD->getCanonicalDecl();
  543. D = FD;
  544. }
  545. return D;
  546. }
  547. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
  548. ValueDecl *D) {
  549. D = getCanonicalDecl(D);
  550. auto *VD = dyn_cast<VarDecl>(D);
  551. auto *FD = dyn_cast<FieldDecl>(D);
  552. DSAVarData DVar;
  553. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  554. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  555. // in a region but not in construct]
  556. // File-scope or namespace-scope variables referenced in called routines
  557. // in the region are shared unless they appear in a threadprivate
  558. // directive.
  559. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  560. DVar.CKind = OMPC_shared;
  561. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  562. // in a region but not in construct]
  563. // Variables with static storage duration that are declared in called
  564. // routines in the region are shared.
  565. if (VD && VD->hasGlobalStorage())
  566. DVar.CKind = OMPC_shared;
  567. // Non-static data members are shared by default.
  568. if (FD)
  569. DVar.CKind = OMPC_shared;
  570. return DVar;
  571. }
  572. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  573. // in a Construct, C/C++, predetermined, p.1]
  574. // Variables with automatic storage duration that are declared in a scope
  575. // inside the construct are private.
  576. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  577. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  578. DVar.CKind = OMPC_private;
  579. return DVar;
  580. }
  581. DVar.DKind = Iter->Directive;
  582. // Explicitly specified attributes and local variables with predetermined
  583. // attributes.
  584. if (Iter->SharingMap.count(D)) {
  585. DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
  586. DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
  587. DVar.CKind = Iter->SharingMap[D].Attributes;
  588. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  589. return DVar;
  590. }
  591. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  592. // in a Construct, C/C++, implicitly determined, p.1]
  593. // In a parallel or task construct, the data-sharing attributes of these
  594. // variables are determined by the default clause, if present.
  595. switch (Iter->DefaultAttr) {
  596. case DSA_shared:
  597. DVar.CKind = OMPC_shared;
  598. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  599. return DVar;
  600. case DSA_none:
  601. return DVar;
  602. case DSA_unspecified:
  603. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  604. // in a Construct, implicitly determined, p.2]
  605. // In a parallel construct, if no default clause is present, these
  606. // variables are shared.
  607. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  608. if (isOpenMPParallelDirective(DVar.DKind) ||
  609. isOpenMPTeamsDirective(DVar.DKind)) {
  610. DVar.CKind = OMPC_shared;
  611. return DVar;
  612. }
  613. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  614. // in a Construct, implicitly determined, p.4]
  615. // In a task construct, if no default clause is present, a variable that in
  616. // the enclosing context is determined to be shared by all implicit tasks
  617. // bound to the current team is shared.
  618. if (isOpenMPTaskingDirective(DVar.DKind)) {
  619. DSAVarData DVarTemp;
  620. auto I = Iter, E = Stack.back().first.rend();
  621. do {
  622. ++I;
  623. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  624. // Referenced in a Construct, implicitly determined, p.6]
  625. // In a task construct, if no default clause is present, a variable
  626. // whose data-sharing attribute is not determined by the rules above is
  627. // firstprivate.
  628. DVarTemp = getDSA(I, D);
  629. if (DVarTemp.CKind != OMPC_shared) {
  630. DVar.RefExpr = nullptr;
  631. DVar.CKind = OMPC_firstprivate;
  632. return DVar;
  633. }
  634. } while (I != E && !isParallelOrTaskRegion(I->Directive));
  635. DVar.CKind =
  636. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  637. return DVar;
  638. }
  639. }
  640. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  641. // in a Construct, implicitly determined, p.3]
  642. // For constructs other than task, if no default clause is present, these
  643. // variables inherit their data-sharing attributes from the enclosing
  644. // context.
  645. return getDSA(++Iter, D);
  646. }
  647. Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
  648. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  649. D = getCanonicalDecl(D);
  650. auto &StackElem = Stack.back().first.back();
  651. auto It = StackElem.AlignedMap.find(D);
  652. if (It == StackElem.AlignedMap.end()) {
  653. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  654. StackElem.AlignedMap[D] = NewDE;
  655. return nullptr;
  656. } else {
  657. assert(It->second && "Unexpected nullptr expr in the aligned map");
  658. return It->second;
  659. }
  660. return nullptr;
  661. }
  662. void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
  663. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  664. D = getCanonicalDecl(D);
  665. auto &StackElem = Stack.back().first.back();
  666. StackElem.LCVMap.insert(
  667. {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
  668. }
  669. DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
  670. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  671. D = getCanonicalDecl(D);
  672. auto &StackElem = Stack.back().first.back();
  673. auto It = StackElem.LCVMap.find(D);
  674. if (It != StackElem.LCVMap.end())
  675. return It->second;
  676. return {0, nullptr};
  677. }
  678. DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
  679. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  680. "Data-sharing attributes stack is empty");
  681. D = getCanonicalDecl(D);
  682. auto &StackElem = *std::next(Stack.back().first.rbegin());
  683. auto It = StackElem.LCVMap.find(D);
  684. if (It != StackElem.LCVMap.end())
  685. return It->second;
  686. return {0, nullptr};
  687. }
  688. ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
  689. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  690. "Data-sharing attributes stack is empty");
  691. auto &StackElem = *std::next(Stack.back().first.rbegin());
  692. if (StackElem.LCVMap.size() < I)
  693. return nullptr;
  694. for (auto &Pair : StackElem.LCVMap)
  695. if (Pair.second.first == I)
  696. return Pair.first;
  697. return nullptr;
  698. }
  699. void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
  700. DeclRefExpr *PrivateCopy) {
  701. D = getCanonicalDecl(D);
  702. if (A == OMPC_threadprivate) {
  703. auto &Data = Threadprivates[D];
  704. Data.Attributes = A;
  705. Data.RefExpr.setPointer(E);
  706. Data.PrivateCopy = nullptr;
  707. } else {
  708. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  709. auto &Data = Stack.back().first.back().SharingMap[D];
  710. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  711. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  712. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  713. (isLoopControlVariable(D).first && A == OMPC_private));
  714. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  715. Data.RefExpr.setInt(/*IntVal=*/true);
  716. return;
  717. }
  718. const bool IsLastprivate =
  719. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  720. Data.Attributes = A;
  721. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  722. Data.PrivateCopy = PrivateCopy;
  723. if (PrivateCopy) {
  724. auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  725. Data.Attributes = A;
  726. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  727. Data.PrivateCopy = nullptr;
  728. }
  729. }
  730. }
  731. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  732. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  733. StringRef Name, const AttrVec *Attrs = nullptr) {
  734. DeclContext *DC = SemaRef.CurContext;
  735. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  736. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  737. VarDecl *Decl =
  738. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  739. if (Attrs) {
  740. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  741. I != E; ++I)
  742. Decl->addAttr(*I);
  743. }
  744. Decl->setImplicit();
  745. return Decl;
  746. }
  747. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  748. SourceLocation Loc,
  749. bool RefersToCapture = false) {
  750. D->setReferenced();
  751. D->markUsed(S.Context);
  752. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  753. SourceLocation(), D, RefersToCapture, Loc, Ty,
  754. VK_LValue);
  755. }
  756. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  757. BinaryOperatorKind BOK) {
  758. D = getCanonicalDecl(D);
  759. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  760. assert(
  761. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  762. "Additional reduction info may be specified only for reduction items.");
  763. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  764. assert(ReductionData.ReductionRange.isInvalid() &&
  765. Stack.back().first.back().Directive == OMPD_taskgroup &&
  766. "Additional reduction info may be specified only once for reduction "
  767. "items.");
  768. ReductionData.set(BOK, SR);
  769. Expr *&TaskgroupReductionRef =
  770. Stack.back().first.back().TaskgroupReductionRef;
  771. if (!TaskgroupReductionRef) {
  772. auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
  773. SemaRef.Context.VoidPtrTy, ".task_red.");
  774. TaskgroupReductionRef =
  775. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  776. }
  777. }
  778. void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
  779. const Expr *ReductionRef) {
  780. D = getCanonicalDecl(D);
  781. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  782. assert(
  783. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  784. "Additional reduction info may be specified only for reduction items.");
  785. auto &ReductionData = Stack.back().first.back().ReductionMap[D];
  786. assert(ReductionData.ReductionRange.isInvalid() &&
  787. Stack.back().first.back().Directive == OMPD_taskgroup &&
  788. "Additional reduction info may be specified only once for reduction "
  789. "items.");
  790. ReductionData.set(ReductionRef, SR);
  791. Expr *&TaskgroupReductionRef =
  792. Stack.back().first.back().TaskgroupReductionRef;
  793. if (!TaskgroupReductionRef) {
  794. auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
  795. ".task_red.");
  796. TaskgroupReductionRef =
  797. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  798. }
  799. }
  800. DSAStackTy::DSAVarData
  801. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  802. BinaryOperatorKind &BOK,
  803. Expr *&TaskgroupDescriptor) {
  804. D = getCanonicalDecl(D);
  805. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  806. if (Stack.back().first.empty())
  807. return DSAVarData();
  808. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  809. E = Stack.back().first.rend();
  810. I != E; std::advance(I, 1)) {
  811. auto &Data = I->SharingMap[D];
  812. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  813. continue;
  814. auto &ReductionData = I->ReductionMap[D];
  815. if (!ReductionData.ReductionOp ||
  816. ReductionData.ReductionOp.is<const Expr *>())
  817. return DSAVarData();
  818. SR = ReductionData.ReductionRange;
  819. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  820. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  821. "expression for the descriptor is not "
  822. "set.");
  823. TaskgroupDescriptor = I->TaskgroupReductionRef;
  824. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  825. Data.PrivateCopy, I->DefaultAttrLoc);
  826. }
  827. return DSAVarData();
  828. }
  829. DSAStackTy::DSAVarData
  830. DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
  831. const Expr *&ReductionRef,
  832. Expr *&TaskgroupDescriptor) {
  833. D = getCanonicalDecl(D);
  834. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  835. if (Stack.back().first.empty())
  836. return DSAVarData();
  837. for (auto I = std::next(Stack.back().first.rbegin(), 1),
  838. E = Stack.back().first.rend();
  839. I != E; std::advance(I, 1)) {
  840. auto &Data = I->SharingMap[D];
  841. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  842. continue;
  843. auto &ReductionData = I->ReductionMap[D];
  844. if (!ReductionData.ReductionOp ||
  845. !ReductionData.ReductionOp.is<const Expr *>())
  846. return DSAVarData();
  847. SR = ReductionData.ReductionRange;
  848. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  849. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  850. "expression for the descriptor is not "
  851. "set.");
  852. TaskgroupDescriptor = I->TaskgroupReductionRef;
  853. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  854. Data.PrivateCopy, I->DefaultAttrLoc);
  855. }
  856. return DSAVarData();
  857. }
  858. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  859. D = D->getCanonicalDecl();
  860. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  861. reverse_iterator I = Iter, E = Stack.back().first.rend();
  862. Scope *TopScope = nullptr;
  863. while (I != E && !isParallelOrTaskRegion(I->Directive))
  864. ++I;
  865. if (I == E)
  866. return false;
  867. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  868. Scope *CurScope = getCurScope();
  869. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  870. CurScope = CurScope->getParent();
  871. return CurScope != TopScope;
  872. }
  873. return false;
  874. }
  875. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
  876. D = getCanonicalDecl(D);
  877. DSAVarData DVar;
  878. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  879. // in a Construct, C/C++, predetermined, p.1]
  880. // Variables appearing in threadprivate directives are threadprivate.
  881. auto *VD = dyn_cast<VarDecl>(D);
  882. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  883. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  884. SemaRef.getLangOpts().OpenMPUseTLS &&
  885. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  886. (VD && VD->getStorageClass() == SC_Register &&
  887. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  888. addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  889. D->getLocation()),
  890. OMPC_threadprivate);
  891. }
  892. auto TI = Threadprivates.find(D);
  893. if (TI != Threadprivates.end()) {
  894. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  895. DVar.CKind = OMPC_threadprivate;
  896. return DVar;
  897. } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  898. DVar.RefExpr = buildDeclRefExpr(
  899. SemaRef, VD, D->getType().getNonReferenceType(),
  900. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  901. DVar.CKind = OMPC_threadprivate;
  902. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  903. }
  904. if (isStackEmpty())
  905. // Not in OpenMP execution region and top scope was already checked.
  906. return DVar;
  907. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  908. // in a Construct, C/C++, predetermined, p.4]
  909. // Static data members are shared.
  910. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  911. // in a Construct, C/C++, predetermined, p.7]
  912. // Variables with static storage duration that are declared in a scope
  913. // inside the construct are shared.
  914. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
  915. if (VD && VD->isStaticDataMember()) {
  916. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  917. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  918. return DVar;
  919. DVar.CKind = OMPC_shared;
  920. return DVar;
  921. }
  922. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  923. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  924. Type = SemaRef.getASTContext().getBaseElementType(Type);
  925. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  926. // in a Construct, C/C++, predetermined, p.6]
  927. // Variables with const qualified type having no mutable member are
  928. // shared.
  929. CXXRecordDecl *RD =
  930. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  931. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  932. if (auto *CTD = CTSD->getSpecializedTemplate())
  933. RD = CTD->getTemplatedDecl();
  934. if (IsConstant &&
  935. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  936. RD->hasMutableFields())) {
  937. // Variables with const-qualified type having no mutable member may be
  938. // listed in a firstprivate clause, even if they are static data members.
  939. DSAVarData DVarTemp = hasDSA(
  940. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
  941. MatchesAlways, FromParent);
  942. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  943. return DVar;
  944. DVar.CKind = OMPC_shared;
  945. return DVar;
  946. }
  947. // Explicitly specified attributes and local variables with predetermined
  948. // attributes.
  949. auto I = Stack.back().first.rbegin();
  950. auto EndI = Stack.back().first.rend();
  951. if (FromParent && I != EndI)
  952. std::advance(I, 1);
  953. if (I->SharingMap.count(D)) {
  954. DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
  955. DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
  956. DVar.CKind = I->SharingMap[D].Attributes;
  957. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  958. DVar.DKind = I->Directive;
  959. }
  960. return DVar;
  961. }
  962. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  963. bool FromParent) {
  964. if (isStackEmpty()) {
  965. StackTy::reverse_iterator I;
  966. return getDSA(I, D);
  967. }
  968. D = getCanonicalDecl(D);
  969. auto StartI = Stack.back().first.rbegin();
  970. auto EndI = Stack.back().first.rend();
  971. if (FromParent && StartI != EndI)
  972. std::advance(StartI, 1);
  973. return getDSA(StartI, D);
  974. }
  975. DSAStackTy::DSAVarData
  976. DSAStackTy::hasDSA(ValueDecl *D,
  977. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  978. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  979. bool FromParent) {
  980. if (isStackEmpty())
  981. return {};
  982. D = getCanonicalDecl(D);
  983. auto I = Stack.back().first.rbegin();
  984. auto EndI = Stack.back().first.rend();
  985. if (FromParent && I != EndI)
  986. std::advance(I, 1);
  987. for (; I != EndI; std::advance(I, 1)) {
  988. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  989. continue;
  990. auto NewI = I;
  991. DSAVarData DVar = getDSA(NewI, D);
  992. if (I == NewI && CPred(DVar.CKind))
  993. return DVar;
  994. }
  995. return {};
  996. }
  997. DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  998. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  999. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1000. bool FromParent) {
  1001. if (isStackEmpty())
  1002. return {};
  1003. D = getCanonicalDecl(D);
  1004. auto StartI = Stack.back().first.rbegin();
  1005. auto EndI = Stack.back().first.rend();
  1006. if (FromParent && StartI != EndI)
  1007. std::advance(StartI, 1);
  1008. if (StartI == EndI || !DPred(StartI->Directive))
  1009. return {};
  1010. auto NewI = StartI;
  1011. DSAVarData DVar = getDSA(NewI, D);
  1012. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1013. }
  1014. bool DSAStackTy::hasExplicitDSA(
  1015. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1016. unsigned Level, bool NotLastprivate) {
  1017. if (CPred(ClauseKindMode))
  1018. return true;
  1019. if (isStackEmpty())
  1020. return false;
  1021. D = getCanonicalDecl(D);
  1022. auto StartI = Stack.back().first.begin();
  1023. auto EndI = Stack.back().first.end();
  1024. if (std::distance(StartI, EndI) <= (int)Level)
  1025. return false;
  1026. std::advance(StartI, Level);
  1027. return (StartI->SharingMap.count(D) > 0) &&
  1028. StartI->SharingMap[D].RefExpr.getPointer() &&
  1029. CPred(StartI->SharingMap[D].Attributes) &&
  1030. (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
  1031. }
  1032. bool DSAStackTy::hasExplicitDirective(
  1033. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1034. unsigned Level) {
  1035. if (isStackEmpty())
  1036. return false;
  1037. auto StartI = Stack.back().first.begin();
  1038. auto EndI = Stack.back().first.end();
  1039. if (std::distance(StartI, EndI) <= (int)Level)
  1040. return false;
  1041. std::advance(StartI, Level);
  1042. return DPred(StartI->Directive);
  1043. }
  1044. bool DSAStackTy::hasDirective(
  1045. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1046. const DeclarationNameInfo &, SourceLocation)>
  1047. &DPred,
  1048. bool FromParent) {
  1049. // We look only in the enclosing region.
  1050. if (isStackEmpty())
  1051. return false;
  1052. auto StartI = std::next(Stack.back().first.rbegin());
  1053. auto EndI = Stack.back().first.rend();
  1054. if (FromParent && StartI != EndI)
  1055. StartI = std::next(StartI);
  1056. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1057. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1058. return true;
  1059. }
  1060. return false;
  1061. }
  1062. void Sema::InitDataSharingAttributesStack() {
  1063. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1064. }
  1065. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1066. void Sema::pushOpenMPFunctionRegion() {
  1067. DSAStack->pushFunction();
  1068. }
  1069. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1070. DSAStack->popFunction(OldFSI);
  1071. }
  1072. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
  1073. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1074. auto &Ctx = getASTContext();
  1075. bool IsByRef = true;
  1076. // Find the directive that is associated with the provided scope.
  1077. D = cast<ValueDecl>(D->getCanonicalDecl());
  1078. auto Ty = D->getType();
  1079. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1080. // This table summarizes how a given variable should be passed to the device
  1081. // given its type and the clauses where it appears. This table is based on
  1082. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1083. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1084. //
  1085. // =========================================================================
  1086. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1087. // | |(tofrom:scalar)| | pvt | | | |
  1088. // =========================================================================
  1089. // | scl | | | | - | | bycopy|
  1090. // | scl | | - | x | - | - | bycopy|
  1091. // | scl | | x | - | - | - | null |
  1092. // | scl | x | | | - | | byref |
  1093. // | scl | x | - | x | - | - | bycopy|
  1094. // | scl | x | x | - | - | - | null |
  1095. // | scl | | - | - | - | x | byref |
  1096. // | scl | x | - | - | - | x | byref |
  1097. //
  1098. // | agg | n.a. | | | - | | byref |
  1099. // | agg | n.a. | - | x | - | - | byref |
  1100. // | agg | n.a. | x | - | - | - | null |
  1101. // | agg | n.a. | - | - | - | x | byref |
  1102. // | agg | n.a. | - | - | - | x[] | byref |
  1103. //
  1104. // | ptr | n.a. | | | - | | bycopy|
  1105. // | ptr | n.a. | - | x | - | - | bycopy|
  1106. // | ptr | n.a. | x | - | - | - | null |
  1107. // | ptr | n.a. | - | - | - | x | byref |
  1108. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1109. // | ptr | n.a. | - | - | x | | bycopy|
  1110. // | ptr | n.a. | - | - | x | x | bycopy|
  1111. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1112. // =========================================================================
  1113. // Legend:
  1114. // scl - scalar
  1115. // ptr - pointer
  1116. // agg - aggregate
  1117. // x - applies
  1118. // - - invalid in this combination
  1119. // [] - mapped with an array section
  1120. // byref - should be mapped by reference
  1121. // byval - should be mapped by value
  1122. // null - initialize a local variable to null on the device
  1123. //
  1124. // Observations:
  1125. // - All scalar declarations that show up in a map clause have to be passed
  1126. // by reference, because they may have been mapped in the enclosing data
  1127. // environment.
  1128. // - If the scalar value does not fit the size of uintptr, it has to be
  1129. // passed by reference, regardless the result in the table above.
  1130. // - For pointers mapped by value that have either an implicit map or an
  1131. // array section, the runtime library may pass the NULL value to the
  1132. // device instead of the value passed to it by the compiler.
  1133. if (Ty->isReferenceType())
  1134. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1135. // Locate map clauses and see if the variable being captured is referred to
  1136. // in any of those clauses. Here we only care about variables, not fields,
  1137. // because fields are part of aggregates.
  1138. bool IsVariableUsedInMapClause = false;
  1139. bool IsVariableAssociatedWithSection = false;
  1140. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1141. D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1142. MapExprComponents,
  1143. OpenMPClauseKind WhereFoundClauseKind) {
  1144. // Only the map clause information influences how a variable is
  1145. // captured. E.g. is_device_ptr does not require changing the default
  1146. // behavior.
  1147. if (WhereFoundClauseKind != OMPC_map)
  1148. return false;
  1149. auto EI = MapExprComponents.rbegin();
  1150. auto EE = MapExprComponents.rend();
  1151. assert(EI != EE && "Invalid map expression!");
  1152. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1153. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1154. ++EI;
  1155. if (EI == EE)
  1156. return false;
  1157. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1158. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1159. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1160. IsVariableAssociatedWithSection = true;
  1161. // There is nothing more we need to know about this variable.
  1162. return true;
  1163. }
  1164. // Keep looking for more map info.
  1165. return false;
  1166. });
  1167. if (IsVariableUsedInMapClause) {
  1168. // If variable is identified in a map clause it is always captured by
  1169. // reference except if it is a pointer that is dereferenced somehow.
  1170. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1171. } else {
  1172. // By default, all the data that has a scalar type is mapped by copy.
  1173. IsByRef = !Ty->isScalarType() ||
  1174. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
  1175. }
  1176. }
  1177. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1178. IsByRef = !DSAStack->hasExplicitDSA(
  1179. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1180. Level, /*NotLastprivate=*/true);
  1181. }
  1182. // When passing data by copy, we need to make sure it fits the uintptr size
  1183. // and alignment, because the runtime library only deals with uintptr types.
  1184. // If it does not fit the uintptr size, we need to pass the data by reference
  1185. // instead.
  1186. if (!IsByRef &&
  1187. (Ctx.getTypeSizeInChars(Ty) >
  1188. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1189. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1190. IsByRef = true;
  1191. }
  1192. return IsByRef;
  1193. }
  1194. unsigned Sema::getOpenMPNestingLevel() const {
  1195. assert(getLangOpts().OpenMP);
  1196. return DSAStack->getNestingLevel();
  1197. }
  1198. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1199. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1200. !DSAStack->isClauseParsingMode()) ||
  1201. DSAStack->hasDirective(
  1202. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1203. SourceLocation) -> bool {
  1204. return isOpenMPTargetExecutionDirective(K);
  1205. },
  1206. false);
  1207. }
  1208. VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  1209. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1210. D = getCanonicalDecl(D);
  1211. // If we are attempting to capture a global variable in a directive with
  1212. // 'target' we return true so that this global is also mapped to the device.
  1213. //
  1214. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  1215. // then it should not be captured. Therefore, an extra check has to be
  1216. // inserted here once support for 'declare target' is added.
  1217. //
  1218. auto *VD = dyn_cast<VarDecl>(D);
  1219. if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
  1220. return VD;
  1221. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1222. (!DSAStack->isClauseParsingMode() ||
  1223. DSAStack->getParentDirective() != OMPD_unknown)) {
  1224. auto &&Info = DSAStack->isLoopControlVariable(D);
  1225. if (Info.first ||
  1226. (VD && VD->hasLocalStorage() &&
  1227. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1228. (VD && DSAStack->isForceVarCapturing()))
  1229. return VD ? VD : Info.second;
  1230. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1231. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1232. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1233. DVarPrivate = DSAStack->hasDSA(
  1234. D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  1235. DSAStack->isClauseParsingMode());
  1236. if (DVarPrivate.CKind != OMPC_unknown)
  1237. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1238. }
  1239. return nullptr;
  1240. }
  1241. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  1242. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1243. return DSAStack->hasExplicitDSA(
  1244. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
  1245. Level) ||
  1246. // Consider taskgroup reduction descriptor variable a private to avoid
  1247. // possible capture in the region.
  1248. (DSAStack->hasExplicitDirective(
  1249. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1250. Level) &&
  1251. DSAStack->isTaskgroupReductionRef(D, Level));
  1252. }
  1253. void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
  1254. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1255. D = getCanonicalDecl(D);
  1256. OpenMPClauseKind OMPC = OMPC_unknown;
  1257. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1258. const unsigned NewLevel = I - 1;
  1259. if (DSAStack->hasExplicitDSA(D,
  1260. [&OMPC](const OpenMPClauseKind K) {
  1261. if (isOpenMPPrivate(K)) {
  1262. OMPC = K;
  1263. return true;
  1264. }
  1265. return false;
  1266. },
  1267. NewLevel))
  1268. break;
  1269. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1270. D, NewLevel,
  1271. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1272. OpenMPClauseKind) { return true; })) {
  1273. OMPC = OMPC_map;
  1274. break;
  1275. }
  1276. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1277. NewLevel)) {
  1278. OMPC = OMPC_firstprivate;
  1279. break;
  1280. }
  1281. }
  1282. if (OMPC != OMPC_unknown)
  1283. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1284. }
  1285. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  1286. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1287. // Return true if the current level is no longer enclosed in a target region.
  1288. auto *VD = dyn_cast<VarDecl>(D);
  1289. return VD && !VD->hasLocalStorage() &&
  1290. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1291. Level);
  1292. }
  1293. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1294. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1295. const DeclarationNameInfo &DirName,
  1296. Scope *CurScope, SourceLocation Loc) {
  1297. DSAStack->push(DKind, DirName, CurScope, Loc);
  1298. PushExpressionEvaluationContext(
  1299. ExpressionEvaluationContext::PotentiallyEvaluated);
  1300. }
  1301. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1302. DSAStack->setClauseParsingMode(K);
  1303. }
  1304. void Sema::EndOpenMPClause() {
  1305. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1306. }
  1307. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1308. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1309. // A variable of class type (or array thereof) that appears in a lastprivate
  1310. // clause requires an accessible, unambiguous default constructor for the
  1311. // class type, unless the list item is also specified in a firstprivate
  1312. // clause.
  1313. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1314. for (auto *C : D->clauses()) {
  1315. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1316. SmallVector<Expr *, 8> PrivateCopies;
  1317. for (auto *DE : Clause->varlists()) {
  1318. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1319. PrivateCopies.push_back(nullptr);
  1320. continue;
  1321. }
  1322. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1323. VarDecl *VD = cast<VarDecl>(DRE->getDecl());
  1324. QualType Type = VD->getType().getNonReferenceType();
  1325. auto DVar = DSAStack->getTopDSA(VD, false);
  1326. if (DVar.CKind == OMPC_lastprivate) {
  1327. // Generate helper private variable and initialize it with the
  1328. // default value. The address of the original variable is replaced
  1329. // by the address of the new private variable in CodeGen. This new
  1330. // variable is not added to IdResolver, so the code in the OpenMP
  1331. // region uses original variable for proper diagnostics.
  1332. auto *VDPrivate = buildVarDecl(
  1333. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1334. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  1335. ActOnUninitializedDecl(VDPrivate);
  1336. if (VDPrivate->isInvalidDecl())
  1337. continue;
  1338. PrivateCopies.push_back(buildDeclRefExpr(
  1339. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1340. } else {
  1341. // The variable is also a firstprivate, so initialization sequence
  1342. // for private copy is generated already.
  1343. PrivateCopies.push_back(nullptr);
  1344. }
  1345. }
  1346. // Set initializers to private copies if no errors were found.
  1347. if (PrivateCopies.size() == Clause->varlist_size())
  1348. Clause->setPrivateCopies(PrivateCopies);
  1349. }
  1350. }
  1351. }
  1352. DSAStack->pop();
  1353. DiscardCleanupsInEvaluationContext();
  1354. PopExpressionEvaluationContext();
  1355. }
  1356. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1357. Expr *NumIterations, Sema &SemaRef,
  1358. Scope *S, DSAStackTy *Stack);
  1359. namespace {
  1360. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1361. private:
  1362. Sema &SemaRef;
  1363. public:
  1364. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1365. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1366. NamedDecl *ND = Candidate.getCorrectionDecl();
  1367. if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1368. return VD->hasGlobalStorage() &&
  1369. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1370. SemaRef.getCurScope());
  1371. }
  1372. return false;
  1373. }
  1374. };
  1375. class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
  1376. private:
  1377. Sema &SemaRef;
  1378. public:
  1379. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1380. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1381. NamedDecl *ND = Candidate.getCorrectionDecl();
  1382. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1383. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1384. SemaRef.getCurScope());
  1385. }
  1386. return false;
  1387. }
  1388. };
  1389. } // namespace
  1390. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1391. CXXScopeSpec &ScopeSpec,
  1392. const DeclarationNameInfo &Id) {
  1393. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1394. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1395. if (Lookup.isAmbiguous())
  1396. return ExprError();
  1397. VarDecl *VD;
  1398. if (!Lookup.isSingleResult()) {
  1399. if (TypoCorrection Corrected = CorrectTypo(
  1400. Id, LookupOrdinaryName, CurScope, nullptr,
  1401. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1402. diagnoseTypo(Corrected,
  1403. PDiag(Lookup.empty()
  1404. ? diag::err_undeclared_var_use_suggest
  1405. : diag::err_omp_expected_var_arg_suggest)
  1406. << Id.getName());
  1407. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1408. } else {
  1409. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1410. : diag::err_omp_expected_var_arg)
  1411. << Id.getName();
  1412. return ExprError();
  1413. }
  1414. } else {
  1415. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1416. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1417. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1418. return ExprError();
  1419. }
  1420. }
  1421. Lookup.suppressDiagnostics();
  1422. // OpenMP [2.9.2, Syntax, C/C++]
  1423. // Variables must be file-scope, namespace-scope, or static block-scope.
  1424. if (!VD->hasGlobalStorage()) {
  1425. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1426. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1427. bool IsDecl =
  1428. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1429. Diag(VD->getLocation(),
  1430. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1431. << VD;
  1432. return ExprError();
  1433. }
  1434. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1435. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1436. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1437. // A threadprivate directive for file-scope variables must appear outside
  1438. // any definition or declaration.
  1439. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1440. !getCurLexicalContext()->isTranslationUnit()) {
  1441. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1442. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1443. bool IsDecl =
  1444. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1445. Diag(VD->getLocation(),
  1446. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1447. << VD;
  1448. return ExprError();
  1449. }
  1450. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1451. // A threadprivate directive for static class member variables must appear
  1452. // in the class definition, in the same scope in which the member
  1453. // variables are declared.
  1454. if (CanonicalVD->isStaticDataMember() &&
  1455. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1456. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1457. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1458. bool IsDecl =
  1459. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1460. Diag(VD->getLocation(),
  1461. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1462. << VD;
  1463. return ExprError();
  1464. }
  1465. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1466. // A threadprivate directive for namespace-scope variables must appear
  1467. // outside any definition or declaration other than the namespace
  1468. // definition itself.
  1469. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1470. (!getCurLexicalContext()->isFileContext() ||
  1471. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1472. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1473. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1474. bool IsDecl =
  1475. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1476. Diag(VD->getLocation(),
  1477. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1478. << VD;
  1479. return ExprError();
  1480. }
  1481. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1482. // A threadprivate directive for static block-scope variables must appear
  1483. // in the scope of the variable and not in a nested scope.
  1484. if (CanonicalVD->isStaticLocal() && CurScope &&
  1485. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1486. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1487. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1488. bool IsDecl =
  1489. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1490. Diag(VD->getLocation(),
  1491. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1492. << VD;
  1493. return ExprError();
  1494. }
  1495. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1496. // A threadprivate directive must lexically precede all references to any
  1497. // of the variables in its list.
  1498. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1499. Diag(Id.getLoc(), diag::err_omp_var_used)
  1500. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1501. return ExprError();
  1502. }
  1503. QualType ExprType = VD->getType().getNonReferenceType();
  1504. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1505. SourceLocation(), VD,
  1506. /*RefersToEnclosingVariableOrCapture=*/false,
  1507. Id.getLoc(), ExprType, VK_LValue);
  1508. }
  1509. Sema::DeclGroupPtrTy
  1510. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1511. ArrayRef<Expr *> VarList) {
  1512. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1513. CurContext->addDecl(D);
  1514. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1515. }
  1516. return nullptr;
  1517. }
  1518. namespace {
  1519. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1520. Sema &SemaRef;
  1521. public:
  1522. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1523. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1524. if (VD->hasLocalStorage()) {
  1525. SemaRef.Diag(E->getLocStart(),
  1526. diag::err_omp_local_var_in_threadprivate_init)
  1527. << E->getSourceRange();
  1528. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1529. << VD << VD->getSourceRange();
  1530. return true;
  1531. }
  1532. }
  1533. return false;
  1534. }
  1535. bool VisitStmt(const Stmt *S) {
  1536. for (auto Child : S->children()) {
  1537. if (Child && Visit(Child))
  1538. return true;
  1539. }
  1540. return false;
  1541. }
  1542. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1543. };
  1544. } // namespace
  1545. OMPThreadPrivateDecl *
  1546. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1547. SmallVector<Expr *, 8> Vars;
  1548. for (auto &RefExpr : VarList) {
  1549. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1550. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1551. SourceLocation ILoc = DE->getExprLoc();
  1552. // Mark variable as used.
  1553. VD->setReferenced();
  1554. VD->markUsed(Context);
  1555. QualType QType = VD->getType();
  1556. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1557. // It will be analyzed later.
  1558. Vars.push_back(DE);
  1559. continue;
  1560. }
  1561. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1562. // A threadprivate variable must not have an incomplete type.
  1563. if (RequireCompleteType(ILoc, VD->getType(),
  1564. diag::err_omp_threadprivate_incomplete_type)) {
  1565. continue;
  1566. }
  1567. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1568. // A threadprivate variable must not have a reference type.
  1569. if (VD->getType()->isReferenceType()) {
  1570. Diag(ILoc, diag::err_omp_ref_type_arg)
  1571. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1572. bool IsDecl =
  1573. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1574. Diag(VD->getLocation(),
  1575. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1576. << VD;
  1577. continue;
  1578. }
  1579. // Check if this is a TLS variable. If TLS is not being supported, produce
  1580. // the corresponding diagnostic.
  1581. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1582. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1583. getLangOpts().OpenMPUseTLS &&
  1584. getASTContext().getTargetInfo().isTLSSupported())) ||
  1585. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1586. !VD->isLocalVarDecl())) {
  1587. Diag(ILoc, diag::err_omp_var_thread_local)
  1588. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1589. bool IsDecl =
  1590. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1591. Diag(VD->getLocation(),
  1592. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1593. << VD;
  1594. continue;
  1595. }
  1596. // Check if initial value of threadprivate variable reference variable with
  1597. // local storage (it is not supported by runtime).
  1598. if (auto Init = VD->getAnyInitializer()) {
  1599. LocalVarRefChecker Checker(*this);
  1600. if (Checker.Visit(Init))
  1601. continue;
  1602. }
  1603. Vars.push_back(RefExpr);
  1604. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1605. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1606. Context, SourceRange(Loc, Loc)));
  1607. if (auto *ML = Context.getASTMutationListener())
  1608. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1609. }
  1610. OMPThreadPrivateDecl *D = nullptr;
  1611. if (!Vars.empty()) {
  1612. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1613. Vars);
  1614. D->setAccess(AS_public);
  1615. }
  1616. return D;
  1617. }
  1618. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1619. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1620. bool IsLoopIterVar = false) {
  1621. if (DVar.RefExpr) {
  1622. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1623. << getOpenMPClauseName(DVar.CKind);
  1624. return;
  1625. }
  1626. enum {
  1627. PDSA_StaticMemberShared,
  1628. PDSA_StaticLocalVarShared,
  1629. PDSA_LoopIterVarPrivate,
  1630. PDSA_LoopIterVarLinear,
  1631. PDSA_LoopIterVarLastprivate,
  1632. PDSA_ConstVarShared,
  1633. PDSA_GlobalVarShared,
  1634. PDSA_TaskVarFirstprivate,
  1635. PDSA_LocalVarPrivate,
  1636. PDSA_Implicit
  1637. } Reason = PDSA_Implicit;
  1638. bool ReportHint = false;
  1639. auto ReportLoc = D->getLocation();
  1640. auto *VD = dyn_cast<VarDecl>(D);
  1641. if (IsLoopIterVar) {
  1642. if (DVar.CKind == OMPC_private)
  1643. Reason = PDSA_LoopIterVarPrivate;
  1644. else if (DVar.CKind == OMPC_lastprivate)
  1645. Reason = PDSA_LoopIterVarLastprivate;
  1646. else
  1647. Reason = PDSA_LoopIterVarLinear;
  1648. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1649. DVar.CKind == OMPC_firstprivate) {
  1650. Reason = PDSA_TaskVarFirstprivate;
  1651. ReportLoc = DVar.ImplicitDSALoc;
  1652. } else if (VD && VD->isStaticLocal())
  1653. Reason = PDSA_StaticLocalVarShared;
  1654. else if (VD && VD->isStaticDataMember())
  1655. Reason = PDSA_StaticMemberShared;
  1656. else if (VD && VD->isFileVarDecl())
  1657. Reason = PDSA_GlobalVarShared;
  1658. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1659. Reason = PDSA_ConstVarShared;
  1660. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1661. ReportHint = true;
  1662. Reason = PDSA_LocalVarPrivate;
  1663. }
  1664. if (Reason != PDSA_Implicit) {
  1665. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1666. << Reason << ReportHint
  1667. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1668. } else if (DVar.ImplicitDSALoc.isValid()) {
  1669. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1670. << getOpenMPClauseName(DVar.CKind);
  1671. }
  1672. }
  1673. namespace {
  1674. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1675. DSAStackTy *Stack;
  1676. Sema &SemaRef;
  1677. bool ErrorFound;
  1678. CapturedStmt *CS;
  1679. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1680. llvm::SmallVector<Expr *, 8> ImplicitMap;
  1681. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1682. llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
  1683. public:
  1684. void VisitDeclRefExpr(DeclRefExpr *E) {
  1685. if (E->isTypeDependent() || E->isValueDependent() ||
  1686. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1687. return;
  1688. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1689. VD = VD->getCanonicalDecl();
  1690. // Skip internally declared variables.
  1691. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1692. return;
  1693. auto DVar = Stack->getTopDSA(VD, false);
  1694. // Check if the variable has explicit DSA set and stop analysis if it so.
  1695. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1696. return;
  1697. // Skip internally declared static variables.
  1698. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
  1699. return;
  1700. auto ELoc = E->getExprLoc();
  1701. auto DKind = Stack->getCurrentDirective();
  1702. // The default(none) clause requires that each variable that is referenced
  1703. // in the construct, and does not have a predetermined data-sharing
  1704. // attribute, must have its data-sharing attribute explicitly determined
  1705. // by being listed in a data-sharing attribute clause.
  1706. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1707. isParallelOrTaskRegion(DKind) &&
  1708. VarsWithInheritedDSA.count(VD) == 0) {
  1709. VarsWithInheritedDSA[VD] = E;
  1710. return;
  1711. }
  1712. if (isOpenMPTargetExecutionDirective(DKind) &&
  1713. !Stack->isLoopControlVariable(VD).first) {
  1714. if (!Stack->checkMappableExprComponentListsForDecl(
  1715. VD, /*CurrentRegionOnly=*/true,
  1716. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1717. StackComponents,
  1718. OpenMPClauseKind) {
  1719. // Variable is used if it has been marked as an array, array
  1720. // section or the variable iself.
  1721. return StackComponents.size() == 1 ||
  1722. std::all_of(
  1723. std::next(StackComponents.rbegin()),
  1724. StackComponents.rend(),
  1725. [](const OMPClauseMappableExprCommon::
  1726. MappableComponent &MC) {
  1727. return MC.getAssociatedDeclaration() ==
  1728. nullptr &&
  1729. (isa<OMPArraySectionExpr>(
  1730. MC.getAssociatedExpression()) ||
  1731. isa<ArraySubscriptExpr>(
  1732. MC.getAssociatedExpression()));
  1733. });
  1734. })) {
  1735. bool IsFirstprivate = false;
  1736. // By default lambdas are captured as firstprivates.
  1737. if (const auto *RD =
  1738. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  1739. IsFirstprivate = RD->isLambda();
  1740. IsFirstprivate =
  1741. IsFirstprivate ||
  1742. (VD->getType().getNonReferenceType()->isScalarType() &&
  1743. Stack->getDefaultDMA() != DMA_tofrom_scalar);
  1744. if (IsFirstprivate)
  1745. ImplicitFirstprivate.emplace_back(E);
  1746. else
  1747. ImplicitMap.emplace_back(E);
  1748. return;
  1749. }
  1750. }
  1751. // OpenMP [2.9.3.6, Restrictions, p.2]
  1752. // A list item that appears in a reduction clause of the innermost
  1753. // enclosing worksharing or parallel construct may not be accessed in an
  1754. // explicit task.
  1755. DVar = Stack->hasInnermostDSA(
  1756. VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1757. [](OpenMPDirectiveKind K) -> bool {
  1758. return isOpenMPParallelDirective(K) ||
  1759. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1760. },
  1761. /*FromParent=*/true);
  1762. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1763. ErrorFound = true;
  1764. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1765. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1766. return;
  1767. }
  1768. // Define implicit data-sharing attributes for task.
  1769. DVar = Stack->getImplicitDSA(VD, false);
  1770. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1771. !Stack->isLoopControlVariable(VD).first)
  1772. ImplicitFirstprivate.push_back(E);
  1773. }
  1774. }
  1775. void VisitMemberExpr(MemberExpr *E) {
  1776. if (E->isTypeDependent() || E->isValueDependent() ||
  1777. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1778. return;
  1779. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  1780. if (!FD)
  1781. return;
  1782. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1783. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1784. auto DVar = Stack->getTopDSA(FD, false);
  1785. // Check if the variable has explicit DSA set and stop analysis if it
  1786. // so.
  1787. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  1788. return;
  1789. if (isOpenMPTargetExecutionDirective(DKind) &&
  1790. !Stack->isLoopControlVariable(FD).first &&
  1791. !Stack->checkMappableExprComponentListsForDecl(
  1792. FD, /*CurrentRegionOnly=*/true,
  1793. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1794. StackComponents,
  1795. OpenMPClauseKind) {
  1796. return isa<CXXThisExpr>(
  1797. cast<MemberExpr>(
  1798. StackComponents.back().getAssociatedExpression())
  1799. ->getBase()
  1800. ->IgnoreParens());
  1801. })) {
  1802. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  1803. // A bit-field cannot appear in a map clause.
  1804. //
  1805. if (FD->isBitField()) {
  1806. SemaRef.Diag(E->getMemberLoc(),
  1807. diag::err_omp_bit_fields_forbidden_in_clause)
  1808. << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
  1809. return;
  1810. }
  1811. ImplicitMap.emplace_back(E);
  1812. return;
  1813. }
  1814. auto ELoc = E->getExprLoc();
  1815. // OpenMP [2.9.3.6, Restrictions, p.2]
  1816. // A list item that appears in a reduction clause of the innermost
  1817. // enclosing worksharing or parallel construct may not be accessed in
  1818. // an explicit task.
  1819. DVar = Stack->hasInnermostDSA(
  1820. FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1821. [](OpenMPDirectiveKind K) -> bool {
  1822. return isOpenMPParallelDirective(K) ||
  1823. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1824. },
  1825. /*FromParent=*/true);
  1826. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1827. ErrorFound = true;
  1828. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1829. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1830. return;
  1831. }
  1832. // Define implicit data-sharing attributes for task.
  1833. DVar = Stack->getImplicitDSA(FD, false);
  1834. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1835. !Stack->isLoopControlVariable(FD).first)
  1836. ImplicitFirstprivate.push_back(E);
  1837. return;
  1838. }
  1839. if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
  1840. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  1841. CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
  1842. auto *VD = cast<ValueDecl>(
  1843. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  1844. if (!Stack->checkMappableExprComponentListsForDecl(
  1845. VD, /*CurrentRegionOnly=*/true,
  1846. [&CurComponents](
  1847. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1848. StackComponents,
  1849. OpenMPClauseKind) {
  1850. auto CCI = CurComponents.rbegin();
  1851. auto CCE = CurComponents.rend();
  1852. for (const auto &SC : llvm::reverse(StackComponents)) {
  1853. // Do both expressions have the same kind?
  1854. if (CCI->getAssociatedExpression()->getStmtClass() !=
  1855. SC.getAssociatedExpression()->getStmtClass())
  1856. if (!(isa<OMPArraySectionExpr>(
  1857. SC.getAssociatedExpression()) &&
  1858. isa<ArraySubscriptExpr>(
  1859. CCI->getAssociatedExpression())))
  1860. return false;
  1861. Decl *CCD = CCI->getAssociatedDeclaration();
  1862. Decl *SCD = SC.getAssociatedDeclaration();
  1863. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  1864. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  1865. if (SCD != CCD)
  1866. return false;
  1867. std::advance(CCI, 1);
  1868. if (CCI == CCE)
  1869. break;
  1870. }
  1871. return true;
  1872. })) {
  1873. Visit(E->getBase());
  1874. }
  1875. } else
  1876. Visit(E->getBase());
  1877. }
  1878. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1879. for (auto *C : S->clauses()) {
  1880. // Skip analysis of arguments of implicitly defined firstprivate clause
  1881. // for task|target directives.
  1882. // Skip analysis of arguments of implicitly defined map clause for target
  1883. // directives.
  1884. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  1885. C->isImplicit())) {
  1886. for (auto *CC : C->children()) {
  1887. if (CC)
  1888. Visit(CC);
  1889. }
  1890. }
  1891. }
  1892. }
  1893. void VisitStmt(Stmt *S) {
  1894. for (auto *C : S->children()) {
  1895. if (C && !isa<OMPExecutableDirective>(C))
  1896. Visit(C);
  1897. }
  1898. }
  1899. bool isErrorFound() { return ErrorFound; }
  1900. ArrayRef<Expr *> getImplicitFirstprivate() const {
  1901. return ImplicitFirstprivate;
  1902. }
  1903. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  1904. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1905. return VarsWithInheritedDSA;
  1906. }
  1907. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1908. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1909. };
  1910. } // namespace
  1911. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1912. switch (DKind) {
  1913. case OMPD_parallel:
  1914. case OMPD_parallel_for:
  1915. case OMPD_parallel_for_simd:
  1916. case OMPD_parallel_sections:
  1917. case OMPD_teams:
  1918. case OMPD_teams_distribute: {
  1919. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1920. QualType KmpInt32PtrTy =
  1921. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1922. Sema::CapturedParamNameType Params[] = {
  1923. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1924. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1925. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1926. };
  1927. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1928. Params);
  1929. break;
  1930. }
  1931. case OMPD_target_teams:
  1932. case OMPD_target_parallel:
  1933. case OMPD_target_parallel_for:
  1934. case OMPD_target_parallel_for_simd: {
  1935. Sema::CapturedParamNameType ParamsTarget[] = {
  1936. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1937. };
  1938. // Start a captured region for 'target' with no implicit parameters.
  1939. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1940. ParamsTarget);
  1941. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1942. QualType KmpInt32PtrTy =
  1943. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1944. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  1945. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1946. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1947. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1948. };
  1949. // Start a captured region for 'teams' or 'parallel'. Both regions have
  1950. // the same implicit parameters.
  1951. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1952. ParamsTeamsOrParallel);
  1953. break;
  1954. }
  1955. case OMPD_simd:
  1956. case OMPD_for:
  1957. case OMPD_for_simd:
  1958. case OMPD_sections:
  1959. case OMPD_section:
  1960. case OMPD_single:
  1961. case OMPD_master:
  1962. case OMPD_critical:
  1963. case OMPD_taskgroup:
  1964. case OMPD_distribute:
  1965. case OMPD_ordered:
  1966. case OMPD_atomic:
  1967. case OMPD_target_data:
  1968. case OMPD_target:
  1969. case OMPD_target_simd: {
  1970. Sema::CapturedParamNameType Params[] = {
  1971. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1972. };
  1973. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1974. Params);
  1975. break;
  1976. }
  1977. case OMPD_task: {
  1978. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1979. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1980. FunctionProtoType::ExtProtoInfo EPI;
  1981. EPI.Variadic = true;
  1982. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1983. Sema::CapturedParamNameType Params[] = {
  1984. std::make_pair(".global_tid.", KmpInt32Ty),
  1985. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  1986. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  1987. std::make_pair(".copy_fn.",
  1988. Context.getPointerType(CopyFnType).withConst()),
  1989. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  1990. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1991. };
  1992. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1993. Params);
  1994. // Mark this captured region as inlined, because we don't use outlined
  1995. // function directly.
  1996. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1997. AlwaysInlineAttr::CreateImplicit(
  1998. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1999. break;
  2000. }
  2001. case OMPD_taskloop:
  2002. case OMPD_taskloop_simd: {
  2003. QualType KmpInt32Ty =
  2004. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2005. QualType KmpUInt64Ty =
  2006. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  2007. QualType KmpInt64Ty =
  2008. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  2009. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2010. FunctionProtoType::ExtProtoInfo EPI;
  2011. EPI.Variadic = true;
  2012. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2013. Sema::CapturedParamNameType Params[] = {
  2014. std::make_pair(".global_tid.", KmpInt32Ty),
  2015. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2016. std::make_pair(".privates.",
  2017. Context.VoidPtrTy.withConst().withRestrict()),
  2018. std::make_pair(
  2019. ".copy_fn.",
  2020. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2021. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2022. std::make_pair(".lb.", KmpUInt64Ty),
  2023. std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
  2024. std::make_pair(".liter.", KmpInt32Ty),
  2025. std::make_pair(".reductions.",
  2026. Context.VoidPtrTy.withConst().withRestrict()),
  2027. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2028. };
  2029. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2030. Params);
  2031. // Mark this captured region as inlined, because we don't use outlined
  2032. // function directly.
  2033. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2034. AlwaysInlineAttr::CreateImplicit(
  2035. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2036. break;
  2037. }
  2038. case OMPD_distribute_parallel_for_simd:
  2039. case OMPD_distribute_simd:
  2040. case OMPD_distribute_parallel_for:
  2041. case OMPD_teams_distribute_simd:
  2042. case OMPD_target_teams_distribute:
  2043. case OMPD_target_teams_distribute_parallel_for:
  2044. case OMPD_target_teams_distribute_parallel_for_simd:
  2045. case OMPD_target_teams_distribute_simd: {
  2046. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2047. QualType KmpInt32PtrTy =
  2048. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2049. Sema::CapturedParamNameType Params[] = {
  2050. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2051. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2052. std::make_pair(".previous.lb.", Context.getSizeType()),
  2053. std::make_pair(".previous.ub.", Context.getSizeType()),
  2054. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2055. };
  2056. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2057. Params);
  2058. break;
  2059. }
  2060. case OMPD_teams_distribute_parallel_for:
  2061. case OMPD_teams_distribute_parallel_for_simd: {
  2062. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2063. QualType KmpInt32PtrTy =
  2064. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2065. Sema::CapturedParamNameType ParamsTeams[] = {
  2066. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2067. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2068. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2069. };
  2070. // Start a captured region for 'target' with no implicit parameters.
  2071. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2072. ParamsTeams);
  2073. Sema::CapturedParamNameType ParamsParallel[] = {
  2074. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2075. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2076. std::make_pair(".previous.lb.", Context.getSizeType()),
  2077. std::make_pair(".previous.ub.", Context.getSizeType()),
  2078. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2079. };
  2080. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2081. // the same implicit parameters.
  2082. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2083. ParamsParallel);
  2084. break;
  2085. }
  2086. case OMPD_target_update:
  2087. case OMPD_target_enter_data:
  2088. case OMPD_target_exit_data: {
  2089. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2090. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2091. FunctionProtoType::ExtProtoInfo EPI;
  2092. EPI.Variadic = true;
  2093. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2094. Sema::CapturedParamNameType Params[] = {
  2095. std::make_pair(".global_tid.", KmpInt32Ty),
  2096. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2097. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  2098. std::make_pair(".copy_fn.",
  2099. Context.getPointerType(CopyFnType).withConst()),
  2100. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2101. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2102. };
  2103. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2104. Params);
  2105. // Mark this captured region as inlined, because we don't use outlined
  2106. // function directly.
  2107. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2108. AlwaysInlineAttr::CreateImplicit(
  2109. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2110. break;
  2111. }
  2112. case OMPD_threadprivate:
  2113. case OMPD_taskyield:
  2114. case OMPD_barrier:
  2115. case OMPD_taskwait:
  2116. case OMPD_cancellation_point:
  2117. case OMPD_cancel:
  2118. case OMPD_flush:
  2119. case OMPD_declare_reduction:
  2120. case OMPD_declare_simd:
  2121. case OMPD_declare_target:
  2122. case OMPD_end_declare_target:
  2123. llvm_unreachable("OpenMP Directive is not allowed");
  2124. case OMPD_unknown:
  2125. llvm_unreachable("Unknown OpenMP directive");
  2126. }
  2127. }
  2128. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2129. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2130. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2131. return CaptureRegions.size();
  2132. }
  2133. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2134. Expr *CaptureExpr, bool WithInit,
  2135. bool AsExpression) {
  2136. assert(CaptureExpr);
  2137. ASTContext &C = S.getASTContext();
  2138. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2139. QualType Ty = Init->getType();
  2140. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2141. if (S.getLangOpts().CPlusPlus)
  2142. Ty = C.getLValueReferenceType(Ty);
  2143. else {
  2144. Ty = C.getPointerType(Ty);
  2145. ExprResult Res =
  2146. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2147. if (!Res.isUsable())
  2148. return nullptr;
  2149. Init = Res.get();
  2150. }
  2151. WithInit = true;
  2152. }
  2153. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2154. CaptureExpr->getLocStart());
  2155. if (!WithInit)
  2156. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
  2157. S.CurContext->addHiddenDecl(CED);
  2158. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2159. return CED;
  2160. }
  2161. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2162. bool WithInit) {
  2163. OMPCapturedExprDecl *CD;
  2164. if (auto *VD = S.IsOpenMPCapturedDecl(D))
  2165. CD = cast<OMPCapturedExprDecl>(VD);
  2166. else
  2167. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2168. /*AsExpression=*/false);
  2169. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2170. CaptureExpr->getExprLoc());
  2171. }
  2172. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2173. if (!Ref) {
  2174. auto *CD =
  2175. buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
  2176. CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
  2177. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2178. CaptureExpr->getExprLoc());
  2179. }
  2180. ExprResult Res = Ref;
  2181. if (!S.getLangOpts().CPlusPlus &&
  2182. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2183. Ref->getType()->isPointerType())
  2184. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2185. if (!Res.isUsable())
  2186. return ExprError();
  2187. return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
  2188. }
  2189. namespace {
  2190. // OpenMP directives parsed in this section are represented as a
  2191. // CapturedStatement with an associated statement. If a syntax error
  2192. // is detected during the parsing of the associated statement, the
  2193. // compiler must abort processing and close the CapturedStatement.
  2194. //
  2195. // Combined directives such as 'target parallel' have more than one
  2196. // nested CapturedStatements. This RAII ensures that we unwind out
  2197. // of all the nested CapturedStatements when an error is found.
  2198. class CaptureRegionUnwinderRAII {
  2199. private:
  2200. Sema &S;
  2201. bool &ErrorFound;
  2202. OpenMPDirectiveKind DKind;
  2203. public:
  2204. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2205. OpenMPDirectiveKind DKind)
  2206. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2207. ~CaptureRegionUnwinderRAII() {
  2208. if (ErrorFound) {
  2209. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2210. while (--ThisCaptureLevel >= 0)
  2211. S.ActOnCapturedRegionError();
  2212. }
  2213. }
  2214. };
  2215. } // namespace
  2216. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2217. ArrayRef<OMPClause *> Clauses) {
  2218. bool ErrorFound = false;
  2219. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2220. *this, ErrorFound, DSAStack->getCurrentDirective());
  2221. if (!S.isUsable()) {
  2222. ErrorFound = true;
  2223. return StmtError();
  2224. }
  2225. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2226. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2227. OMPOrderedClause *OC = nullptr;
  2228. OMPScheduleClause *SC = nullptr;
  2229. SmallVector<OMPLinearClause *, 4> LCs;
  2230. SmallVector<OMPClauseWithPreInit *, 8> PICs;
  2231. // This is required for proper codegen.
  2232. for (auto *Clause : Clauses) {
  2233. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2234. Clause->getClauseKind() == OMPC_in_reduction) {
  2235. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2236. // with the corresponding in_reduction items.
  2237. auto *IRC = cast<OMPInReductionClause>(Clause);
  2238. for (auto *E : IRC->taskgroup_descriptors())
  2239. if (E)
  2240. MarkDeclarationsReferencedInExpr(E);
  2241. }
  2242. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2243. Clause->getClauseKind() == OMPC_copyprivate ||
  2244. (getLangOpts().OpenMPUseTLS &&
  2245. getASTContext().getTargetInfo().isTLSSupported() &&
  2246. Clause->getClauseKind() == OMPC_copyin)) {
  2247. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2248. // Mark all variables in private list clauses as used in inner region.
  2249. for (auto *VarRef : Clause->children()) {
  2250. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2251. MarkDeclarationsReferencedInExpr(E);
  2252. }
  2253. }
  2254. DSAStack->setForceVarCapturing(/*V=*/false);
  2255. } else if (CaptureRegions.size() > 1 ||
  2256. CaptureRegions.back() != OMPD_unknown) {
  2257. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2258. PICs.push_back(C);
  2259. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2260. if (auto *E = C->getPostUpdateExpr())
  2261. MarkDeclarationsReferencedInExpr(E);
  2262. }
  2263. }
  2264. if (Clause->getClauseKind() == OMPC_schedule)
  2265. SC = cast<OMPScheduleClause>(Clause);
  2266. else if (Clause->getClauseKind() == OMPC_ordered)
  2267. OC = cast<OMPOrderedClause>(Clause);
  2268. else if (Clause->getClauseKind() == OMPC_linear)
  2269. LCs.push_back(cast<OMPLinearClause>(Clause));
  2270. }
  2271. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2272. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2273. // specified.
  2274. if (SC &&
  2275. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2276. SC->getSecondScheduleModifier() ==
  2277. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2278. OC) {
  2279. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2280. ? SC->getFirstScheduleModifierLoc()
  2281. : SC->getSecondScheduleModifierLoc(),
  2282. diag::err_omp_schedule_nonmonotonic_ordered)
  2283. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2284. ErrorFound = true;
  2285. }
  2286. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2287. for (auto *C : LCs) {
  2288. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  2289. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2290. }
  2291. ErrorFound = true;
  2292. }
  2293. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2294. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2295. OC->getNumForLoops()) {
  2296. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  2297. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2298. ErrorFound = true;
  2299. }
  2300. if (ErrorFound) {
  2301. return StmtError();
  2302. }
  2303. StmtResult SR = S;
  2304. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2305. // Mark all variables in private list clauses as used in inner region.
  2306. // Required for proper codegen of combined directives.
  2307. // TODO: add processing for other clauses.
  2308. if (ThisCaptureRegion != OMPD_unknown) {
  2309. for (auto *C : PICs) {
  2310. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2311. // Find the particular capture region for the clause if the
  2312. // directive is a combined one with multiple capture regions.
  2313. // If the directive is not a combined one, the capture region
  2314. // associated with the clause is OMPD_unknown and is generated
  2315. // only once.
  2316. if (CaptureRegion == ThisCaptureRegion ||
  2317. CaptureRegion == OMPD_unknown) {
  2318. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2319. for (auto *D : DS->decls())
  2320. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2321. }
  2322. }
  2323. }
  2324. }
  2325. SR = ActOnCapturedRegionEnd(SR.get());
  2326. }
  2327. return SR;
  2328. }
  2329. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2330. OpenMPDirectiveKind CancelRegion,
  2331. SourceLocation StartLoc) {
  2332. // CancelRegion is only needed for cancel and cancellation_point.
  2333. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2334. return false;
  2335. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2336. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2337. return false;
  2338. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2339. << getOpenMPDirectiveName(CancelRegion);
  2340. return true;
  2341. }
  2342. static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  2343. OpenMPDirectiveKind CurrentRegion,
  2344. const DeclarationNameInfo &CurrentName,
  2345. OpenMPDirectiveKind CancelRegion,
  2346. SourceLocation StartLoc) {
  2347. if (Stack->getCurScope()) {
  2348. auto ParentRegion = Stack->getParentDirective();
  2349. auto OffendingRegion = ParentRegion;
  2350. bool NestingProhibited = false;
  2351. bool CloseNesting = true;
  2352. bool OrphanSeen = false;
  2353. enum {
  2354. NoRecommend,
  2355. ShouldBeInParallelRegion,
  2356. ShouldBeInOrderedRegion,
  2357. ShouldBeInTargetRegion,
  2358. ShouldBeInTeamsRegion
  2359. } Recommend = NoRecommend;
  2360. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2361. // OpenMP [2.16, Nesting of Regions]
  2362. // OpenMP constructs may not be nested inside a simd region.
  2363. // OpenMP [2.8.1,simd Construct, Restrictions]
  2364. // An ordered construct with the simd clause is the only OpenMP
  2365. // construct that can appear in the simd region.
  2366. // Allowing a SIMD construct nested in another SIMD construct is an
  2367. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2368. // message.
  2369. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2370. ? diag::err_omp_prohibited_region_simd
  2371. : diag::warn_omp_nesting_simd);
  2372. return CurrentRegion != OMPD_simd;
  2373. }
  2374. if (ParentRegion == OMPD_atomic) {
  2375. // OpenMP [2.16, Nesting of Regions]
  2376. // OpenMP constructs may not be nested inside an atomic region.
  2377. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2378. return true;
  2379. }
  2380. if (CurrentRegion == OMPD_section) {
  2381. // OpenMP [2.7.2, sections Construct, Restrictions]
  2382. // Orphaned section directives are prohibited. That is, the section
  2383. // directives must appear within the sections construct and must not be
  2384. // encountered elsewhere in the sections region.
  2385. if (ParentRegion != OMPD_sections &&
  2386. ParentRegion != OMPD_parallel_sections) {
  2387. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2388. << (ParentRegion != OMPD_unknown)
  2389. << getOpenMPDirectiveName(ParentRegion);
  2390. return true;
  2391. }
  2392. return false;
  2393. }
  2394. // Allow some constructs (except teams) to be orphaned (they could be
  2395. // used in functions, called from OpenMP regions with the required
  2396. // preconditions).
  2397. if (ParentRegion == OMPD_unknown &&
  2398. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2399. return false;
  2400. if (CurrentRegion == OMPD_cancellation_point ||
  2401. CurrentRegion == OMPD_cancel) {
  2402. // OpenMP [2.16, Nesting of Regions]
  2403. // A cancellation point construct for which construct-type-clause is
  2404. // taskgroup must be nested inside a task construct. A cancellation
  2405. // point construct for which construct-type-clause is not taskgroup must
  2406. // be closely nested inside an OpenMP construct that matches the type
  2407. // specified in construct-type-clause.
  2408. // A cancel construct for which construct-type-clause is taskgroup must be
  2409. // nested inside a task construct. A cancel construct for which
  2410. // construct-type-clause is not taskgroup must be closely nested inside an
  2411. // OpenMP construct that matches the type specified in
  2412. // construct-type-clause.
  2413. NestingProhibited =
  2414. !((CancelRegion == OMPD_parallel &&
  2415. (ParentRegion == OMPD_parallel ||
  2416. ParentRegion == OMPD_target_parallel)) ||
  2417. (CancelRegion == OMPD_for &&
  2418. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2419. ParentRegion == OMPD_target_parallel_for ||
  2420. ParentRegion == OMPD_distribute_parallel_for ||
  2421. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2422. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2423. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2424. (CancelRegion == OMPD_sections &&
  2425. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2426. ParentRegion == OMPD_parallel_sections)));
  2427. } else if (CurrentRegion == OMPD_master) {
  2428. // OpenMP [2.16, Nesting of Regions]
  2429. // A master region may not be closely nested inside a worksharing,
  2430. // atomic, or explicit task region.
  2431. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2432. isOpenMPTaskingDirective(ParentRegion);
  2433. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2434. // OpenMP [2.16, Nesting of Regions]
  2435. // A critical region may not be nested (closely or otherwise) inside a
  2436. // critical region with the same name. Note that this restriction is not
  2437. // sufficient to prevent deadlock.
  2438. SourceLocation PreviousCriticalLoc;
  2439. bool DeadLock = Stack->hasDirective(
  2440. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2441. const DeclarationNameInfo &DNI,
  2442. SourceLocation Loc) -> bool {
  2443. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2444. PreviousCriticalLoc = Loc;
  2445. return true;
  2446. } else
  2447. return false;
  2448. },
  2449. false /* skip top directive */);
  2450. if (DeadLock) {
  2451. SemaRef.Diag(StartLoc,
  2452. diag::err_omp_prohibited_region_critical_same_name)
  2453. << CurrentName.getName();
  2454. if (PreviousCriticalLoc.isValid())
  2455. SemaRef.Diag(PreviousCriticalLoc,
  2456. diag::note_omp_previous_critical_region);
  2457. return true;
  2458. }
  2459. } else if (CurrentRegion == OMPD_barrier) {
  2460. // OpenMP [2.16, Nesting of Regions]
  2461. // A barrier region may not be closely nested inside a worksharing,
  2462. // explicit task, critical, ordered, atomic, or master region.
  2463. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2464. isOpenMPTaskingDirective(ParentRegion) ||
  2465. ParentRegion == OMPD_master ||
  2466. ParentRegion == OMPD_critical ||
  2467. ParentRegion == OMPD_ordered;
  2468. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2469. !isOpenMPParallelDirective(CurrentRegion) &&
  2470. !isOpenMPTeamsDirective(CurrentRegion)) {
  2471. // OpenMP [2.16, Nesting of Regions]
  2472. // A worksharing region may not be closely nested inside a worksharing,
  2473. // explicit task, critical, ordered, atomic, or master region.
  2474. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2475. isOpenMPTaskingDirective(ParentRegion) ||
  2476. ParentRegion == OMPD_master ||
  2477. ParentRegion == OMPD_critical ||
  2478. ParentRegion == OMPD_ordered;
  2479. Recommend = ShouldBeInParallelRegion;
  2480. } else if (CurrentRegion == OMPD_ordered) {
  2481. // OpenMP [2.16, Nesting of Regions]
  2482. // An ordered region may not be closely nested inside a critical,
  2483. // atomic, or explicit task region.
  2484. // An ordered region must be closely nested inside a loop region (or
  2485. // parallel loop region) with an ordered clause.
  2486. // OpenMP [2.8.1,simd Construct, Restrictions]
  2487. // An ordered construct with the simd clause is the only OpenMP construct
  2488. // that can appear in the simd region.
  2489. NestingProhibited = ParentRegion == OMPD_critical ||
  2490. isOpenMPTaskingDirective(ParentRegion) ||
  2491. !(isOpenMPSimdDirective(ParentRegion) ||
  2492. Stack->isParentOrderedRegion());
  2493. Recommend = ShouldBeInOrderedRegion;
  2494. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2495. // OpenMP [2.16, Nesting of Regions]
  2496. // If specified, a teams construct must be contained within a target
  2497. // construct.
  2498. NestingProhibited = ParentRegion != OMPD_target;
  2499. OrphanSeen = ParentRegion == OMPD_unknown;
  2500. Recommend = ShouldBeInTargetRegion;
  2501. }
  2502. if (!NestingProhibited &&
  2503. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2504. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2505. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2506. // OpenMP [2.16, Nesting of Regions]
  2507. // distribute, parallel, parallel sections, parallel workshare, and the
  2508. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2509. // constructs that can be closely nested in the teams region.
  2510. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2511. !isOpenMPDistributeDirective(CurrentRegion);
  2512. Recommend = ShouldBeInParallelRegion;
  2513. }
  2514. if (!NestingProhibited &&
  2515. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2516. // OpenMP 4.5 [2.17 Nesting of Regions]
  2517. // The region associated with the distribute construct must be strictly
  2518. // nested inside a teams region
  2519. NestingProhibited =
  2520. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2521. Recommend = ShouldBeInTeamsRegion;
  2522. }
  2523. if (!NestingProhibited &&
  2524. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2525. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2526. // OpenMP 4.5 [2.17 Nesting of Regions]
  2527. // If a target, target update, target data, target enter data, or
  2528. // target exit data construct is encountered during execution of a
  2529. // target region, the behavior is unspecified.
  2530. NestingProhibited = Stack->hasDirective(
  2531. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2532. SourceLocation) -> bool {
  2533. if (isOpenMPTargetExecutionDirective(K)) {
  2534. OffendingRegion = K;
  2535. return true;
  2536. } else
  2537. return false;
  2538. },
  2539. false /* don't skip top directive */);
  2540. CloseNesting = false;
  2541. }
  2542. if (NestingProhibited) {
  2543. if (OrphanSeen) {
  2544. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2545. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2546. } else {
  2547. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2548. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2549. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2550. }
  2551. return true;
  2552. }
  2553. }
  2554. return false;
  2555. }
  2556. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2557. ArrayRef<OMPClause *> Clauses,
  2558. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2559. bool ErrorFound = false;
  2560. unsigned NamedModifiersNumber = 0;
  2561. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2562. OMPD_unknown + 1);
  2563. SmallVector<SourceLocation, 4> NameModifierLoc;
  2564. for (const auto *C : Clauses) {
  2565. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2566. // At most one if clause without a directive-name-modifier can appear on
  2567. // the directive.
  2568. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2569. if (FoundNameModifiers[CurNM]) {
  2570. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2571. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2572. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2573. ErrorFound = true;
  2574. } else if (CurNM != OMPD_unknown) {
  2575. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2576. ++NamedModifiersNumber;
  2577. }
  2578. FoundNameModifiers[CurNM] = IC;
  2579. if (CurNM == OMPD_unknown)
  2580. continue;
  2581. // Check if the specified name modifier is allowed for the current
  2582. // directive.
  2583. // At most one if clause with the particular directive-name-modifier can
  2584. // appear on the directive.
  2585. bool MatchFound = false;
  2586. for (auto NM : AllowedNameModifiers) {
  2587. if (CurNM == NM) {
  2588. MatchFound = true;
  2589. break;
  2590. }
  2591. }
  2592. if (!MatchFound) {
  2593. S.Diag(IC->getNameModifierLoc(),
  2594. diag::err_omp_wrong_if_directive_name_modifier)
  2595. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2596. ErrorFound = true;
  2597. }
  2598. }
  2599. }
  2600. // If any if clause on the directive includes a directive-name-modifier then
  2601. // all if clauses on the directive must include a directive-name-modifier.
  2602. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2603. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2604. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2605. diag::err_omp_no_more_if_clause);
  2606. } else {
  2607. std::string Values;
  2608. std::string Sep(", ");
  2609. unsigned AllowedCnt = 0;
  2610. unsigned TotalAllowedNum =
  2611. AllowedNameModifiers.size() - NamedModifiersNumber;
  2612. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2613. ++Cnt) {
  2614. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2615. if (!FoundNameModifiers[NM]) {
  2616. Values += "'";
  2617. Values += getOpenMPDirectiveName(NM);
  2618. Values += "'";
  2619. if (AllowedCnt + 2 == TotalAllowedNum)
  2620. Values += " or ";
  2621. else if (AllowedCnt + 1 != TotalAllowedNum)
  2622. Values += Sep;
  2623. ++AllowedCnt;
  2624. }
  2625. }
  2626. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2627. diag::err_omp_unnamed_if_clause)
  2628. << (TotalAllowedNum > 1) << Values;
  2629. }
  2630. for (auto Loc : NameModifierLoc) {
  2631. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2632. }
  2633. ErrorFound = true;
  2634. }
  2635. return ErrorFound;
  2636. }
  2637. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2638. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2639. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2640. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2641. StmtResult Res = StmtError();
  2642. // First check CancelRegion which is then used in checkNestingOfRegions.
  2643. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  2644. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2645. StartLoc))
  2646. return StmtError();
  2647. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2648. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2649. bool ErrorFound = false;
  2650. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2651. if (AStmt && !CurContext->isDependentContext()) {
  2652. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2653. // Check default data sharing attributes for referenced variables.
  2654. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2655. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  2656. Stmt *S = AStmt;
  2657. while (--ThisCaptureLevel >= 0)
  2658. S = cast<CapturedStmt>(S)->getCapturedStmt();
  2659. DSAChecker.Visit(S);
  2660. if (DSAChecker.isErrorFound())
  2661. return StmtError();
  2662. // Generate list of implicitly defined firstprivate variables.
  2663. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2664. SmallVector<Expr *, 4> ImplicitFirstprivates(
  2665. DSAChecker.getImplicitFirstprivate().begin(),
  2666. DSAChecker.getImplicitFirstprivate().end());
  2667. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  2668. DSAChecker.getImplicitMap().end());
  2669. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  2670. for (auto *C : Clauses) {
  2671. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  2672. for (auto *E : IRC->taskgroup_descriptors())
  2673. if (E)
  2674. ImplicitFirstprivates.emplace_back(E);
  2675. }
  2676. }
  2677. if (!ImplicitFirstprivates.empty()) {
  2678. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2679. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  2680. SourceLocation())) {
  2681. ClausesWithImplicit.push_back(Implicit);
  2682. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2683. ImplicitFirstprivates.size();
  2684. } else
  2685. ErrorFound = true;
  2686. }
  2687. if (!ImplicitMaps.empty()) {
  2688. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  2689. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  2690. SourceLocation(), SourceLocation(), ImplicitMaps,
  2691. SourceLocation(), SourceLocation(), SourceLocation())) {
  2692. ClausesWithImplicit.emplace_back(Implicit);
  2693. ErrorFound |=
  2694. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  2695. } else
  2696. ErrorFound = true;
  2697. }
  2698. }
  2699. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2700. switch (Kind) {
  2701. case OMPD_parallel:
  2702. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2703. EndLoc);
  2704. AllowedNameModifiers.push_back(OMPD_parallel);
  2705. break;
  2706. case OMPD_simd:
  2707. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2708. VarsWithInheritedDSA);
  2709. break;
  2710. case OMPD_for:
  2711. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2712. VarsWithInheritedDSA);
  2713. break;
  2714. case OMPD_for_simd:
  2715. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2716. EndLoc, VarsWithInheritedDSA);
  2717. break;
  2718. case OMPD_sections:
  2719. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2720. EndLoc);
  2721. break;
  2722. case OMPD_section:
  2723. assert(ClausesWithImplicit.empty() &&
  2724. "No clauses are allowed for 'omp section' directive");
  2725. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2726. break;
  2727. case OMPD_single:
  2728. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2729. EndLoc);
  2730. break;
  2731. case OMPD_master:
  2732. assert(ClausesWithImplicit.empty() &&
  2733. "No clauses are allowed for 'omp master' directive");
  2734. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2735. break;
  2736. case OMPD_critical:
  2737. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2738. StartLoc, EndLoc);
  2739. break;
  2740. case OMPD_parallel_for:
  2741. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2742. EndLoc, VarsWithInheritedDSA);
  2743. AllowedNameModifiers.push_back(OMPD_parallel);
  2744. break;
  2745. case OMPD_parallel_for_simd:
  2746. Res = ActOnOpenMPParallelForSimdDirective(
  2747. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2748. AllowedNameModifiers.push_back(OMPD_parallel);
  2749. break;
  2750. case OMPD_parallel_sections:
  2751. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2752. StartLoc, EndLoc);
  2753. AllowedNameModifiers.push_back(OMPD_parallel);
  2754. break;
  2755. case OMPD_task:
  2756. Res =
  2757. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2758. AllowedNameModifiers.push_back(OMPD_task);
  2759. break;
  2760. case OMPD_taskyield:
  2761. assert(ClausesWithImplicit.empty() &&
  2762. "No clauses are allowed for 'omp taskyield' directive");
  2763. assert(AStmt == nullptr &&
  2764. "No associated statement allowed for 'omp taskyield' directive");
  2765. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2766. break;
  2767. case OMPD_barrier:
  2768. assert(ClausesWithImplicit.empty() &&
  2769. "No clauses are allowed for 'omp barrier' directive");
  2770. assert(AStmt == nullptr &&
  2771. "No associated statement allowed for 'omp barrier' directive");
  2772. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2773. break;
  2774. case OMPD_taskwait:
  2775. assert(ClausesWithImplicit.empty() &&
  2776. "No clauses are allowed for 'omp taskwait' directive");
  2777. assert(AStmt == nullptr &&
  2778. "No associated statement allowed for 'omp taskwait' directive");
  2779. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2780. break;
  2781. case OMPD_taskgroup:
  2782. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  2783. EndLoc);
  2784. break;
  2785. case OMPD_flush:
  2786. assert(AStmt == nullptr &&
  2787. "No associated statement allowed for 'omp flush' directive");
  2788. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2789. break;
  2790. case OMPD_ordered:
  2791. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2792. EndLoc);
  2793. break;
  2794. case OMPD_atomic:
  2795. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2796. EndLoc);
  2797. break;
  2798. case OMPD_teams:
  2799. Res =
  2800. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2801. break;
  2802. case OMPD_target:
  2803. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2804. EndLoc);
  2805. AllowedNameModifiers.push_back(OMPD_target);
  2806. break;
  2807. case OMPD_target_parallel:
  2808. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2809. StartLoc, EndLoc);
  2810. AllowedNameModifiers.push_back(OMPD_target);
  2811. AllowedNameModifiers.push_back(OMPD_parallel);
  2812. break;
  2813. case OMPD_target_parallel_for:
  2814. Res = ActOnOpenMPTargetParallelForDirective(
  2815. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2816. AllowedNameModifiers.push_back(OMPD_target);
  2817. AllowedNameModifiers.push_back(OMPD_parallel);
  2818. break;
  2819. case OMPD_cancellation_point:
  2820. assert(ClausesWithImplicit.empty() &&
  2821. "No clauses are allowed for 'omp cancellation point' directive");
  2822. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2823. "cancellation point' directive");
  2824. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2825. break;
  2826. case OMPD_cancel:
  2827. assert(AStmt == nullptr &&
  2828. "No associated statement allowed for 'omp cancel' directive");
  2829. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2830. CancelRegion);
  2831. AllowedNameModifiers.push_back(OMPD_cancel);
  2832. break;
  2833. case OMPD_target_data:
  2834. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2835. EndLoc);
  2836. AllowedNameModifiers.push_back(OMPD_target_data);
  2837. break;
  2838. case OMPD_target_enter_data:
  2839. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2840. EndLoc, AStmt);
  2841. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2842. break;
  2843. case OMPD_target_exit_data:
  2844. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2845. EndLoc, AStmt);
  2846. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2847. break;
  2848. case OMPD_taskloop:
  2849. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2850. EndLoc, VarsWithInheritedDSA);
  2851. AllowedNameModifiers.push_back(OMPD_taskloop);
  2852. break;
  2853. case OMPD_taskloop_simd:
  2854. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2855. EndLoc, VarsWithInheritedDSA);
  2856. AllowedNameModifiers.push_back(OMPD_taskloop);
  2857. break;
  2858. case OMPD_distribute:
  2859. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2860. EndLoc, VarsWithInheritedDSA);
  2861. break;
  2862. case OMPD_target_update:
  2863. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  2864. EndLoc, AStmt);
  2865. AllowedNameModifiers.push_back(OMPD_target_update);
  2866. break;
  2867. case OMPD_distribute_parallel_for:
  2868. Res = ActOnOpenMPDistributeParallelForDirective(
  2869. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2870. AllowedNameModifiers.push_back(OMPD_parallel);
  2871. break;
  2872. case OMPD_distribute_parallel_for_simd:
  2873. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  2874. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2875. AllowedNameModifiers.push_back(OMPD_parallel);
  2876. break;
  2877. case OMPD_distribute_simd:
  2878. Res = ActOnOpenMPDistributeSimdDirective(
  2879. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2880. break;
  2881. case OMPD_target_parallel_for_simd:
  2882. Res = ActOnOpenMPTargetParallelForSimdDirective(
  2883. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2884. AllowedNameModifiers.push_back(OMPD_target);
  2885. AllowedNameModifiers.push_back(OMPD_parallel);
  2886. break;
  2887. case OMPD_target_simd:
  2888. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2889. EndLoc, VarsWithInheritedDSA);
  2890. AllowedNameModifiers.push_back(OMPD_target);
  2891. break;
  2892. case OMPD_teams_distribute:
  2893. Res = ActOnOpenMPTeamsDistributeDirective(
  2894. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2895. break;
  2896. case OMPD_teams_distribute_simd:
  2897. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  2898. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2899. break;
  2900. case OMPD_teams_distribute_parallel_for_simd:
  2901. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  2902. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2903. AllowedNameModifiers.push_back(OMPD_parallel);
  2904. break;
  2905. case OMPD_teams_distribute_parallel_for:
  2906. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  2907. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2908. AllowedNameModifiers.push_back(OMPD_parallel);
  2909. break;
  2910. case OMPD_target_teams:
  2911. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2912. EndLoc);
  2913. AllowedNameModifiers.push_back(OMPD_target);
  2914. break;
  2915. case OMPD_target_teams_distribute:
  2916. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  2917. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2918. AllowedNameModifiers.push_back(OMPD_target);
  2919. break;
  2920. case OMPD_target_teams_distribute_parallel_for:
  2921. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  2922. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2923. AllowedNameModifiers.push_back(OMPD_target);
  2924. AllowedNameModifiers.push_back(OMPD_parallel);
  2925. break;
  2926. case OMPD_target_teams_distribute_parallel_for_simd:
  2927. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  2928. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2929. AllowedNameModifiers.push_back(OMPD_target);
  2930. AllowedNameModifiers.push_back(OMPD_parallel);
  2931. break;
  2932. case OMPD_target_teams_distribute_simd:
  2933. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  2934. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2935. AllowedNameModifiers.push_back(OMPD_target);
  2936. break;
  2937. case OMPD_declare_target:
  2938. case OMPD_end_declare_target:
  2939. case OMPD_threadprivate:
  2940. case OMPD_declare_reduction:
  2941. case OMPD_declare_simd:
  2942. llvm_unreachable("OpenMP Directive is not allowed");
  2943. case OMPD_unknown:
  2944. llvm_unreachable("Unknown OpenMP directive");
  2945. }
  2946. for (auto P : VarsWithInheritedDSA) {
  2947. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2948. << P.first << P.second->getSourceRange();
  2949. }
  2950. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2951. if (!AllowedNameModifiers.empty())
  2952. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2953. ErrorFound;
  2954. if (ErrorFound)
  2955. return StmtError();
  2956. return Res;
  2957. }
  2958. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  2959. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  2960. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  2961. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  2962. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  2963. assert(Aligneds.size() == Alignments.size());
  2964. assert(Linears.size() == LinModifiers.size());
  2965. assert(Linears.size() == Steps.size());
  2966. if (!DG || DG.get().isNull())
  2967. return DeclGroupPtrTy();
  2968. if (!DG.get().isSingleDecl()) {
  2969. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  2970. return DG;
  2971. }
  2972. auto *ADecl = DG.get().getSingleDecl();
  2973. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  2974. ADecl = FTD->getTemplatedDecl();
  2975. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  2976. if (!FD) {
  2977. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  2978. return DeclGroupPtrTy();
  2979. }
  2980. // OpenMP [2.8.2, declare simd construct, Description]
  2981. // The parameter of the simdlen clause must be a constant positive integer
  2982. // expression.
  2983. ExprResult SL;
  2984. if (Simdlen)
  2985. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  2986. // OpenMP [2.8.2, declare simd construct, Description]
  2987. // The special this pointer can be used as if was one of the arguments to the
  2988. // function in any of the linear, aligned, or uniform clauses.
  2989. // The uniform clause declares one or more arguments to have an invariant
  2990. // value for all concurrent invocations of the function in the execution of a
  2991. // single SIMD loop.
  2992. llvm::DenseMap<Decl *, Expr *> UniformedArgs;
  2993. Expr *UniformedLinearThis = nullptr;
  2994. for (auto *E : Uniforms) {
  2995. E = E->IgnoreParenImpCasts();
  2996. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  2997. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  2998. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  2999. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3000. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3001. UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
  3002. continue;
  3003. }
  3004. if (isa<CXXThisExpr>(E)) {
  3005. UniformedLinearThis = E;
  3006. continue;
  3007. }
  3008. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3009. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3010. }
  3011. // OpenMP [2.8.2, declare simd construct, Description]
  3012. // The aligned clause declares that the object to which each list item points
  3013. // is aligned to the number of bytes expressed in the optional parameter of
  3014. // the aligned clause.
  3015. // The special this pointer can be used as if was one of the arguments to the
  3016. // function in any of the linear, aligned, or uniform clauses.
  3017. // The type of list items appearing in the aligned clause must be array,
  3018. // pointer, reference to array, or reference to pointer.
  3019. llvm::DenseMap<Decl *, Expr *> AlignedArgs;
  3020. Expr *AlignedThis = nullptr;
  3021. for (auto *E : Aligneds) {
  3022. E = E->IgnoreParenImpCasts();
  3023. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3024. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3025. auto *CanonPVD = PVD->getCanonicalDecl();
  3026. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3027. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3028. ->getCanonicalDecl() == CanonPVD) {
  3029. // OpenMP [2.8.1, simd construct, Restrictions]
  3030. // A list-item cannot appear in more than one aligned clause.
  3031. if (AlignedArgs.count(CanonPVD) > 0) {
  3032. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3033. << 1 << E->getSourceRange();
  3034. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3035. diag::note_omp_explicit_dsa)
  3036. << getOpenMPClauseName(OMPC_aligned);
  3037. continue;
  3038. }
  3039. AlignedArgs[CanonPVD] = E;
  3040. QualType QTy = PVD->getType()
  3041. .getNonReferenceType()
  3042. .getUnqualifiedType()
  3043. .getCanonicalType();
  3044. const Type *Ty = QTy.getTypePtrOrNull();
  3045. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3046. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3047. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3048. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3049. }
  3050. continue;
  3051. }
  3052. }
  3053. if (isa<CXXThisExpr>(E)) {
  3054. if (AlignedThis) {
  3055. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3056. << 2 << E->getSourceRange();
  3057. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3058. << getOpenMPClauseName(OMPC_aligned);
  3059. }
  3060. AlignedThis = E;
  3061. continue;
  3062. }
  3063. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3064. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3065. }
  3066. // The optional parameter of the aligned clause, alignment, must be a constant
  3067. // positive integer expression. If no optional parameter is specified,
  3068. // implementation-defined default alignments for SIMD instructions on the
  3069. // target platforms are assumed.
  3070. SmallVector<Expr *, 4> NewAligns;
  3071. for (auto *E : Alignments) {
  3072. ExprResult Align;
  3073. if (E)
  3074. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3075. NewAligns.push_back(Align.get());
  3076. }
  3077. // OpenMP [2.8.2, declare simd construct, Description]
  3078. // The linear clause declares one or more list items to be private to a SIMD
  3079. // lane and to have a linear relationship with respect to the iteration space
  3080. // of a loop.
  3081. // The special this pointer can be used as if was one of the arguments to the
  3082. // function in any of the linear, aligned, or uniform clauses.
  3083. // When a linear-step expression is specified in a linear clause it must be
  3084. // either a constant integer expression or an integer-typed parameter that is
  3085. // specified in a uniform clause on the directive.
  3086. llvm::DenseMap<Decl *, Expr *> LinearArgs;
  3087. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3088. auto MI = LinModifiers.begin();
  3089. for (auto *E : Linears) {
  3090. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3091. ++MI;
  3092. E = E->IgnoreParenImpCasts();
  3093. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3094. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3095. auto *CanonPVD = PVD->getCanonicalDecl();
  3096. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3097. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3098. ->getCanonicalDecl() == CanonPVD) {
  3099. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3100. // A list-item cannot appear in more than one linear clause.
  3101. if (LinearArgs.count(CanonPVD) > 0) {
  3102. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3103. << getOpenMPClauseName(OMPC_linear)
  3104. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3105. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3106. diag::note_omp_explicit_dsa)
  3107. << getOpenMPClauseName(OMPC_linear);
  3108. continue;
  3109. }
  3110. // Each argument can appear in at most one uniform or linear clause.
  3111. if (UniformedArgs.count(CanonPVD) > 0) {
  3112. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3113. << getOpenMPClauseName(OMPC_linear)
  3114. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3115. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3116. diag::note_omp_explicit_dsa)
  3117. << getOpenMPClauseName(OMPC_uniform);
  3118. continue;
  3119. }
  3120. LinearArgs[CanonPVD] = E;
  3121. if (E->isValueDependent() || E->isTypeDependent() ||
  3122. E->isInstantiationDependent() ||
  3123. E->containsUnexpandedParameterPack())
  3124. continue;
  3125. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3126. PVD->getOriginalType());
  3127. continue;
  3128. }
  3129. }
  3130. if (isa<CXXThisExpr>(E)) {
  3131. if (UniformedLinearThis) {
  3132. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3133. << getOpenMPClauseName(OMPC_linear)
  3134. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3135. << E->getSourceRange();
  3136. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3137. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3138. : OMPC_linear);
  3139. continue;
  3140. }
  3141. UniformedLinearThis = E;
  3142. if (E->isValueDependent() || E->isTypeDependent() ||
  3143. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3144. continue;
  3145. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3146. E->getType());
  3147. continue;
  3148. }
  3149. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3150. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3151. }
  3152. Expr *Step = nullptr;
  3153. Expr *NewStep = nullptr;
  3154. SmallVector<Expr *, 4> NewSteps;
  3155. for (auto *E : Steps) {
  3156. // Skip the same step expression, it was checked already.
  3157. if (Step == E || !E) {
  3158. NewSteps.push_back(E ? NewStep : nullptr);
  3159. continue;
  3160. }
  3161. Step = E;
  3162. if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3163. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3164. auto *CanonPVD = PVD->getCanonicalDecl();
  3165. if (UniformedArgs.count(CanonPVD) == 0) {
  3166. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3167. << Step->getSourceRange();
  3168. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3169. E->isInstantiationDependent() ||
  3170. E->containsUnexpandedParameterPack() ||
  3171. CanonPVD->getType()->hasIntegerRepresentation())
  3172. NewSteps.push_back(Step);
  3173. else {
  3174. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3175. << Step->getSourceRange();
  3176. }
  3177. continue;
  3178. }
  3179. NewStep = Step;
  3180. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3181. !Step->isInstantiationDependent() &&
  3182. !Step->containsUnexpandedParameterPack()) {
  3183. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3184. .get();
  3185. if (NewStep)
  3186. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3187. }
  3188. NewSteps.push_back(NewStep);
  3189. }
  3190. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3191. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3192. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3193. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3194. const_cast<Expr **>(Linears.data()), Linears.size(),
  3195. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3196. NewSteps.data(), NewSteps.size(), SR);
  3197. ADecl->addAttr(NewAttr);
  3198. return ConvertDeclToDeclGroup(ADecl);
  3199. }
  3200. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3201. Stmt *AStmt,
  3202. SourceLocation StartLoc,
  3203. SourceLocation EndLoc) {
  3204. if (!AStmt)
  3205. return StmtError();
  3206. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3207. // 1.2.2 OpenMP Language Terminology
  3208. // Structured block - An executable statement with a single entry at the
  3209. // top and a single exit at the bottom.
  3210. // The point of exit cannot be a branch out of the structured block.
  3211. // longjmp() and throw() must not violate the entry/exit criteria.
  3212. CS->getCapturedDecl()->setNothrow();
  3213. getCurFunction()->setHasBranchProtectedScope();
  3214. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3215. DSAStack->isCancelRegion());
  3216. }
  3217. namespace {
  3218. /// \brief Helper class for checking canonical form of the OpenMP loops and
  3219. /// extracting iteration space of each loop in the loop nest, that will be used
  3220. /// for IR generation.
  3221. class OpenMPIterationSpaceChecker {
  3222. /// \brief Reference to Sema.
  3223. Sema &SemaRef;
  3224. /// \brief A location for diagnostics (when there is no some better location).
  3225. SourceLocation DefaultLoc;
  3226. /// \brief A location for diagnostics (when increment is not compatible).
  3227. SourceLocation ConditionLoc;
  3228. /// \brief A source location for referring to loop init later.
  3229. SourceRange InitSrcRange;
  3230. /// \brief A source location for referring to condition later.
  3231. SourceRange ConditionSrcRange;
  3232. /// \brief A source location for referring to increment later.
  3233. SourceRange IncrementSrcRange;
  3234. /// \brief Loop variable.
  3235. ValueDecl *LCDecl = nullptr;
  3236. /// \brief Reference to loop variable.
  3237. Expr *LCRef = nullptr;
  3238. /// \brief Lower bound (initializer for the var).
  3239. Expr *LB = nullptr;
  3240. /// \brief Upper bound.
  3241. Expr *UB = nullptr;
  3242. /// \brief Loop step (increment).
  3243. Expr *Step = nullptr;
  3244. /// \brief This flag is true when condition is one of:
  3245. /// Var < UB
  3246. /// Var <= UB
  3247. /// UB > Var
  3248. /// UB >= Var
  3249. bool TestIsLessOp = false;
  3250. /// \brief This flag is true when condition is strict ( < or > ).
  3251. bool TestIsStrictOp = false;
  3252. /// \brief This flag is true when step is subtracted on each iteration.
  3253. bool SubtractStep = false;
  3254. public:
  3255. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3256. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3257. /// \brief Check init-expr for canonical loop form and save loop counter
  3258. /// variable - #Var and its initialization value - #LB.
  3259. bool CheckInit(Stmt *S, bool EmitDiags = true);
  3260. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  3261. /// for less/greater and for strict/non-strict comparison.
  3262. bool CheckCond(Expr *S);
  3263. /// \brief Check incr-expr for canonical loop form and return true if it
  3264. /// does not conform, otherwise save loop step (#Step).
  3265. bool CheckInc(Expr *S);
  3266. /// \brief Return the loop counter variable.
  3267. ValueDecl *GetLoopDecl() const { return LCDecl; }
  3268. /// \brief Return the reference expression to loop counter variable.
  3269. Expr *GetLoopDeclRefExpr() const { return LCRef; }
  3270. /// \brief Source range of the loop init.
  3271. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  3272. /// \brief Source range of the loop condition.
  3273. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  3274. /// \brief Source range of the loop increment.
  3275. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  3276. /// \brief True if the step should be subtracted.
  3277. bool ShouldSubtractStep() const { return SubtractStep; }
  3278. /// \brief Build the expression to calculate the number of iterations.
  3279. Expr *
  3280. BuildNumIterations(Scope *S, const bool LimitedType,
  3281. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3282. /// \brief Build the precondition expression for the loops.
  3283. Expr *BuildPreCond(Scope *S, Expr *Cond,
  3284. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3285. /// \brief Build reference expression to the counter be used for codegen.
  3286. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
  3287. DSAStackTy &DSA) const;
  3288. /// \brief Build reference expression to the private counter be used for
  3289. /// codegen.
  3290. Expr *BuildPrivateCounterVar() const;
  3291. /// \brief Build initialization of the counter be used for codegen.
  3292. Expr *BuildCounterInit() const;
  3293. /// \brief Build step of the counter be used for codegen.
  3294. Expr *BuildCounterStep() const;
  3295. /// \brief Return true if any expression is dependent.
  3296. bool Dependent() const;
  3297. private:
  3298. /// \brief Check the right-hand side of an assignment in the increment
  3299. /// expression.
  3300. bool CheckIncRHS(Expr *RHS);
  3301. /// \brief Helper to set loop counter variable and its initializer.
  3302. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3303. /// \brief Helper to set upper bound.
  3304. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3305. SourceLocation SL);
  3306. /// \brief Helper to set loop increment.
  3307. bool SetStep(Expr *NewStep, bool Subtract);
  3308. };
  3309. bool OpenMPIterationSpaceChecker::Dependent() const {
  3310. if (!LCDecl) {
  3311. assert(!LB && !UB && !Step);
  3312. return false;
  3313. }
  3314. return LCDecl->getType()->isDependentType() ||
  3315. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3316. (Step && Step->isValueDependent());
  3317. }
  3318. bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
  3319. Expr *NewLCRefExpr,
  3320. Expr *NewLB) {
  3321. // State consistency checking to ensure correct usage.
  3322. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3323. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3324. if (!NewLCDecl || !NewLB)
  3325. return true;
  3326. LCDecl = getCanonicalDecl(NewLCDecl);
  3327. LCRef = NewLCRefExpr;
  3328. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3329. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3330. if ((Ctor->isCopyOrMoveConstructor() ||
  3331. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3332. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3333. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3334. LB = NewLB;
  3335. return false;
  3336. }
  3337. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3338. SourceRange SR, SourceLocation SL) {
  3339. // State consistency checking to ensure correct usage.
  3340. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3341. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3342. if (!NewUB)
  3343. return true;
  3344. UB = NewUB;
  3345. TestIsLessOp = LessOp;
  3346. TestIsStrictOp = StrictOp;
  3347. ConditionSrcRange = SR;
  3348. ConditionLoc = SL;
  3349. return false;
  3350. }
  3351. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  3352. // State consistency checking to ensure correct usage.
  3353. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3354. if (!NewStep)
  3355. return true;
  3356. if (!NewStep->isValueDependent()) {
  3357. // Check that the step is integer expression.
  3358. SourceLocation StepLoc = NewStep->getLocStart();
  3359. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3360. StepLoc, getExprAsWritten(NewStep));
  3361. if (Val.isInvalid())
  3362. return true;
  3363. NewStep = Val.get();
  3364. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3365. // If test-expr is of form var relational-op b and relational-op is < or
  3366. // <= then incr-expr must cause var to increase on each iteration of the
  3367. // loop. If test-expr is of form var relational-op b and relational-op is
  3368. // > or >= then incr-expr must cause var to decrease on each iteration of
  3369. // the loop.
  3370. // If test-expr is of form b relational-op var and relational-op is < or
  3371. // <= then incr-expr must cause var to decrease on each iteration of the
  3372. // loop. If test-expr is of form b relational-op var and relational-op is
  3373. // > or >= then incr-expr must cause var to increase on each iteration of
  3374. // the loop.
  3375. llvm::APSInt Result;
  3376. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3377. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3378. bool IsConstNeg =
  3379. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3380. bool IsConstPos =
  3381. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3382. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3383. if (UB && (IsConstZero ||
  3384. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3385. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3386. SemaRef.Diag(NewStep->getExprLoc(),
  3387. diag::err_omp_loop_incr_not_compatible)
  3388. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3389. SemaRef.Diag(ConditionLoc,
  3390. diag::note_omp_loop_cond_requres_compatible_incr)
  3391. << TestIsLessOp << ConditionSrcRange;
  3392. return true;
  3393. }
  3394. if (TestIsLessOp == Subtract) {
  3395. NewStep =
  3396. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3397. .get();
  3398. Subtract = !Subtract;
  3399. }
  3400. }
  3401. Step = NewStep;
  3402. SubtractStep = Subtract;
  3403. return false;
  3404. }
  3405. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  3406. // Check init-expr for canonical loop form and save loop counter
  3407. // variable - #Var and its initialization value - #LB.
  3408. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3409. // var = lb
  3410. // integer-type var = lb
  3411. // random-access-iterator-type var = lb
  3412. // pointer-type var = lb
  3413. //
  3414. if (!S) {
  3415. if (EmitDiags) {
  3416. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3417. }
  3418. return true;
  3419. }
  3420. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3421. if (!ExprTemp->cleanupsHaveSideEffects())
  3422. S = ExprTemp->getSubExpr();
  3423. InitSrcRange = S->getSourceRange();
  3424. if (Expr *E = dyn_cast<Expr>(S))
  3425. S = E->IgnoreParens();
  3426. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3427. if (BO->getOpcode() == BO_Assign) {
  3428. auto *LHS = BO->getLHS()->IgnoreParens();
  3429. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3430. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3431. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3432. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3433. return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3434. }
  3435. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3436. if (ME->isArrow() &&
  3437. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3438. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3439. }
  3440. }
  3441. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3442. if (DS->isSingleDecl()) {
  3443. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3444. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3445. // Accept non-canonical init form here but emit ext. warning.
  3446. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3447. SemaRef.Diag(S->getLocStart(),
  3448. diag::ext_omp_loop_not_canonical_init)
  3449. << S->getSourceRange();
  3450. return SetLCDeclAndLB(Var, nullptr, Var->getInit());
  3451. }
  3452. }
  3453. }
  3454. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3455. if (CE->getOperator() == OO_Equal) {
  3456. auto *LHS = CE->getArg(0);
  3457. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3458. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3459. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3460. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3461. return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3462. }
  3463. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3464. if (ME->isArrow() &&
  3465. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3466. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3467. }
  3468. }
  3469. }
  3470. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3471. return false;
  3472. if (EmitDiags) {
  3473. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3474. << S->getSourceRange();
  3475. }
  3476. return true;
  3477. }
  3478. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3479. /// variable (which may be the loop variable) if possible.
  3480. static const ValueDecl *GetInitLCDecl(Expr *E) {
  3481. if (!E)
  3482. return nullptr;
  3483. E = getExprAsWritten(E);
  3484. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3485. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3486. if ((Ctor->isCopyOrMoveConstructor() ||
  3487. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3488. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3489. E = CE->getArg(0)->IgnoreParenImpCasts();
  3490. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3491. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3492. return getCanonicalDecl(VD);
  3493. }
  3494. if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3495. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3496. return getCanonicalDecl(ME->getMemberDecl());
  3497. return nullptr;
  3498. }
  3499. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  3500. // Check test-expr for canonical form, save upper-bound UB, flags for
  3501. // less/greater and for strict/non-strict comparison.
  3502. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3503. // var relational-op b
  3504. // b relational-op var
  3505. //
  3506. if (!S) {
  3507. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3508. return true;
  3509. }
  3510. S = getExprAsWritten(S);
  3511. SourceLocation CondLoc = S->getLocStart();
  3512. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3513. if (BO->isRelationalOp()) {
  3514. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3515. return SetUB(BO->getRHS(),
  3516. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3517. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3518. BO->getSourceRange(), BO->getOperatorLoc());
  3519. if (GetInitLCDecl(BO->getRHS()) == LCDecl)
  3520. return SetUB(BO->getLHS(),
  3521. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3522. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3523. BO->getSourceRange(), BO->getOperatorLoc());
  3524. }
  3525. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3526. if (CE->getNumArgs() == 2) {
  3527. auto Op = CE->getOperator();
  3528. switch (Op) {
  3529. case OO_Greater:
  3530. case OO_GreaterEqual:
  3531. case OO_Less:
  3532. case OO_LessEqual:
  3533. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3534. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3535. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3536. CE->getOperatorLoc());
  3537. if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3538. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3539. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3540. CE->getOperatorLoc());
  3541. break;
  3542. default:
  3543. break;
  3544. }
  3545. }
  3546. }
  3547. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3548. return false;
  3549. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3550. << S->getSourceRange() << LCDecl;
  3551. return true;
  3552. }
  3553. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  3554. // RHS of canonical loop form increment can be:
  3555. // var + incr
  3556. // incr + var
  3557. // var - incr
  3558. //
  3559. RHS = RHS->IgnoreParenImpCasts();
  3560. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  3561. if (BO->isAdditiveOp()) {
  3562. bool IsAdd = BO->getOpcode() == BO_Add;
  3563. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3564. return SetStep(BO->getRHS(), !IsAdd);
  3565. if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
  3566. return SetStep(BO->getLHS(), false);
  3567. }
  3568. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3569. bool IsAdd = CE->getOperator() == OO_Plus;
  3570. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3571. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3572. return SetStep(CE->getArg(1), !IsAdd);
  3573. if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3574. return SetStep(CE->getArg(0), false);
  3575. }
  3576. }
  3577. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3578. return false;
  3579. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3580. << RHS->getSourceRange() << LCDecl;
  3581. return true;
  3582. }
  3583. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  3584. // Check incr-expr for canonical loop form and return true if it
  3585. // does not conform.
  3586. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3587. // ++var
  3588. // var++
  3589. // --var
  3590. // var--
  3591. // var += incr
  3592. // var -= incr
  3593. // var = var + incr
  3594. // var = incr + var
  3595. // var = var - incr
  3596. //
  3597. if (!S) {
  3598. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  3599. return true;
  3600. }
  3601. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3602. if (!ExprTemp->cleanupsHaveSideEffects())
  3603. S = ExprTemp->getSubExpr();
  3604. IncrementSrcRange = S->getSourceRange();
  3605. S = S->IgnoreParens();
  3606. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  3607. if (UO->isIncrementDecrementOp() &&
  3608. GetInitLCDecl(UO->getSubExpr()) == LCDecl)
  3609. return SetStep(SemaRef
  3610. .ActOnIntegerConstant(UO->getLocStart(),
  3611. (UO->isDecrementOp() ? -1 : 1))
  3612. .get(),
  3613. false);
  3614. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3615. switch (BO->getOpcode()) {
  3616. case BO_AddAssign:
  3617. case BO_SubAssign:
  3618. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3619. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3620. break;
  3621. case BO_Assign:
  3622. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3623. return CheckIncRHS(BO->getRHS());
  3624. break;
  3625. default:
  3626. break;
  3627. }
  3628. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3629. switch (CE->getOperator()) {
  3630. case OO_PlusPlus:
  3631. case OO_MinusMinus:
  3632. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3633. return SetStep(SemaRef
  3634. .ActOnIntegerConstant(
  3635. CE->getLocStart(),
  3636. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3637. .get(),
  3638. false);
  3639. break;
  3640. case OO_PlusEqual:
  3641. case OO_MinusEqual:
  3642. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3643. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3644. break;
  3645. case OO_Equal:
  3646. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3647. return CheckIncRHS(CE->getArg(1));
  3648. break;
  3649. default:
  3650. break;
  3651. }
  3652. }
  3653. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3654. return false;
  3655. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3656. << S->getSourceRange() << LCDecl;
  3657. return true;
  3658. }
  3659. static ExprResult
  3660. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3661. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3662. if (SemaRef.CurContext->isDependentContext())
  3663. return ExprResult(Capture);
  3664. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3665. return SemaRef.PerformImplicitConversion(
  3666. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3667. /*AllowExplicit=*/true);
  3668. auto I = Captures.find(Capture);
  3669. if (I != Captures.end())
  3670. return buildCapture(SemaRef, Capture, I->second);
  3671. DeclRefExpr *Ref = nullptr;
  3672. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3673. Captures[Capture] = Ref;
  3674. return Res;
  3675. }
  3676. /// \brief Build the expression to calculate the number of iterations.
  3677. Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
  3678. Scope *S, const bool LimitedType,
  3679. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3680. ExprResult Diff;
  3681. auto VarType = LCDecl->getType().getNonReferenceType();
  3682. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3683. SemaRef.getLangOpts().CPlusPlus) {
  3684. // Upper - Lower
  3685. auto *UBExpr = TestIsLessOp ? UB : LB;
  3686. auto *LBExpr = TestIsLessOp ? LB : UB;
  3687. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3688. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3689. if (!Upper || !Lower)
  3690. return nullptr;
  3691. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3692. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3693. // BuildBinOp already emitted error, this one is to point user to upper
  3694. // and lower bound, and to tell what is passed to 'operator-'.
  3695. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3696. << Upper->getSourceRange() << Lower->getSourceRange();
  3697. return nullptr;
  3698. }
  3699. }
  3700. if (!Diff.isUsable())
  3701. return nullptr;
  3702. // Upper - Lower [- 1]
  3703. if (TestIsStrictOp)
  3704. Diff = SemaRef.BuildBinOp(
  3705. S, DefaultLoc, BO_Sub, Diff.get(),
  3706. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3707. if (!Diff.isUsable())
  3708. return nullptr;
  3709. // Upper - Lower [- 1] + Step
  3710. auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3711. if (!NewStep.isUsable())
  3712. return nullptr;
  3713. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3714. if (!Diff.isUsable())
  3715. return nullptr;
  3716. // Parentheses (for dumping/debugging purposes only).
  3717. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3718. if (!Diff.isUsable())
  3719. return nullptr;
  3720. // (Upper - Lower [- 1] + Step) / Step
  3721. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3722. if (!Diff.isUsable())
  3723. return nullptr;
  3724. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3725. QualType Type = Diff.get()->getType();
  3726. auto &C = SemaRef.Context;
  3727. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3728. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3729. if (!Type->isIntegerType() || UseVarType) {
  3730. unsigned NewSize =
  3731. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3732. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3733. : Type->hasSignedIntegerRepresentation();
  3734. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3735. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3736. Diff = SemaRef.PerformImplicitConversion(
  3737. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3738. if (!Diff.isUsable())
  3739. return nullptr;
  3740. }
  3741. }
  3742. if (LimitedType) {
  3743. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3744. if (NewSize != C.getTypeSize(Type)) {
  3745. if (NewSize < C.getTypeSize(Type)) {
  3746. assert(NewSize == 64 && "incorrect loop var size");
  3747. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3748. << InitSrcRange << ConditionSrcRange;
  3749. }
  3750. QualType NewType = C.getIntTypeForBitwidth(
  3751. NewSize, Type->hasSignedIntegerRepresentation() ||
  3752. C.getTypeSize(Type) < NewSize);
  3753. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3754. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3755. Sema::AA_Converting, true);
  3756. if (!Diff.isUsable())
  3757. return nullptr;
  3758. }
  3759. }
  3760. }
  3761. return Diff.get();
  3762. }
  3763. Expr *OpenMPIterationSpaceChecker::BuildPreCond(
  3764. Scope *S, Expr *Cond,
  3765. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3766. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3767. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3768. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3769. auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
  3770. auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
  3771. if (!NewLB.isUsable() || !NewUB.isUsable())
  3772. return nullptr;
  3773. auto CondExpr = SemaRef.BuildBinOp(
  3774. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3775. : (TestIsStrictOp ? BO_GT : BO_GE),
  3776. NewLB.get(), NewUB.get());
  3777. if (CondExpr.isUsable()) {
  3778. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  3779. SemaRef.Context.BoolTy))
  3780. CondExpr = SemaRef.PerformImplicitConversion(
  3781. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3782. /*AllowExplicit=*/true);
  3783. }
  3784. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3785. // Otherwise use original loop conditon and evaluate it in runtime.
  3786. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3787. }
  3788. /// \brief Build reference expression to the counter be used for codegen.
  3789. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
  3790. llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  3791. auto *VD = dyn_cast<VarDecl>(LCDecl);
  3792. if (!VD) {
  3793. VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
  3794. auto *Ref = buildDeclRefExpr(
  3795. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  3796. DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  3797. // If the loop control decl is explicitly marked as private, do not mark it
  3798. // as captured again.
  3799. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  3800. Captures.insert(std::make_pair(LCRef, Ref));
  3801. return Ref;
  3802. }
  3803. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  3804. DefaultLoc);
  3805. }
  3806. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3807. if (LCDecl && !LCDecl->isInvalidDecl()) {
  3808. auto Type = LCDecl->getType().getNonReferenceType();
  3809. auto *PrivateVar =
  3810. buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
  3811. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
  3812. if (PrivateVar->isInvalidDecl())
  3813. return nullptr;
  3814. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3815. }
  3816. return nullptr;
  3817. }
  3818. /// \brief Build initialization of the counter to be used for codegen.
  3819. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3820. /// \brief Build step of the counter be used for codegen.
  3821. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3822. /// \brief Iteration space of a single for loop.
  3823. struct LoopIterationSpace final {
  3824. /// \brief Condition of the loop.
  3825. Expr *PreCond = nullptr;
  3826. /// \brief This expression calculates the number of iterations in the loop.
  3827. /// It is always possible to calculate it before starting the loop.
  3828. Expr *NumIterations = nullptr;
  3829. /// \brief The loop counter variable.
  3830. Expr *CounterVar = nullptr;
  3831. /// \brief Private loop counter variable.
  3832. Expr *PrivateCounterVar = nullptr;
  3833. /// \brief This is initializer for the initial value of #CounterVar.
  3834. Expr *CounterInit = nullptr;
  3835. /// \brief This is step for the #CounterVar used to generate its update:
  3836. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3837. Expr *CounterStep = nullptr;
  3838. /// \brief Should step be subtracted?
  3839. bool Subtract = false;
  3840. /// \brief Source range of the loop init.
  3841. SourceRange InitSrcRange;
  3842. /// \brief Source range of the loop condition.
  3843. SourceRange CondSrcRange;
  3844. /// \brief Source range of the loop increment.
  3845. SourceRange IncSrcRange;
  3846. };
  3847. } // namespace
  3848. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3849. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3850. assert(Init && "Expected loop in canonical form.");
  3851. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3852. if (AssociatedLoops > 0 &&
  3853. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3854. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3855. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3856. if (auto *D = ISC.GetLoopDecl()) {
  3857. auto *VD = dyn_cast<VarDecl>(D);
  3858. if (!VD) {
  3859. if (auto *Private = IsOpenMPCapturedDecl(D))
  3860. VD = Private;
  3861. else {
  3862. auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
  3863. /*WithInit=*/false);
  3864. VD = cast<VarDecl>(Ref->getDecl());
  3865. }
  3866. }
  3867. DSAStack->addLoopControlVariable(D, VD);
  3868. }
  3869. }
  3870. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3871. }
  3872. }
  3873. /// \brief Called on a for stmt to check and extract its iteration space
  3874. /// for further processing (such as collapsing).
  3875. static bool CheckOpenMPIterationSpace(
  3876. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3877. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3878. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3879. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3880. LoopIterationSpace &ResultIterSpace,
  3881. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3882. // OpenMP [2.6, Canonical Loop Form]
  3883. // for (init-expr; test-expr; incr-expr) structured-block
  3884. auto *For = dyn_cast_or_null<ForStmt>(S);
  3885. if (!For) {
  3886. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3887. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3888. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3889. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3890. if (NestedLoopCount > 1) {
  3891. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3892. SemaRef.Diag(DSA.getConstructLoc(),
  3893. diag::note_omp_collapse_ordered_expr)
  3894. << 2 << CollapseLoopCountExpr->getSourceRange()
  3895. << OrderedLoopCountExpr->getSourceRange();
  3896. else if (CollapseLoopCountExpr)
  3897. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3898. diag::note_omp_collapse_ordered_expr)
  3899. << 0 << CollapseLoopCountExpr->getSourceRange();
  3900. else
  3901. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3902. diag::note_omp_collapse_ordered_expr)
  3903. << 1 << OrderedLoopCountExpr->getSourceRange();
  3904. }
  3905. return true;
  3906. }
  3907. assert(For->getBody());
  3908. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3909. // Check init.
  3910. auto Init = For->getInit();
  3911. if (ISC.CheckInit(Init))
  3912. return true;
  3913. bool HasErrors = false;
  3914. // Check loop variable's type.
  3915. if (auto *LCDecl = ISC.GetLoopDecl()) {
  3916. auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
  3917. // OpenMP [2.6, Canonical Loop Form]
  3918. // Var is one of the following:
  3919. // A variable of signed or unsigned integer type.
  3920. // For C++, a variable of a random access iterator type.
  3921. // For C, a variable of a pointer type.
  3922. auto VarType = LCDecl->getType().getNonReferenceType();
  3923. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3924. !VarType->isPointerType() &&
  3925. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3926. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3927. << SemaRef.getLangOpts().CPlusPlus;
  3928. HasErrors = true;
  3929. }
  3930. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  3931. // a Construct
  3932. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3933. // parallel for construct is (are) private.
  3934. // The loop iteration variable in the associated for-loop of a simd
  3935. // construct with just one associated for-loop is linear with a
  3936. // constant-linear-step that is the increment of the associated for-loop.
  3937. // Exclude loop var from the list of variables with implicitly defined data
  3938. // sharing attributes.
  3939. VarsWithImplicitDSA.erase(LCDecl);
  3940. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  3941. // in a Construct, C/C++].
  3942. // The loop iteration variable in the associated for-loop of a simd
  3943. // construct with just one associated for-loop may be listed in a linear
  3944. // clause with a constant-linear-step that is the increment of the
  3945. // associated for-loop.
  3946. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3947. // parallel for construct may be listed in a private or lastprivate clause.
  3948. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  3949. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3950. // declared in the loop and it is predetermined as a private.
  3951. auto PredeterminedCKind =
  3952. isOpenMPSimdDirective(DKind)
  3953. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3954. : OMPC_private;
  3955. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3956. DVar.CKind != PredeterminedCKind) ||
  3957. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3958. isOpenMPDistributeDirective(DKind)) &&
  3959. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3960. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3961. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3962. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3963. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3964. << getOpenMPClauseName(PredeterminedCKind);
  3965. if (DVar.RefExpr == nullptr)
  3966. DVar.CKind = PredeterminedCKind;
  3967. ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  3968. HasErrors = true;
  3969. } else if (LoopDeclRefExpr != nullptr) {
  3970. // Make the loop iteration variable private (for worksharing constructs),
  3971. // linear (for simd directives with the only one associated loop) or
  3972. // lastprivate (for simd directives with several collapsed or ordered
  3973. // loops).
  3974. if (DVar.CKind == OMPC_unknown)
  3975. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  3976. [](OpenMPDirectiveKind) -> bool { return true; },
  3977. /*FromParent=*/false);
  3978. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  3979. }
  3980. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3981. // Check test-expr.
  3982. HasErrors |= ISC.CheckCond(For->getCond());
  3983. // Check incr-expr.
  3984. HasErrors |= ISC.CheckInc(For->getInc());
  3985. }
  3986. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3987. return HasErrors;
  3988. // Build the loop's iteration space representation.
  3989. ResultIterSpace.PreCond =
  3990. ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  3991. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  3992. DSA.getCurScope(),
  3993. (isOpenMPWorksharingDirective(DKind) ||
  3994. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  3995. Captures);
  3996. ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
  3997. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  3998. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  3999. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  4000. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  4001. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  4002. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  4003. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  4004. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4005. ResultIterSpace.NumIterations == nullptr ||
  4006. ResultIterSpace.CounterVar == nullptr ||
  4007. ResultIterSpace.PrivateCounterVar == nullptr ||
  4008. ResultIterSpace.CounterInit == nullptr ||
  4009. ResultIterSpace.CounterStep == nullptr);
  4010. return HasErrors;
  4011. }
  4012. /// \brief Build 'VarRef = Start.
  4013. static ExprResult
  4014. BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4015. ExprResult Start,
  4016. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4017. // Build 'VarRef = Start.
  4018. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4019. if (!NewStart.isUsable())
  4020. return ExprError();
  4021. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4022. VarRef.get()->getType())) {
  4023. NewStart = SemaRef.PerformImplicitConversion(
  4024. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4025. /*AllowExplicit=*/true);
  4026. if (!NewStart.isUsable())
  4027. return ExprError();
  4028. }
  4029. auto Init =
  4030. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4031. return Init;
  4032. }
  4033. /// \brief Build 'VarRef = Start + Iter * Step'.
  4034. static ExprResult
  4035. BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
  4036. ExprResult VarRef, ExprResult Start, ExprResult Iter,
  4037. ExprResult Step, bool Subtract,
  4038. llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
  4039. // Add parentheses (for debugging purposes only).
  4040. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4041. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4042. !Step.isUsable())
  4043. return ExprError();
  4044. ExprResult NewStep = Step;
  4045. if (Captures)
  4046. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4047. if (NewStep.isInvalid())
  4048. return ExprError();
  4049. ExprResult Update =
  4050. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4051. if (!Update.isUsable())
  4052. return ExprError();
  4053. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4054. // 'VarRef = Start (+|-) Iter * Step'.
  4055. ExprResult NewStart = Start;
  4056. if (Captures)
  4057. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4058. if (NewStart.isInvalid())
  4059. return ExprError();
  4060. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4061. ExprResult SavedUpdate = Update;
  4062. ExprResult UpdateVal;
  4063. if (VarRef.get()->getType()->isOverloadableType() ||
  4064. NewStart.get()->getType()->isOverloadableType() ||
  4065. Update.get()->getType()->isOverloadableType()) {
  4066. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4067. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4068. Update =
  4069. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4070. if (Update.isUsable()) {
  4071. UpdateVal =
  4072. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4073. VarRef.get(), SavedUpdate.get());
  4074. if (UpdateVal.isUsable()) {
  4075. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4076. UpdateVal.get());
  4077. }
  4078. }
  4079. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4080. }
  4081. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4082. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4083. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4084. NewStart.get(), SavedUpdate.get());
  4085. if (!Update.isUsable())
  4086. return ExprError();
  4087. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4088. VarRef.get()->getType())) {
  4089. Update = SemaRef.PerformImplicitConversion(
  4090. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4091. if (!Update.isUsable())
  4092. return ExprError();
  4093. }
  4094. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4095. }
  4096. return Update;
  4097. }
  4098. /// \brief Convert integer expression \a E to make it have at least \a Bits
  4099. /// bits.
  4100. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4101. if (E == nullptr)
  4102. return ExprError();
  4103. auto &C = SemaRef.Context;
  4104. QualType OldType = E->getType();
  4105. unsigned HasBits = C.getTypeSize(OldType);
  4106. if (HasBits >= Bits)
  4107. return ExprResult(E);
  4108. // OK to convert to signed, because new type has more bits than old.
  4109. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4110. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4111. true);
  4112. }
  4113. /// \brief Check if the given expression \a E is a constant integer that fits
  4114. /// into \a Bits bits.
  4115. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  4116. if (E == nullptr)
  4117. return false;
  4118. llvm::APSInt Result;
  4119. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4120. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4121. return false;
  4122. }
  4123. /// Build preinits statement for the given declarations.
  4124. static Stmt *buildPreInits(ASTContext &Context,
  4125. MutableArrayRef<Decl *> PreInits) {
  4126. if (!PreInits.empty()) {
  4127. return new (Context) DeclStmt(
  4128. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4129. SourceLocation(), SourceLocation());
  4130. }
  4131. return nullptr;
  4132. }
  4133. /// Build preinits statement for the given declarations.
  4134. static Stmt *
  4135. buildPreInits(ASTContext &Context,
  4136. const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4137. if (!Captures.empty()) {
  4138. SmallVector<Decl *, 16> PreInits;
  4139. for (auto &Pair : Captures)
  4140. PreInits.push_back(Pair.second->getDecl());
  4141. return buildPreInits(Context, PreInits);
  4142. }
  4143. return nullptr;
  4144. }
  4145. /// Build postupdate expression for the given list of postupdates expressions.
  4146. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4147. Expr *PostUpdate = nullptr;
  4148. if (!PostUpdates.empty()) {
  4149. for (auto *E : PostUpdates) {
  4150. Expr *ConvE = S.BuildCStyleCastExpr(
  4151. E->getExprLoc(),
  4152. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4153. E->getExprLoc(), E)
  4154. .get();
  4155. PostUpdate = PostUpdate
  4156. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4157. PostUpdate, ConvE)
  4158. .get()
  4159. : ConvE;
  4160. }
  4161. }
  4162. return PostUpdate;
  4163. }
  4164. /// \brief Called on a for stmt to check itself and nested loops (if any).
  4165. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4166. /// number of collapsed loops otherwise.
  4167. static unsigned
  4168. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4169. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4170. DSAStackTy &DSA,
  4171. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  4172. OMPLoopDirective::HelperExprs &Built) {
  4173. unsigned NestedLoopCount = 1;
  4174. if (CollapseLoopCountExpr) {
  4175. // Found 'collapse' clause - calculate collapse number.
  4176. llvm::APSInt Result;
  4177. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4178. NestedLoopCount = Result.getLimitedValue();
  4179. }
  4180. if (OrderedLoopCountExpr) {
  4181. // Found 'ordered' clause - calculate collapse number.
  4182. llvm::APSInt Result;
  4183. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4184. if (Result.getLimitedValue() < NestedLoopCount) {
  4185. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4186. diag::err_omp_wrong_ordered_loop_count)
  4187. << OrderedLoopCountExpr->getSourceRange();
  4188. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4189. diag::note_collapse_loop_count)
  4190. << CollapseLoopCountExpr->getSourceRange();
  4191. }
  4192. NestedLoopCount = Result.getLimitedValue();
  4193. }
  4194. }
  4195. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4196. // 'for simd', etc.).
  4197. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  4198. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4199. IterSpaces.resize(NestedLoopCount);
  4200. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4201. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4202. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  4203. NestedLoopCount, CollapseLoopCountExpr,
  4204. OrderedLoopCountExpr, VarsWithImplicitDSA,
  4205. IterSpaces[Cnt], Captures))
  4206. return 0;
  4207. // Move on to the next nested for loop, or to the loop body.
  4208. // OpenMP [2.8.1, simd construct, Restrictions]
  4209. // All loops associated with the construct must be perfectly nested; that
  4210. // is, there must be no intervening code nor any OpenMP directive between
  4211. // any two loops.
  4212. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4213. }
  4214. Built.clear(/* size */ NestedLoopCount);
  4215. if (SemaRef.CurContext->isDependentContext())
  4216. return NestedLoopCount;
  4217. // An example of what is generated for the following code:
  4218. //
  4219. // #pragma omp simd collapse(2) ordered(2)
  4220. // for (i = 0; i < NI; ++i)
  4221. // for (k = 0; k < NK; ++k)
  4222. // for (j = J0; j < NJ; j+=2) {
  4223. // <loop body>
  4224. // }
  4225. //
  4226. // We generate the code below.
  4227. // Note: the loop body may be outlined in CodeGen.
  4228. // Note: some counters may be C++ classes, operator- is used to find number of
  4229. // iterations and operator+= to calculate counter value.
  4230. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4231. // or i64 is currently supported).
  4232. //
  4233. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4234. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4235. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4236. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4237. // // similar updates for vars in clauses (e.g. 'linear')
  4238. // <loop body (using local i and j)>
  4239. // }
  4240. // i = NI; // assign final values of counters
  4241. // j = NJ;
  4242. //
  4243. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4244. // the iteration counts of the collapsed for loops.
  4245. // Precondition tests if there is at least one iteration (all conditions are
  4246. // true).
  4247. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4248. auto N0 = IterSpaces[0].NumIterations;
  4249. ExprResult LastIteration32 = WidenIterationCount(
  4250. 32 /* Bits */, SemaRef
  4251. .PerformImplicitConversion(
  4252. N0->IgnoreImpCasts(), N0->getType(),
  4253. Sema::AA_Converting, /*AllowExplicit=*/true)
  4254. .get(),
  4255. SemaRef);
  4256. ExprResult LastIteration64 = WidenIterationCount(
  4257. 64 /* Bits */, SemaRef
  4258. .PerformImplicitConversion(
  4259. N0->IgnoreImpCasts(), N0->getType(),
  4260. Sema::AA_Converting, /*AllowExplicit=*/true)
  4261. .get(),
  4262. SemaRef);
  4263. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4264. return NestedLoopCount;
  4265. auto &C = SemaRef.Context;
  4266. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4267. Scope *CurScope = DSA.getCurScope();
  4268. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4269. if (PreCond.isUsable()) {
  4270. PreCond =
  4271. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4272. PreCond.get(), IterSpaces[Cnt].PreCond);
  4273. }
  4274. auto N = IterSpaces[Cnt].NumIterations;
  4275. SourceLocation Loc = N->getExprLoc();
  4276. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4277. if (LastIteration32.isUsable())
  4278. LastIteration32 = SemaRef.BuildBinOp(
  4279. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4280. SemaRef
  4281. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4282. Sema::AA_Converting,
  4283. /*AllowExplicit=*/true)
  4284. .get());
  4285. if (LastIteration64.isUsable())
  4286. LastIteration64 = SemaRef.BuildBinOp(
  4287. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4288. SemaRef
  4289. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4290. Sema::AA_Converting,
  4291. /*AllowExplicit=*/true)
  4292. .get());
  4293. }
  4294. // Choose either the 32-bit or 64-bit version.
  4295. ExprResult LastIteration = LastIteration64;
  4296. if (LastIteration32.isUsable() &&
  4297. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4298. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4299. FitsInto(
  4300. 32 /* Bits */,
  4301. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4302. LastIteration64.get(), SemaRef)))
  4303. LastIteration = LastIteration32;
  4304. QualType VType = LastIteration.get()->getType();
  4305. QualType RealVType = VType;
  4306. QualType StrideVType = VType;
  4307. if (isOpenMPTaskLoopDirective(DKind)) {
  4308. VType =
  4309. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4310. StrideVType =
  4311. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4312. }
  4313. if (!LastIteration.isUsable())
  4314. return 0;
  4315. // Save the number of iterations.
  4316. ExprResult NumIterations = LastIteration;
  4317. {
  4318. LastIteration = SemaRef.BuildBinOp(
  4319. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4320. LastIteration.get(),
  4321. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4322. if (!LastIteration.isUsable())
  4323. return 0;
  4324. }
  4325. // Calculate the last iteration number beforehand instead of doing this on
  4326. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4327. llvm::APSInt Result;
  4328. bool IsConstant =
  4329. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4330. ExprResult CalcLastIteration;
  4331. if (!IsConstant) {
  4332. ExprResult SaveRef =
  4333. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4334. LastIteration = SaveRef;
  4335. // Prepare SaveRef + 1.
  4336. NumIterations = SemaRef.BuildBinOp(
  4337. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4338. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4339. if (!NumIterations.isUsable())
  4340. return 0;
  4341. }
  4342. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4343. // Build variables passed into runtime, necessary for worksharing directives.
  4344. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4345. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4346. isOpenMPDistributeDirective(DKind)) {
  4347. // Lower bound variable, initialized with zero.
  4348. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4349. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4350. SemaRef.AddInitializerToDecl(LBDecl,
  4351. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4352. /*DirectInit*/ false);
  4353. // Upper bound variable, initialized with last iteration number.
  4354. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4355. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4356. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4357. /*DirectInit*/ false);
  4358. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4359. // This will be used to implement clause 'lastprivate'.
  4360. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4361. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4362. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4363. SemaRef.AddInitializerToDecl(ILDecl,
  4364. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4365. /*DirectInit*/ false);
  4366. // Stride variable returned by runtime (we initialize it to 1 by default).
  4367. VarDecl *STDecl =
  4368. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4369. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4370. SemaRef.AddInitializerToDecl(STDecl,
  4371. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4372. /*DirectInit*/ false);
  4373. // Build expression: UB = min(UB, LastIteration)
  4374. // It is necessary for CodeGen of directives with static scheduling.
  4375. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4376. UB.get(), LastIteration.get());
  4377. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4378. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  4379. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4380. CondOp.get());
  4381. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4382. // If we have a combined directive that combines 'distribute', 'for' or
  4383. // 'simd' we need to be able to access the bounds of the schedule of the
  4384. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4385. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4386. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4387. // Lower bound variable, initialized with zero.
  4388. VarDecl *CombLBDecl =
  4389. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4390. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4391. SemaRef.AddInitializerToDecl(
  4392. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4393. /*DirectInit*/ false);
  4394. // Upper bound variable, initialized with last iteration number.
  4395. VarDecl *CombUBDecl =
  4396. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4397. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4398. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4399. /*DirectInit*/ false);
  4400. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4401. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4402. ExprResult CombCondOp =
  4403. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4404. LastIteration.get(), CombUB.get());
  4405. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4406. CombCondOp.get());
  4407. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4408. auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4409. // We expect to have at least 2 more parameters than the 'parallel'
  4410. // directive does - the lower and upper bounds of the previous schedule.
  4411. assert(CD->getNumParams() >= 4 &&
  4412. "Unexpected number of parameters in loop combined directive");
  4413. // Set the proper type for the bounds given what we learned from the
  4414. // enclosed loops.
  4415. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4416. auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4417. // Previous lower and upper bounds are obtained from the region
  4418. // parameters.
  4419. PrevLB =
  4420. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  4421. PrevUB =
  4422. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  4423. }
  4424. }
  4425. // Build the iteration variable and its initialization before loop.
  4426. ExprResult IV;
  4427. ExprResult Init, CombInit;
  4428. {
  4429. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  4430. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  4431. Expr *RHS =
  4432. (isOpenMPWorksharingDirective(DKind) ||
  4433. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4434. ? LB.get()
  4435. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4436. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  4437. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  4438. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4439. Expr *CombRHS =
  4440. (isOpenMPWorksharingDirective(DKind) ||
  4441. isOpenMPTaskLoopDirective(DKind) ||
  4442. isOpenMPDistributeDirective(DKind))
  4443. ? CombLB.get()
  4444. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4445. CombInit =
  4446. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  4447. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  4448. }
  4449. }
  4450. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  4451. SourceLocation CondLoc;
  4452. ExprResult Cond =
  4453. (isOpenMPWorksharingDirective(DKind) ||
  4454. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4455. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  4456. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  4457. NumIterations.get());
  4458. ExprResult CombCond;
  4459. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4460. CombCond =
  4461. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  4462. }
  4463. // Loop increment (IV = IV + 1)
  4464. SourceLocation IncLoc;
  4465. ExprResult Inc =
  4466. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  4467. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  4468. if (!Inc.isUsable())
  4469. return 0;
  4470. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  4471. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  4472. if (!Inc.isUsable())
  4473. return 0;
  4474. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  4475. // Used for directives with static scheduling.
  4476. // In combined construct, add combined version that use CombLB and CombUB
  4477. // base variables for the update
  4478. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  4479. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4480. isOpenMPDistributeDirective(DKind)) {
  4481. // LB + ST
  4482. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  4483. if (!NextLB.isUsable())
  4484. return 0;
  4485. // LB = LB + ST
  4486. NextLB =
  4487. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4488. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4489. if (!NextLB.isUsable())
  4490. return 0;
  4491. // UB + ST
  4492. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4493. if (!NextUB.isUsable())
  4494. return 0;
  4495. // UB = UB + ST
  4496. NextUB =
  4497. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4498. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4499. if (!NextUB.isUsable())
  4500. return 0;
  4501. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4502. CombNextLB =
  4503. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  4504. if (!NextLB.isUsable())
  4505. return 0;
  4506. // LB = LB + ST
  4507. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  4508. CombNextLB.get());
  4509. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  4510. if (!CombNextLB.isUsable())
  4511. return 0;
  4512. // UB + ST
  4513. CombNextUB =
  4514. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  4515. if (!CombNextUB.isUsable())
  4516. return 0;
  4517. // UB = UB + ST
  4518. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  4519. CombNextUB.get());
  4520. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  4521. if (!CombNextUB.isUsable())
  4522. return 0;
  4523. }
  4524. }
  4525. // Create increment expression for distribute loop when combined in a same
  4526. // directive with for as IV = IV + ST; ensure upper bound expression based
  4527. // on PrevUB instead of NumIterations - used to implement 'for' when found
  4528. // in combination with 'distribute', like in 'distribute parallel for'
  4529. SourceLocation DistIncLoc;
  4530. ExprResult DistCond, DistInc, PrevEUB;
  4531. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4532. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  4533. assert(DistCond.isUsable() && "distribute cond expr was not built");
  4534. DistInc =
  4535. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  4536. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4537. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  4538. DistInc.get());
  4539. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  4540. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4541. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  4542. // construct
  4543. SourceLocation DistEUBLoc;
  4544. ExprResult IsUBGreater =
  4545. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  4546. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4547. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  4548. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  4549. CondOp.get());
  4550. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  4551. }
  4552. // Build updates and final values of the loop counters.
  4553. bool HasErrors = false;
  4554. Built.Counters.resize(NestedLoopCount);
  4555. Built.Inits.resize(NestedLoopCount);
  4556. Built.Updates.resize(NestedLoopCount);
  4557. Built.Finals.resize(NestedLoopCount);
  4558. SmallVector<Expr *, 4> LoopMultipliers;
  4559. {
  4560. ExprResult Div;
  4561. // Go from inner nested loop to outer.
  4562. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4563. LoopIterationSpace &IS = IterSpaces[Cnt];
  4564. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4565. // Build: Iter = (IV / Div) % IS.NumIters
  4566. // where Div is product of previous iterations' IS.NumIters.
  4567. ExprResult Iter;
  4568. if (Div.isUsable()) {
  4569. Iter =
  4570. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4571. } else {
  4572. Iter = IV;
  4573. assert((Cnt == (int)NestedLoopCount - 1) &&
  4574. "unusable div expected on first iteration only");
  4575. }
  4576. if (Cnt != 0 && Iter.isUsable())
  4577. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4578. IS.NumIterations);
  4579. if (!Iter.isUsable()) {
  4580. HasErrors = true;
  4581. break;
  4582. }
  4583. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4584. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  4585. auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
  4586. IS.CounterVar->getExprLoc(),
  4587. /*RefersToCapture=*/true);
  4588. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4589. IS.CounterInit, Captures);
  4590. if (!Init.isUsable()) {
  4591. HasErrors = true;
  4592. break;
  4593. }
  4594. ExprResult Update = BuildCounterUpdate(
  4595. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  4596. IS.CounterStep, IS.Subtract, &Captures);
  4597. if (!Update.isUsable()) {
  4598. HasErrors = true;
  4599. break;
  4600. }
  4601. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4602. ExprResult Final = BuildCounterUpdate(
  4603. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4604. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  4605. if (!Final.isUsable()) {
  4606. HasErrors = true;
  4607. break;
  4608. }
  4609. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4610. if (Cnt != 0) {
  4611. if (Div.isUnset())
  4612. Div = IS.NumIterations;
  4613. else
  4614. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4615. IS.NumIterations);
  4616. // Add parentheses (for debugging purposes only).
  4617. if (Div.isUsable())
  4618. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  4619. if (!Div.isUsable()) {
  4620. HasErrors = true;
  4621. break;
  4622. }
  4623. LoopMultipliers.push_back(Div.get());
  4624. }
  4625. if (!Update.isUsable() || !Final.isUsable()) {
  4626. HasErrors = true;
  4627. break;
  4628. }
  4629. // Save results
  4630. Built.Counters[Cnt] = IS.CounterVar;
  4631. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4632. Built.Inits[Cnt] = Init.get();
  4633. Built.Updates[Cnt] = Update.get();
  4634. Built.Finals[Cnt] = Final.get();
  4635. }
  4636. }
  4637. if (HasErrors)
  4638. return 0;
  4639. // Save results
  4640. Built.IterationVarRef = IV.get();
  4641. Built.LastIteration = LastIteration.get();
  4642. Built.NumIterations = NumIterations.get();
  4643. Built.CalcLastIteration =
  4644. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4645. Built.PreCond = PreCond.get();
  4646. Built.PreInits = buildPreInits(C, Captures);
  4647. Built.Cond = Cond.get();
  4648. Built.Init = Init.get();
  4649. Built.Inc = Inc.get();
  4650. Built.LB = LB.get();
  4651. Built.UB = UB.get();
  4652. Built.IL = IL.get();
  4653. Built.ST = ST.get();
  4654. Built.EUB = EUB.get();
  4655. Built.NLB = NextLB.get();
  4656. Built.NUB = NextUB.get();
  4657. Built.PrevLB = PrevLB.get();
  4658. Built.PrevUB = PrevUB.get();
  4659. Built.DistInc = DistInc.get();
  4660. Built.PrevEUB = PrevEUB.get();
  4661. Built.DistCombinedFields.LB = CombLB.get();
  4662. Built.DistCombinedFields.UB = CombUB.get();
  4663. Built.DistCombinedFields.EUB = CombEUB.get();
  4664. Built.DistCombinedFields.Init = CombInit.get();
  4665. Built.DistCombinedFields.Cond = CombCond.get();
  4666. Built.DistCombinedFields.NLB = CombNextLB.get();
  4667. Built.DistCombinedFields.NUB = CombNextUB.get();
  4668. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  4669. // Fill data for doacross depend clauses.
  4670. for (auto Pair : DSA.getDoacrossDependClauses()) {
  4671. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4672. Pair.first->setCounterValue(CounterVal);
  4673. else {
  4674. if (NestedLoopCount != Pair.second.size() ||
  4675. NestedLoopCount != LoopMultipliers.size() + 1) {
  4676. // Erroneous case - clause has some problems.
  4677. Pair.first->setCounterValue(CounterVal);
  4678. continue;
  4679. }
  4680. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  4681. auto I = Pair.second.rbegin();
  4682. auto IS = IterSpaces.rbegin();
  4683. auto ILM = LoopMultipliers.rbegin();
  4684. Expr *UpCounterVal = CounterVal;
  4685. Expr *Multiplier = nullptr;
  4686. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4687. if (I->first) {
  4688. assert(IS->CounterStep);
  4689. Expr *NormalizedOffset =
  4690. SemaRef
  4691. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  4692. I->first, IS->CounterStep)
  4693. .get();
  4694. if (Multiplier) {
  4695. NormalizedOffset =
  4696. SemaRef
  4697. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  4698. NormalizedOffset, Multiplier)
  4699. .get();
  4700. }
  4701. assert(I->second == OO_Plus || I->second == OO_Minus);
  4702. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  4703. UpCounterVal = SemaRef
  4704. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  4705. UpCounterVal, NormalizedOffset)
  4706. .get();
  4707. }
  4708. Multiplier = *ILM;
  4709. ++I;
  4710. ++IS;
  4711. ++ILM;
  4712. }
  4713. Pair.first->setCounterValue(UpCounterVal);
  4714. }
  4715. }
  4716. return NestedLoopCount;
  4717. }
  4718. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4719. auto CollapseClauses =
  4720. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4721. if (CollapseClauses.begin() != CollapseClauses.end())
  4722. return (*CollapseClauses.begin())->getNumForLoops();
  4723. return nullptr;
  4724. }
  4725. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4726. auto OrderedClauses =
  4727. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4728. if (OrderedClauses.begin() != OrderedClauses.end())
  4729. return (*OrderedClauses.begin())->getNumForLoops();
  4730. return nullptr;
  4731. }
  4732. static bool checkSimdlenSafelenSpecified(Sema &S,
  4733. const ArrayRef<OMPClause *> Clauses) {
  4734. OMPSafelenClause *Safelen = nullptr;
  4735. OMPSimdlenClause *Simdlen = nullptr;
  4736. for (auto *Clause : Clauses) {
  4737. if (Clause->getClauseKind() == OMPC_safelen)
  4738. Safelen = cast<OMPSafelenClause>(Clause);
  4739. else if (Clause->getClauseKind() == OMPC_simdlen)
  4740. Simdlen = cast<OMPSimdlenClause>(Clause);
  4741. if (Safelen && Simdlen)
  4742. break;
  4743. }
  4744. if (Simdlen && Safelen) {
  4745. llvm::APSInt SimdlenRes, SafelenRes;
  4746. auto SimdlenLength = Simdlen->getSimdlen();
  4747. auto SafelenLength = Safelen->getSafelen();
  4748. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4749. SimdlenLength->isInstantiationDependent() ||
  4750. SimdlenLength->containsUnexpandedParameterPack())
  4751. return false;
  4752. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4753. SafelenLength->isInstantiationDependent() ||
  4754. SafelenLength->containsUnexpandedParameterPack())
  4755. return false;
  4756. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  4757. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  4758. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  4759. // If both simdlen and safelen clauses are specified, the value of the
  4760. // simdlen parameter must be less than or equal to the value of the safelen
  4761. // parameter.
  4762. if (SimdlenRes > SafelenRes) {
  4763. S.Diag(SimdlenLength->getExprLoc(),
  4764. diag::err_omp_wrong_simdlen_safelen_values)
  4765. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  4766. return true;
  4767. }
  4768. }
  4769. return false;
  4770. }
  4771. StmtResult Sema::ActOnOpenMPSimdDirective(
  4772. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4773. SourceLocation EndLoc,
  4774. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4775. if (!AStmt)
  4776. return StmtError();
  4777. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4778. OMPLoopDirective::HelperExprs B;
  4779. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4780. // define the nested loops number.
  4781. unsigned NestedLoopCount = CheckOpenMPLoop(
  4782. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4783. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4784. if (NestedLoopCount == 0)
  4785. return StmtError();
  4786. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4787. "omp simd loop exprs were not built");
  4788. if (!CurContext->isDependentContext()) {
  4789. // Finalize the clauses that need pre-built expressions for CodeGen.
  4790. for (auto C : Clauses) {
  4791. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4792. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4793. B.NumIterations, *this, CurScope,
  4794. DSAStack))
  4795. return StmtError();
  4796. }
  4797. }
  4798. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4799. return StmtError();
  4800. getCurFunction()->setHasBranchProtectedScope();
  4801. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4802. Clauses, AStmt, B);
  4803. }
  4804. StmtResult Sema::ActOnOpenMPForDirective(
  4805. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4806. SourceLocation EndLoc,
  4807. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4808. if (!AStmt)
  4809. return StmtError();
  4810. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4811. OMPLoopDirective::HelperExprs B;
  4812. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4813. // define the nested loops number.
  4814. unsigned NestedLoopCount = CheckOpenMPLoop(
  4815. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4816. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4817. if (NestedLoopCount == 0)
  4818. return StmtError();
  4819. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4820. "omp for loop exprs were not built");
  4821. if (!CurContext->isDependentContext()) {
  4822. // Finalize the clauses that need pre-built expressions for CodeGen.
  4823. for (auto C : Clauses) {
  4824. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4825. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4826. B.NumIterations, *this, CurScope,
  4827. DSAStack))
  4828. return StmtError();
  4829. }
  4830. }
  4831. getCurFunction()->setHasBranchProtectedScope();
  4832. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4833. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4834. }
  4835. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4836. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4837. SourceLocation EndLoc,
  4838. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4839. if (!AStmt)
  4840. return StmtError();
  4841. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4842. OMPLoopDirective::HelperExprs B;
  4843. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4844. // define the nested loops number.
  4845. unsigned NestedLoopCount =
  4846. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4847. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4848. VarsWithImplicitDSA, B);
  4849. if (NestedLoopCount == 0)
  4850. return StmtError();
  4851. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4852. "omp for simd loop exprs were not built");
  4853. if (!CurContext->isDependentContext()) {
  4854. // Finalize the clauses that need pre-built expressions for CodeGen.
  4855. for (auto C : Clauses) {
  4856. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4857. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4858. B.NumIterations, *this, CurScope,
  4859. DSAStack))
  4860. return StmtError();
  4861. }
  4862. }
  4863. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4864. return StmtError();
  4865. getCurFunction()->setHasBranchProtectedScope();
  4866. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4867. Clauses, AStmt, B);
  4868. }
  4869. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4870. Stmt *AStmt,
  4871. SourceLocation StartLoc,
  4872. SourceLocation EndLoc) {
  4873. if (!AStmt)
  4874. return StmtError();
  4875. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4876. auto BaseStmt = AStmt;
  4877. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4878. BaseStmt = CS->getCapturedStmt();
  4879. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4880. auto S = C->children();
  4881. if (S.begin() == S.end())
  4882. return StmtError();
  4883. // All associated statements must be '#pragma omp section' except for
  4884. // the first one.
  4885. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4886. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4887. if (SectionStmt)
  4888. Diag(SectionStmt->getLocStart(),
  4889. diag::err_omp_sections_substmt_not_section);
  4890. return StmtError();
  4891. }
  4892. cast<OMPSectionDirective>(SectionStmt)
  4893. ->setHasCancel(DSAStack->isCancelRegion());
  4894. }
  4895. } else {
  4896. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4897. return StmtError();
  4898. }
  4899. getCurFunction()->setHasBranchProtectedScope();
  4900. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4901. DSAStack->isCancelRegion());
  4902. }
  4903. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4904. SourceLocation StartLoc,
  4905. SourceLocation EndLoc) {
  4906. if (!AStmt)
  4907. return StmtError();
  4908. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4909. getCurFunction()->setHasBranchProtectedScope();
  4910. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4911. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4912. DSAStack->isCancelRegion());
  4913. }
  4914. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4915. Stmt *AStmt,
  4916. SourceLocation StartLoc,
  4917. SourceLocation EndLoc) {
  4918. if (!AStmt)
  4919. return StmtError();
  4920. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4921. getCurFunction()->setHasBranchProtectedScope();
  4922. // OpenMP [2.7.3, single Construct, Restrictions]
  4923. // The copyprivate clause must not be used with the nowait clause.
  4924. OMPClause *Nowait = nullptr;
  4925. OMPClause *Copyprivate = nullptr;
  4926. for (auto *Clause : Clauses) {
  4927. if (Clause->getClauseKind() == OMPC_nowait)
  4928. Nowait = Clause;
  4929. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4930. Copyprivate = Clause;
  4931. if (Copyprivate && Nowait) {
  4932. Diag(Copyprivate->getLocStart(),
  4933. diag::err_omp_single_copyprivate_with_nowait);
  4934. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4935. return StmtError();
  4936. }
  4937. }
  4938. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4939. }
  4940. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4941. SourceLocation StartLoc,
  4942. SourceLocation EndLoc) {
  4943. if (!AStmt)
  4944. return StmtError();
  4945. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4946. getCurFunction()->setHasBranchProtectedScope();
  4947. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4948. }
  4949. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4950. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4951. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4952. if (!AStmt)
  4953. return StmtError();
  4954. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4955. bool ErrorFound = false;
  4956. llvm::APSInt Hint;
  4957. SourceLocation HintLoc;
  4958. bool DependentHint = false;
  4959. for (auto *C : Clauses) {
  4960. if (C->getClauseKind() == OMPC_hint) {
  4961. if (!DirName.getName()) {
  4962. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4963. ErrorFound = true;
  4964. }
  4965. Expr *E = cast<OMPHintClause>(C)->getHint();
  4966. if (E->isTypeDependent() || E->isValueDependent() ||
  4967. E->isInstantiationDependent())
  4968. DependentHint = true;
  4969. else {
  4970. Hint = E->EvaluateKnownConstInt(Context);
  4971. HintLoc = C->getLocStart();
  4972. }
  4973. }
  4974. }
  4975. if (ErrorFound)
  4976. return StmtError();
  4977. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4978. if (Pair.first && DirName.getName() && !DependentHint) {
  4979. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4980. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4981. if (HintLoc.isValid()) {
  4982. Diag(HintLoc, diag::note_omp_critical_hint_here)
  4983. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  4984. } else
  4985. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  4986. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  4987. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  4988. << 1
  4989. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  4990. /*Radix=*/10, /*Signed=*/false);
  4991. } else
  4992. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  4993. }
  4994. }
  4995. getCurFunction()->setHasBranchProtectedScope();
  4996. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  4997. Clauses, AStmt);
  4998. if (!Pair.first && DirName.getName() && !DependentHint)
  4999. DSAStack->addCriticalWithHint(Dir, Hint);
  5000. return Dir;
  5001. }
  5002. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5003. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5004. SourceLocation EndLoc,
  5005. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5006. if (!AStmt)
  5007. return StmtError();
  5008. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5009. // 1.2.2 OpenMP Language Terminology
  5010. // Structured block - An executable statement with a single entry at the
  5011. // top and a single exit at the bottom.
  5012. // The point of exit cannot be a branch out of the structured block.
  5013. // longjmp() and throw() must not violate the entry/exit criteria.
  5014. CS->getCapturedDecl()->setNothrow();
  5015. OMPLoopDirective::HelperExprs B;
  5016. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5017. // define the nested loops number.
  5018. unsigned NestedLoopCount =
  5019. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5020. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5021. VarsWithImplicitDSA, B);
  5022. if (NestedLoopCount == 0)
  5023. return StmtError();
  5024. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5025. "omp parallel for loop exprs were not built");
  5026. if (!CurContext->isDependentContext()) {
  5027. // Finalize the clauses that need pre-built expressions for CodeGen.
  5028. for (auto C : Clauses) {
  5029. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5030. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5031. B.NumIterations, *this, CurScope,
  5032. DSAStack))
  5033. return StmtError();
  5034. }
  5035. }
  5036. getCurFunction()->setHasBranchProtectedScope();
  5037. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5038. NestedLoopCount, Clauses, AStmt, B,
  5039. DSAStack->isCancelRegion());
  5040. }
  5041. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5042. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5043. SourceLocation EndLoc,
  5044. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5045. if (!AStmt)
  5046. return StmtError();
  5047. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5048. // 1.2.2 OpenMP Language Terminology
  5049. // Structured block - An executable statement with a single entry at the
  5050. // top and a single exit at the bottom.
  5051. // The point of exit cannot be a branch out of the structured block.
  5052. // longjmp() and throw() must not violate the entry/exit criteria.
  5053. CS->getCapturedDecl()->setNothrow();
  5054. OMPLoopDirective::HelperExprs B;
  5055. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5056. // define the nested loops number.
  5057. unsigned NestedLoopCount =
  5058. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5059. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5060. VarsWithImplicitDSA, B);
  5061. if (NestedLoopCount == 0)
  5062. return StmtError();
  5063. if (!CurContext->isDependentContext()) {
  5064. // Finalize the clauses that need pre-built expressions for CodeGen.
  5065. for (auto C : Clauses) {
  5066. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5067. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5068. B.NumIterations, *this, CurScope,
  5069. DSAStack))
  5070. return StmtError();
  5071. }
  5072. }
  5073. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5074. return StmtError();
  5075. getCurFunction()->setHasBranchProtectedScope();
  5076. return OMPParallelForSimdDirective::Create(
  5077. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5078. }
  5079. StmtResult
  5080. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5081. Stmt *AStmt, SourceLocation StartLoc,
  5082. SourceLocation EndLoc) {
  5083. if (!AStmt)
  5084. return StmtError();
  5085. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5086. auto BaseStmt = AStmt;
  5087. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5088. BaseStmt = CS->getCapturedStmt();
  5089. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5090. auto S = C->children();
  5091. if (S.begin() == S.end())
  5092. return StmtError();
  5093. // All associated statements must be '#pragma omp section' except for
  5094. // the first one.
  5095. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5096. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5097. if (SectionStmt)
  5098. Diag(SectionStmt->getLocStart(),
  5099. diag::err_omp_parallel_sections_substmt_not_section);
  5100. return StmtError();
  5101. }
  5102. cast<OMPSectionDirective>(SectionStmt)
  5103. ->setHasCancel(DSAStack->isCancelRegion());
  5104. }
  5105. } else {
  5106. Diag(AStmt->getLocStart(),
  5107. diag::err_omp_parallel_sections_not_compound_stmt);
  5108. return StmtError();
  5109. }
  5110. getCurFunction()->setHasBranchProtectedScope();
  5111. return OMPParallelSectionsDirective::Create(
  5112. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5113. }
  5114. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5115. Stmt *AStmt, SourceLocation StartLoc,
  5116. SourceLocation EndLoc) {
  5117. if (!AStmt)
  5118. return StmtError();
  5119. auto *CS = cast<CapturedStmt>(AStmt);
  5120. // 1.2.2 OpenMP Language Terminology
  5121. // Structured block - An executable statement with a single entry at the
  5122. // top and a single exit at the bottom.
  5123. // The point of exit cannot be a branch out of the structured block.
  5124. // longjmp() and throw() must not violate the entry/exit criteria.
  5125. CS->getCapturedDecl()->setNothrow();
  5126. getCurFunction()->setHasBranchProtectedScope();
  5127. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5128. DSAStack->isCancelRegion());
  5129. }
  5130. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5131. SourceLocation EndLoc) {
  5132. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5133. }
  5134. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5135. SourceLocation EndLoc) {
  5136. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5137. }
  5138. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5139. SourceLocation EndLoc) {
  5140. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5141. }
  5142. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5143. Stmt *AStmt,
  5144. SourceLocation StartLoc,
  5145. SourceLocation EndLoc) {
  5146. if (!AStmt)
  5147. return StmtError();
  5148. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5149. getCurFunction()->setHasBranchProtectedScope();
  5150. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5151. AStmt,
  5152. DSAStack->getTaskgroupReductionRef());
  5153. }
  5154. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5155. SourceLocation StartLoc,
  5156. SourceLocation EndLoc) {
  5157. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5158. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5159. }
  5160. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5161. Stmt *AStmt,
  5162. SourceLocation StartLoc,
  5163. SourceLocation EndLoc) {
  5164. OMPClause *DependFound = nullptr;
  5165. OMPClause *DependSourceClause = nullptr;
  5166. OMPClause *DependSinkClause = nullptr;
  5167. bool ErrorFound = false;
  5168. OMPThreadsClause *TC = nullptr;
  5169. OMPSIMDClause *SC = nullptr;
  5170. for (auto *C : Clauses) {
  5171. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5172. DependFound = C;
  5173. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5174. if (DependSourceClause) {
  5175. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  5176. << getOpenMPDirectiveName(OMPD_ordered)
  5177. << getOpenMPClauseName(OMPC_depend) << 2;
  5178. ErrorFound = true;
  5179. } else
  5180. DependSourceClause = C;
  5181. if (DependSinkClause) {
  5182. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5183. << 0;
  5184. ErrorFound = true;
  5185. }
  5186. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5187. if (DependSourceClause) {
  5188. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5189. << 1;
  5190. ErrorFound = true;
  5191. }
  5192. DependSinkClause = C;
  5193. }
  5194. } else if (C->getClauseKind() == OMPC_threads)
  5195. TC = cast<OMPThreadsClause>(C);
  5196. else if (C->getClauseKind() == OMPC_simd)
  5197. SC = cast<OMPSIMDClause>(C);
  5198. }
  5199. if (!ErrorFound && !SC &&
  5200. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5201. // OpenMP [2.8.1,simd Construct, Restrictions]
  5202. // An ordered construct with the simd clause is the only OpenMP construct
  5203. // that can appear in the simd region.
  5204. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5205. ErrorFound = true;
  5206. } else if (DependFound && (TC || SC)) {
  5207. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  5208. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5209. ErrorFound = true;
  5210. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  5211. Diag(DependFound->getLocStart(),
  5212. diag::err_omp_ordered_directive_without_param);
  5213. ErrorFound = true;
  5214. } else if (TC || Clauses.empty()) {
  5215. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  5216. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  5217. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5218. << (TC != nullptr);
  5219. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  5220. ErrorFound = true;
  5221. }
  5222. }
  5223. if ((!AStmt && !DependFound) || ErrorFound)
  5224. return StmtError();
  5225. if (AStmt) {
  5226. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5227. getCurFunction()->setHasBranchProtectedScope();
  5228. }
  5229. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5230. }
  5231. namespace {
  5232. /// \brief Helper class for checking expression in 'omp atomic [update]'
  5233. /// construct.
  5234. class OpenMPAtomicUpdateChecker {
  5235. /// \brief Error results for atomic update expressions.
  5236. enum ExprAnalysisErrorCode {
  5237. /// \brief A statement is not an expression statement.
  5238. NotAnExpression,
  5239. /// \brief Expression is not builtin binary or unary operation.
  5240. NotABinaryOrUnaryExpression,
  5241. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  5242. NotAnUnaryIncDecExpression,
  5243. /// \brief An expression is not of scalar type.
  5244. NotAScalarType,
  5245. /// \brief A binary operation is not an assignment operation.
  5246. NotAnAssignmentOp,
  5247. /// \brief RHS part of the binary operation is not a binary expression.
  5248. NotABinaryExpression,
  5249. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  5250. /// expression.
  5251. NotABinaryOperator,
  5252. /// \brief RHS binary operation does not have reference to the updated LHS
  5253. /// part.
  5254. NotAnUpdateExpression,
  5255. /// \brief No errors is found.
  5256. NoError
  5257. };
  5258. /// \brief Reference to Sema.
  5259. Sema &SemaRef;
  5260. /// \brief A location for note diagnostics (when error is found).
  5261. SourceLocation NoteLoc;
  5262. /// \brief 'x' lvalue part of the source atomic expression.
  5263. Expr *X;
  5264. /// \brief 'expr' rvalue part of the source atomic expression.
  5265. Expr *E;
  5266. /// \brief Helper expression of the form
  5267. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5268. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5269. Expr *UpdateExpr;
  5270. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  5271. /// important for non-associative operations.
  5272. bool IsXLHSInRHSPart;
  5273. BinaryOperatorKind Op;
  5274. SourceLocation OpLoc;
  5275. /// \brief true if the source expression is a postfix unary operation, false
  5276. /// if it is a prefix unary operation.
  5277. bool IsPostfixUpdate;
  5278. public:
  5279. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5280. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5281. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5282. /// \brief Check specified statement that it is suitable for 'atomic update'
  5283. /// constructs and extract 'x', 'expr' and Operation from the original
  5284. /// expression. If DiagId and NoteId == 0, then only check is performed
  5285. /// without error notification.
  5286. /// \param DiagId Diagnostic which should be emitted if error is found.
  5287. /// \param NoteId Diagnostic note for the main error message.
  5288. /// \return true if statement is not an update expression, false otherwise.
  5289. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5290. /// \brief Return the 'x' lvalue part of the source atomic expression.
  5291. Expr *getX() const { return X; }
  5292. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  5293. Expr *getExpr() const { return E; }
  5294. /// \brief Return the update expression used in calculation of the updated
  5295. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5296. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5297. Expr *getUpdateExpr() const { return UpdateExpr; }
  5298. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  5299. /// false otherwise.
  5300. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5301. /// \brief true if the source expression is a postfix unary operation, false
  5302. /// if it is a prefix unary operation.
  5303. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5304. private:
  5305. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5306. unsigned NoteId = 0);
  5307. };
  5308. } // namespace
  5309. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5310. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5311. ExprAnalysisErrorCode ErrorFound = NoError;
  5312. SourceLocation ErrorLoc, NoteLoc;
  5313. SourceRange ErrorRange, NoteRange;
  5314. // Allowed constructs are:
  5315. // x = x binop expr;
  5316. // x = expr binop x;
  5317. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5318. X = AtomicBinOp->getLHS();
  5319. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5320. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5321. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5322. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5323. AtomicInnerBinOp->isBitwiseOp()) {
  5324. Op = AtomicInnerBinOp->getOpcode();
  5325. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5326. auto *LHS = AtomicInnerBinOp->getLHS();
  5327. auto *RHS = AtomicInnerBinOp->getRHS();
  5328. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5329. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5330. /*Canonical=*/true);
  5331. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5332. /*Canonical=*/true);
  5333. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5334. /*Canonical=*/true);
  5335. if (XId == LHSId) {
  5336. E = RHS;
  5337. IsXLHSInRHSPart = true;
  5338. } else if (XId == RHSId) {
  5339. E = LHS;
  5340. IsXLHSInRHSPart = false;
  5341. } else {
  5342. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5343. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5344. NoteLoc = X->getExprLoc();
  5345. NoteRange = X->getSourceRange();
  5346. ErrorFound = NotAnUpdateExpression;
  5347. }
  5348. } else {
  5349. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5350. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5351. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5352. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5353. ErrorFound = NotABinaryOperator;
  5354. }
  5355. } else {
  5356. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5357. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5358. ErrorFound = NotABinaryExpression;
  5359. }
  5360. } else {
  5361. ErrorLoc = AtomicBinOp->getExprLoc();
  5362. ErrorRange = AtomicBinOp->getSourceRange();
  5363. NoteLoc = AtomicBinOp->getOperatorLoc();
  5364. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5365. ErrorFound = NotAnAssignmentOp;
  5366. }
  5367. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5368. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5369. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5370. return true;
  5371. } else if (SemaRef.CurContext->isDependentContext())
  5372. E = X = UpdateExpr = nullptr;
  5373. return ErrorFound != NoError;
  5374. }
  5375. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5376. unsigned NoteId) {
  5377. ExprAnalysisErrorCode ErrorFound = NoError;
  5378. SourceLocation ErrorLoc, NoteLoc;
  5379. SourceRange ErrorRange, NoteRange;
  5380. // Allowed constructs are:
  5381. // x++;
  5382. // x--;
  5383. // ++x;
  5384. // --x;
  5385. // x binop= expr;
  5386. // x = x binop expr;
  5387. // x = expr binop x;
  5388. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5389. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5390. if (AtomicBody->getType()->isScalarType() ||
  5391. AtomicBody->isInstantiationDependent()) {
  5392. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5393. AtomicBody->IgnoreParenImpCasts())) {
  5394. // Check for Compound Assignment Operation
  5395. Op = BinaryOperator::getOpForCompoundAssignment(
  5396. AtomicCompAssignOp->getOpcode());
  5397. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5398. E = AtomicCompAssignOp->getRHS();
  5399. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5400. IsXLHSInRHSPart = true;
  5401. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5402. AtomicBody->IgnoreParenImpCasts())) {
  5403. // Check for Binary Operation
  5404. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5405. return true;
  5406. } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5407. AtomicBody->IgnoreParenImpCasts())) {
  5408. // Check for Unary Operation
  5409. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5410. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5411. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5412. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5413. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5414. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5415. IsXLHSInRHSPart = true;
  5416. } else {
  5417. ErrorFound = NotAnUnaryIncDecExpression;
  5418. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5419. ErrorRange = AtomicUnaryOp->getSourceRange();
  5420. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5421. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5422. }
  5423. } else if (!AtomicBody->isInstantiationDependent()) {
  5424. ErrorFound = NotABinaryOrUnaryExpression;
  5425. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5426. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5427. }
  5428. } else {
  5429. ErrorFound = NotAScalarType;
  5430. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  5431. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5432. }
  5433. } else {
  5434. ErrorFound = NotAnExpression;
  5435. NoteLoc = ErrorLoc = S->getLocStart();
  5436. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5437. }
  5438. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5439. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5440. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5441. return true;
  5442. } else if (SemaRef.CurContext->isDependentContext())
  5443. E = X = UpdateExpr = nullptr;
  5444. if (ErrorFound == NoError && E && X) {
  5445. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5446. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5447. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5448. auto *OVEX = new (SemaRef.getASTContext())
  5449. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5450. auto *OVEExpr = new (SemaRef.getASTContext())
  5451. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5452. auto Update =
  5453. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  5454. IsXLHSInRHSPart ? OVEExpr : OVEX);
  5455. if (Update.isInvalid())
  5456. return true;
  5457. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  5458. Sema::AA_Casting);
  5459. if (Update.isInvalid())
  5460. return true;
  5461. UpdateExpr = Update.get();
  5462. }
  5463. return ErrorFound != NoError;
  5464. }
  5465. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  5466. Stmt *AStmt,
  5467. SourceLocation StartLoc,
  5468. SourceLocation EndLoc) {
  5469. if (!AStmt)
  5470. return StmtError();
  5471. auto *CS = cast<CapturedStmt>(AStmt);
  5472. // 1.2.2 OpenMP Language Terminology
  5473. // Structured block - An executable statement with a single entry at the
  5474. // top and a single exit at the bottom.
  5475. // The point of exit cannot be a branch out of the structured block.
  5476. // longjmp() and throw() must not violate the entry/exit criteria.
  5477. OpenMPClauseKind AtomicKind = OMPC_unknown;
  5478. SourceLocation AtomicKindLoc;
  5479. for (auto *C : Clauses) {
  5480. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  5481. C->getClauseKind() == OMPC_update ||
  5482. C->getClauseKind() == OMPC_capture) {
  5483. if (AtomicKind != OMPC_unknown) {
  5484. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  5485. << SourceRange(C->getLocStart(), C->getLocEnd());
  5486. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  5487. << getOpenMPClauseName(AtomicKind);
  5488. } else {
  5489. AtomicKind = C->getClauseKind();
  5490. AtomicKindLoc = C->getLocStart();
  5491. }
  5492. }
  5493. }
  5494. auto Body = CS->getCapturedStmt();
  5495. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  5496. Body = EWC->getSubExpr();
  5497. Expr *X = nullptr;
  5498. Expr *V = nullptr;
  5499. Expr *E = nullptr;
  5500. Expr *UE = nullptr;
  5501. bool IsXLHSInRHSPart = false;
  5502. bool IsPostfixUpdate = false;
  5503. // OpenMP [2.12.6, atomic Construct]
  5504. // In the next expressions:
  5505. // * x and v (as applicable) are both l-value expressions with scalar type.
  5506. // * During the execution of an atomic region, multiple syntactic
  5507. // occurrences of x must designate the same storage location.
  5508. // * Neither of v and expr (as applicable) may access the storage location
  5509. // designated by x.
  5510. // * Neither of x and expr (as applicable) may access the storage location
  5511. // designated by v.
  5512. // * expr is an expression with scalar type.
  5513. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  5514. // * binop, binop=, ++, and -- are not overloaded operators.
  5515. // * The expression x binop expr must be numerically equivalent to x binop
  5516. // (expr). This requirement is satisfied if the operators in expr have
  5517. // precedence greater than binop, or by using parentheses around expr or
  5518. // subexpressions of expr.
  5519. // * The expression expr binop x must be numerically equivalent to (expr)
  5520. // binop x. This requirement is satisfied if the operators in expr have
  5521. // precedence equal to or greater than binop, or by using parentheses around
  5522. // expr or subexpressions of expr.
  5523. // * For forms that allow multiple occurrences of x, the number of times
  5524. // that x is evaluated is unspecified.
  5525. if (AtomicKind == OMPC_read) {
  5526. enum {
  5527. NotAnExpression,
  5528. NotAnAssignmentOp,
  5529. NotAScalarType,
  5530. NotAnLValue,
  5531. NoError
  5532. } ErrorFound = NoError;
  5533. SourceLocation ErrorLoc, NoteLoc;
  5534. SourceRange ErrorRange, NoteRange;
  5535. // If clause is read:
  5536. // v = x;
  5537. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5538. auto *AtomicBinOp =
  5539. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5540. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5541. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5542. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  5543. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5544. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  5545. if (!X->isLValue() || !V->isLValue()) {
  5546. auto NotLValueExpr = X->isLValue() ? V : X;
  5547. ErrorFound = NotAnLValue;
  5548. ErrorLoc = AtomicBinOp->getExprLoc();
  5549. ErrorRange = AtomicBinOp->getSourceRange();
  5550. NoteLoc = NotLValueExpr->getExprLoc();
  5551. NoteRange = NotLValueExpr->getSourceRange();
  5552. }
  5553. } else if (!X->isInstantiationDependent() ||
  5554. !V->isInstantiationDependent()) {
  5555. auto NotScalarExpr =
  5556. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5557. ? V
  5558. : X;
  5559. ErrorFound = NotAScalarType;
  5560. ErrorLoc = AtomicBinOp->getExprLoc();
  5561. ErrorRange = AtomicBinOp->getSourceRange();
  5562. NoteLoc = NotScalarExpr->getExprLoc();
  5563. NoteRange = NotScalarExpr->getSourceRange();
  5564. }
  5565. } else if (!AtomicBody->isInstantiationDependent()) {
  5566. ErrorFound = NotAnAssignmentOp;
  5567. ErrorLoc = AtomicBody->getExprLoc();
  5568. ErrorRange = AtomicBody->getSourceRange();
  5569. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5570. : AtomicBody->getExprLoc();
  5571. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5572. : AtomicBody->getSourceRange();
  5573. }
  5574. } else {
  5575. ErrorFound = NotAnExpression;
  5576. NoteLoc = ErrorLoc = Body->getLocStart();
  5577. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5578. }
  5579. if (ErrorFound != NoError) {
  5580. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5581. << ErrorRange;
  5582. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5583. << NoteRange;
  5584. return StmtError();
  5585. } else if (CurContext->isDependentContext())
  5586. V = X = nullptr;
  5587. } else if (AtomicKind == OMPC_write) {
  5588. enum {
  5589. NotAnExpression,
  5590. NotAnAssignmentOp,
  5591. NotAScalarType,
  5592. NotAnLValue,
  5593. NoError
  5594. } ErrorFound = NoError;
  5595. SourceLocation ErrorLoc, NoteLoc;
  5596. SourceRange ErrorRange, NoteRange;
  5597. // If clause is write:
  5598. // x = expr;
  5599. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5600. auto *AtomicBinOp =
  5601. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5602. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5603. X = AtomicBinOp->getLHS();
  5604. E = AtomicBinOp->getRHS();
  5605. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5606. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5607. if (!X->isLValue()) {
  5608. ErrorFound = NotAnLValue;
  5609. ErrorLoc = AtomicBinOp->getExprLoc();
  5610. ErrorRange = AtomicBinOp->getSourceRange();
  5611. NoteLoc = X->getExprLoc();
  5612. NoteRange = X->getSourceRange();
  5613. }
  5614. } else if (!X->isInstantiationDependent() ||
  5615. !E->isInstantiationDependent()) {
  5616. auto NotScalarExpr =
  5617. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5618. ? E
  5619. : X;
  5620. ErrorFound = NotAScalarType;
  5621. ErrorLoc = AtomicBinOp->getExprLoc();
  5622. ErrorRange = AtomicBinOp->getSourceRange();
  5623. NoteLoc = NotScalarExpr->getExprLoc();
  5624. NoteRange = NotScalarExpr->getSourceRange();
  5625. }
  5626. } else if (!AtomicBody->isInstantiationDependent()) {
  5627. ErrorFound = NotAnAssignmentOp;
  5628. ErrorLoc = AtomicBody->getExprLoc();
  5629. ErrorRange = AtomicBody->getSourceRange();
  5630. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5631. : AtomicBody->getExprLoc();
  5632. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5633. : AtomicBody->getSourceRange();
  5634. }
  5635. } else {
  5636. ErrorFound = NotAnExpression;
  5637. NoteLoc = ErrorLoc = Body->getLocStart();
  5638. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5639. }
  5640. if (ErrorFound != NoError) {
  5641. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5642. << ErrorRange;
  5643. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5644. << NoteRange;
  5645. return StmtError();
  5646. } else if (CurContext->isDependentContext())
  5647. E = X = nullptr;
  5648. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5649. // If clause is update:
  5650. // x++;
  5651. // x--;
  5652. // ++x;
  5653. // --x;
  5654. // x binop= expr;
  5655. // x = x binop expr;
  5656. // x = expr binop x;
  5657. OpenMPAtomicUpdateChecker Checker(*this);
  5658. if (Checker.checkStatement(
  5659. Body, (AtomicKind == OMPC_update)
  5660. ? diag::err_omp_atomic_update_not_expression_statement
  5661. : diag::err_omp_atomic_not_expression_statement,
  5662. diag::note_omp_atomic_update))
  5663. return StmtError();
  5664. if (!CurContext->isDependentContext()) {
  5665. E = Checker.getExpr();
  5666. X = Checker.getX();
  5667. UE = Checker.getUpdateExpr();
  5668. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5669. }
  5670. } else if (AtomicKind == OMPC_capture) {
  5671. enum {
  5672. NotAnAssignmentOp,
  5673. NotACompoundStatement,
  5674. NotTwoSubstatements,
  5675. NotASpecificExpression,
  5676. NoError
  5677. } ErrorFound = NoError;
  5678. SourceLocation ErrorLoc, NoteLoc;
  5679. SourceRange ErrorRange, NoteRange;
  5680. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5681. // If clause is a capture:
  5682. // v = x++;
  5683. // v = x--;
  5684. // v = ++x;
  5685. // v = --x;
  5686. // v = x binop= expr;
  5687. // v = x = x binop expr;
  5688. // v = x = expr binop x;
  5689. auto *AtomicBinOp =
  5690. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5691. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5692. V = AtomicBinOp->getLHS();
  5693. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5694. OpenMPAtomicUpdateChecker Checker(*this);
  5695. if (Checker.checkStatement(
  5696. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5697. diag::note_omp_atomic_update))
  5698. return StmtError();
  5699. E = Checker.getExpr();
  5700. X = Checker.getX();
  5701. UE = Checker.getUpdateExpr();
  5702. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5703. IsPostfixUpdate = Checker.isPostfixUpdate();
  5704. } else if (!AtomicBody->isInstantiationDependent()) {
  5705. ErrorLoc = AtomicBody->getExprLoc();
  5706. ErrorRange = AtomicBody->getSourceRange();
  5707. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5708. : AtomicBody->getExprLoc();
  5709. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5710. : AtomicBody->getSourceRange();
  5711. ErrorFound = NotAnAssignmentOp;
  5712. }
  5713. if (ErrorFound != NoError) {
  5714. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5715. << ErrorRange;
  5716. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5717. return StmtError();
  5718. } else if (CurContext->isDependentContext()) {
  5719. UE = V = E = X = nullptr;
  5720. }
  5721. } else {
  5722. // If clause is a capture:
  5723. // { v = x; x = expr; }
  5724. // { v = x; x++; }
  5725. // { v = x; x--; }
  5726. // { v = x; ++x; }
  5727. // { v = x; --x; }
  5728. // { v = x; x binop= expr; }
  5729. // { v = x; x = x binop expr; }
  5730. // { v = x; x = expr binop x; }
  5731. // { x++; v = x; }
  5732. // { x--; v = x; }
  5733. // { ++x; v = x; }
  5734. // { --x; v = x; }
  5735. // { x binop= expr; v = x; }
  5736. // { x = x binop expr; v = x; }
  5737. // { x = expr binop x; v = x; }
  5738. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5739. // Check that this is { expr1; expr2; }
  5740. if (CS->size() == 2) {
  5741. auto *First = CS->body_front();
  5742. auto *Second = CS->body_back();
  5743. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5744. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5745. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5746. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5747. // Need to find what subexpression is 'v' and what is 'x'.
  5748. OpenMPAtomicUpdateChecker Checker(*this);
  5749. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5750. BinaryOperator *BinOp = nullptr;
  5751. if (IsUpdateExprFound) {
  5752. BinOp = dyn_cast<BinaryOperator>(First);
  5753. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5754. }
  5755. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5756. // { v = x; x++; }
  5757. // { v = x; x--; }
  5758. // { v = x; ++x; }
  5759. // { v = x; --x; }
  5760. // { v = x; x binop= expr; }
  5761. // { v = x; x = x binop expr; }
  5762. // { v = x; x = expr binop x; }
  5763. // Check that the first expression has form v = x.
  5764. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5765. llvm::FoldingSetNodeID XId, PossibleXId;
  5766. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5767. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5768. IsUpdateExprFound = XId == PossibleXId;
  5769. if (IsUpdateExprFound) {
  5770. V = BinOp->getLHS();
  5771. X = Checker.getX();
  5772. E = Checker.getExpr();
  5773. UE = Checker.getUpdateExpr();
  5774. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5775. IsPostfixUpdate = true;
  5776. }
  5777. }
  5778. if (!IsUpdateExprFound) {
  5779. IsUpdateExprFound = !Checker.checkStatement(First);
  5780. BinOp = nullptr;
  5781. if (IsUpdateExprFound) {
  5782. BinOp = dyn_cast<BinaryOperator>(Second);
  5783. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5784. }
  5785. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5786. // { x++; v = x; }
  5787. // { x--; v = x; }
  5788. // { ++x; v = x; }
  5789. // { --x; v = x; }
  5790. // { x binop= expr; v = x; }
  5791. // { x = x binop expr; v = x; }
  5792. // { x = expr binop x; v = x; }
  5793. // Check that the second expression has form v = x.
  5794. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5795. llvm::FoldingSetNodeID XId, PossibleXId;
  5796. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5797. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5798. IsUpdateExprFound = XId == PossibleXId;
  5799. if (IsUpdateExprFound) {
  5800. V = BinOp->getLHS();
  5801. X = Checker.getX();
  5802. E = Checker.getExpr();
  5803. UE = Checker.getUpdateExpr();
  5804. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5805. IsPostfixUpdate = false;
  5806. }
  5807. }
  5808. }
  5809. if (!IsUpdateExprFound) {
  5810. // { v = x; x = expr; }
  5811. auto *FirstExpr = dyn_cast<Expr>(First);
  5812. auto *SecondExpr = dyn_cast<Expr>(Second);
  5813. if (!FirstExpr || !SecondExpr ||
  5814. !(FirstExpr->isInstantiationDependent() ||
  5815. SecondExpr->isInstantiationDependent())) {
  5816. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5817. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5818. ErrorFound = NotAnAssignmentOp;
  5819. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5820. : First->getLocStart();
  5821. NoteRange = ErrorRange = FirstBinOp
  5822. ? FirstBinOp->getSourceRange()
  5823. : SourceRange(ErrorLoc, ErrorLoc);
  5824. } else {
  5825. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5826. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5827. ErrorFound = NotAnAssignmentOp;
  5828. NoteLoc = ErrorLoc = SecondBinOp
  5829. ? SecondBinOp->getOperatorLoc()
  5830. : Second->getLocStart();
  5831. NoteRange = ErrorRange =
  5832. SecondBinOp ? SecondBinOp->getSourceRange()
  5833. : SourceRange(ErrorLoc, ErrorLoc);
  5834. } else {
  5835. auto *PossibleXRHSInFirst =
  5836. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5837. auto *PossibleXLHSInSecond =
  5838. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5839. llvm::FoldingSetNodeID X1Id, X2Id;
  5840. PossibleXRHSInFirst->Profile(X1Id, Context,
  5841. /*Canonical=*/true);
  5842. PossibleXLHSInSecond->Profile(X2Id, Context,
  5843. /*Canonical=*/true);
  5844. IsUpdateExprFound = X1Id == X2Id;
  5845. if (IsUpdateExprFound) {
  5846. V = FirstBinOp->getLHS();
  5847. X = SecondBinOp->getLHS();
  5848. E = SecondBinOp->getRHS();
  5849. UE = nullptr;
  5850. IsXLHSInRHSPart = false;
  5851. IsPostfixUpdate = true;
  5852. } else {
  5853. ErrorFound = NotASpecificExpression;
  5854. ErrorLoc = FirstBinOp->getExprLoc();
  5855. ErrorRange = FirstBinOp->getSourceRange();
  5856. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5857. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5858. }
  5859. }
  5860. }
  5861. }
  5862. }
  5863. } else {
  5864. NoteLoc = ErrorLoc = Body->getLocStart();
  5865. NoteRange = ErrorRange =
  5866. SourceRange(Body->getLocStart(), Body->getLocStart());
  5867. ErrorFound = NotTwoSubstatements;
  5868. }
  5869. } else {
  5870. NoteLoc = ErrorLoc = Body->getLocStart();
  5871. NoteRange = ErrorRange =
  5872. SourceRange(Body->getLocStart(), Body->getLocStart());
  5873. ErrorFound = NotACompoundStatement;
  5874. }
  5875. if (ErrorFound != NoError) {
  5876. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5877. << ErrorRange;
  5878. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5879. return StmtError();
  5880. } else if (CurContext->isDependentContext()) {
  5881. UE = V = E = X = nullptr;
  5882. }
  5883. }
  5884. }
  5885. getCurFunction()->setHasBranchProtectedScope();
  5886. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5887. X, V, E, UE, IsXLHSInRHSPart,
  5888. IsPostfixUpdate);
  5889. }
  5890. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5891. Stmt *AStmt,
  5892. SourceLocation StartLoc,
  5893. SourceLocation EndLoc) {
  5894. if (!AStmt)
  5895. return StmtError();
  5896. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5897. // 1.2.2 OpenMP Language Terminology
  5898. // Structured block - An executable statement with a single entry at the
  5899. // top and a single exit at the bottom.
  5900. // The point of exit cannot be a branch out of the structured block.
  5901. // longjmp() and throw() must not violate the entry/exit criteria.
  5902. CS->getCapturedDecl()->setNothrow();
  5903. // OpenMP [2.16, Nesting of Regions]
  5904. // If specified, a teams construct must be contained within a target
  5905. // construct. That target construct must contain no statements or directives
  5906. // outside of the teams construct.
  5907. if (DSAStack->hasInnerTeamsRegion()) {
  5908. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5909. bool OMPTeamsFound = true;
  5910. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5911. auto I = CS->body_begin();
  5912. while (I != CS->body_end()) {
  5913. auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  5914. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5915. OMPTeamsFound = false;
  5916. break;
  5917. }
  5918. ++I;
  5919. }
  5920. assert(I != CS->body_end() && "Not found statement");
  5921. S = *I;
  5922. } else {
  5923. auto *OED = dyn_cast<OMPExecutableDirective>(S);
  5924. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  5925. }
  5926. if (!OMPTeamsFound) {
  5927. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5928. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5929. diag::note_omp_nested_teams_construct_here);
  5930. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5931. << isa<OMPExecutableDirective>(S);
  5932. return StmtError();
  5933. }
  5934. }
  5935. getCurFunction()->setHasBranchProtectedScope();
  5936. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5937. }
  5938. StmtResult
  5939. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5940. Stmt *AStmt, SourceLocation StartLoc,
  5941. SourceLocation EndLoc) {
  5942. if (!AStmt)
  5943. return StmtError();
  5944. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5945. // 1.2.2 OpenMP Language Terminology
  5946. // Structured block - An executable statement with a single entry at the
  5947. // top and a single exit at the bottom.
  5948. // The point of exit cannot be a branch out of the structured block.
  5949. // longjmp() and throw() must not violate the entry/exit criteria.
  5950. CS->getCapturedDecl()->setNothrow();
  5951. getCurFunction()->setHasBranchProtectedScope();
  5952. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5953. AStmt);
  5954. }
  5955. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  5956. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5957. SourceLocation EndLoc,
  5958. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5959. if (!AStmt)
  5960. return StmtError();
  5961. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5962. // 1.2.2 OpenMP Language Terminology
  5963. // Structured block - An executable statement with a single entry at the
  5964. // top and a single exit at the bottom.
  5965. // The point of exit cannot be a branch out of the structured block.
  5966. // longjmp() and throw() must not violate the entry/exit criteria.
  5967. CS->getCapturedDecl()->setNothrow();
  5968. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  5969. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  5970. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  5971. // 1.2.2 OpenMP Language Terminology
  5972. // Structured block - An executable statement with a single entry at the
  5973. // top and a single exit at the bottom.
  5974. // The point of exit cannot be a branch out of the structured block.
  5975. // longjmp() and throw() must not violate the entry/exit criteria.
  5976. CS->getCapturedDecl()->setNothrow();
  5977. }
  5978. OMPLoopDirective::HelperExprs B;
  5979. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5980. // define the nested loops number.
  5981. unsigned NestedLoopCount =
  5982. CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  5983. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  5984. VarsWithImplicitDSA, B);
  5985. if (NestedLoopCount == 0)
  5986. return StmtError();
  5987. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5988. "omp target parallel for loop exprs were not built");
  5989. if (!CurContext->isDependentContext()) {
  5990. // Finalize the clauses that need pre-built expressions for CodeGen.
  5991. for (auto C : Clauses) {
  5992. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5993. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5994. B.NumIterations, *this, CurScope,
  5995. DSAStack))
  5996. return StmtError();
  5997. }
  5998. }
  5999. getCurFunction()->setHasBranchProtectedScope();
  6000. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6001. NestedLoopCount, Clauses, AStmt,
  6002. B, DSAStack->isCancelRegion());
  6003. }
  6004. /// Check for existence of a map clause in the list of clauses.
  6005. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6006. const OpenMPClauseKind K) {
  6007. return llvm::any_of(
  6008. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6009. }
  6010. template <typename... Params>
  6011. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6012. const Params... ClauseTypes) {
  6013. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6014. }
  6015. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6016. Stmt *AStmt,
  6017. SourceLocation StartLoc,
  6018. SourceLocation EndLoc) {
  6019. if (!AStmt)
  6020. return StmtError();
  6021. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6022. // OpenMP [2.10.1, Restrictions, p. 97]
  6023. // At least one map clause must appear on the directive.
  6024. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6025. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6026. << "'map' or 'use_device_ptr'"
  6027. << getOpenMPDirectiveName(OMPD_target_data);
  6028. return StmtError();
  6029. }
  6030. getCurFunction()->setHasBranchProtectedScope();
  6031. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6032. AStmt);
  6033. }
  6034. StmtResult
  6035. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6036. SourceLocation StartLoc,
  6037. SourceLocation EndLoc, Stmt *AStmt) {
  6038. if (!AStmt)
  6039. return StmtError();
  6040. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6041. // 1.2.2 OpenMP Language Terminology
  6042. // Structured block - An executable statement with a single entry at the
  6043. // top and a single exit at the bottom.
  6044. // The point of exit cannot be a branch out of the structured block.
  6045. // longjmp() and throw() must not violate the entry/exit criteria.
  6046. CS->getCapturedDecl()->setNothrow();
  6047. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6048. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6049. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6050. // 1.2.2 OpenMP Language Terminology
  6051. // Structured block - An executable statement with a single entry at the
  6052. // top and a single exit at the bottom.
  6053. // The point of exit cannot be a branch out of the structured block.
  6054. // longjmp() and throw() must not violate the entry/exit criteria.
  6055. CS->getCapturedDecl()->setNothrow();
  6056. }
  6057. // OpenMP [2.10.2, Restrictions, p. 99]
  6058. // At least one map clause must appear on the directive.
  6059. if (!hasClauses(Clauses, OMPC_map)) {
  6060. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6061. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6062. return StmtError();
  6063. }
  6064. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6065. AStmt);
  6066. }
  6067. StmtResult
  6068. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6069. SourceLocation StartLoc,
  6070. SourceLocation EndLoc, Stmt *AStmt) {
  6071. if (!AStmt)
  6072. return StmtError();
  6073. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6074. // 1.2.2 OpenMP Language Terminology
  6075. // Structured block - An executable statement with a single entry at the
  6076. // top and a single exit at the bottom.
  6077. // The point of exit cannot be a branch out of the structured block.
  6078. // longjmp() and throw() must not violate the entry/exit criteria.
  6079. CS->getCapturedDecl()->setNothrow();
  6080. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6081. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6082. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6083. // 1.2.2 OpenMP Language Terminology
  6084. // Structured block - An executable statement with a single entry at the
  6085. // top and a single exit at the bottom.
  6086. // The point of exit cannot be a branch out of the structured block.
  6087. // longjmp() and throw() must not violate the entry/exit criteria.
  6088. CS->getCapturedDecl()->setNothrow();
  6089. }
  6090. // OpenMP [2.10.3, Restrictions, p. 102]
  6091. // At least one map clause must appear on the directive.
  6092. if (!hasClauses(Clauses, OMPC_map)) {
  6093. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6094. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6095. return StmtError();
  6096. }
  6097. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6098. AStmt);
  6099. }
  6100. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6101. SourceLocation StartLoc,
  6102. SourceLocation EndLoc,
  6103. Stmt *AStmt) {
  6104. if (!AStmt)
  6105. return StmtError();
  6106. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6107. // 1.2.2 OpenMP Language Terminology
  6108. // Structured block - An executable statement with a single entry at the
  6109. // top and a single exit at the bottom.
  6110. // The point of exit cannot be a branch out of the structured block.
  6111. // longjmp() and throw() must not violate the entry/exit criteria.
  6112. CS->getCapturedDecl()->setNothrow();
  6113. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6114. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6115. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6116. // 1.2.2 OpenMP Language Terminology
  6117. // Structured block - An executable statement with a single entry at the
  6118. // top and a single exit at the bottom.
  6119. // The point of exit cannot be a branch out of the structured block.
  6120. // longjmp() and throw() must not violate the entry/exit criteria.
  6121. CS->getCapturedDecl()->setNothrow();
  6122. }
  6123. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6124. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6125. return StmtError();
  6126. }
  6127. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6128. AStmt);
  6129. }
  6130. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6131. Stmt *AStmt, SourceLocation StartLoc,
  6132. SourceLocation EndLoc) {
  6133. if (!AStmt)
  6134. return StmtError();
  6135. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6136. // 1.2.2 OpenMP Language Terminology
  6137. // Structured block - An executable statement with a single entry at the
  6138. // top and a single exit at the bottom.
  6139. // The point of exit cannot be a branch out of the structured block.
  6140. // longjmp() and throw() must not violate the entry/exit criteria.
  6141. CS->getCapturedDecl()->setNothrow();
  6142. getCurFunction()->setHasBranchProtectedScope();
  6143. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6144. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6145. }
  6146. StmtResult
  6147. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6148. SourceLocation EndLoc,
  6149. OpenMPDirectiveKind CancelRegion) {
  6150. if (DSAStack->isParentNowaitRegion()) {
  6151. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6152. return StmtError();
  6153. }
  6154. if (DSAStack->isParentOrderedRegion()) {
  6155. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6156. return StmtError();
  6157. }
  6158. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6159. CancelRegion);
  6160. }
  6161. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6162. SourceLocation StartLoc,
  6163. SourceLocation EndLoc,
  6164. OpenMPDirectiveKind CancelRegion) {
  6165. if (DSAStack->isParentNowaitRegion()) {
  6166. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6167. return StmtError();
  6168. }
  6169. if (DSAStack->isParentOrderedRegion()) {
  6170. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6171. return StmtError();
  6172. }
  6173. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6174. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6175. CancelRegion);
  6176. }
  6177. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6178. ArrayRef<OMPClause *> Clauses) {
  6179. OMPClause *PrevClause = nullptr;
  6180. bool ErrorFound = false;
  6181. for (auto *C : Clauses) {
  6182. if (C->getClauseKind() == OMPC_grainsize ||
  6183. C->getClauseKind() == OMPC_num_tasks) {
  6184. if (!PrevClause)
  6185. PrevClause = C;
  6186. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6187. S.Diag(C->getLocStart(),
  6188. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6189. << getOpenMPClauseName(C->getClauseKind())
  6190. << getOpenMPClauseName(PrevClause->getClauseKind());
  6191. S.Diag(PrevClause->getLocStart(),
  6192. diag::note_omp_previous_grainsize_num_tasks)
  6193. << getOpenMPClauseName(PrevClause->getClauseKind());
  6194. ErrorFound = true;
  6195. }
  6196. }
  6197. }
  6198. return ErrorFound;
  6199. }
  6200. static bool checkReductionClauseWithNogroup(Sema &S,
  6201. ArrayRef<OMPClause *> Clauses) {
  6202. OMPClause *ReductionClause = nullptr;
  6203. OMPClause *NogroupClause = nullptr;
  6204. for (auto *C : Clauses) {
  6205. if (C->getClauseKind() == OMPC_reduction) {
  6206. ReductionClause = C;
  6207. if (NogroupClause)
  6208. break;
  6209. continue;
  6210. }
  6211. if (C->getClauseKind() == OMPC_nogroup) {
  6212. NogroupClause = C;
  6213. if (ReductionClause)
  6214. break;
  6215. continue;
  6216. }
  6217. }
  6218. if (ReductionClause && NogroupClause) {
  6219. S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
  6220. << SourceRange(NogroupClause->getLocStart(),
  6221. NogroupClause->getLocEnd());
  6222. return true;
  6223. }
  6224. return false;
  6225. }
  6226. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6227. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6228. SourceLocation EndLoc,
  6229. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6230. if (!AStmt)
  6231. return StmtError();
  6232. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6233. OMPLoopDirective::HelperExprs B;
  6234. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6235. // define the nested loops number.
  6236. unsigned NestedLoopCount =
  6237. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6238. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6239. VarsWithImplicitDSA, B);
  6240. if (NestedLoopCount == 0)
  6241. return StmtError();
  6242. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6243. "omp for loop exprs were not built");
  6244. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6245. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6246. // not appear on the same taskloop directive.
  6247. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6248. return StmtError();
  6249. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6250. // If a reduction clause is present on the taskloop directive, the nogroup
  6251. // clause must not be specified.
  6252. if (checkReductionClauseWithNogroup(*this, Clauses))
  6253. return StmtError();
  6254. getCurFunction()->setHasBranchProtectedScope();
  6255. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6256. NestedLoopCount, Clauses, AStmt, B);
  6257. }
  6258. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6259. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6260. SourceLocation EndLoc,
  6261. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6262. if (!AStmt)
  6263. return StmtError();
  6264. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6265. OMPLoopDirective::HelperExprs B;
  6266. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6267. // define the nested loops number.
  6268. unsigned NestedLoopCount =
  6269. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6270. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6271. VarsWithImplicitDSA, B);
  6272. if (NestedLoopCount == 0)
  6273. return StmtError();
  6274. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6275. "omp for loop exprs were not built");
  6276. if (!CurContext->isDependentContext()) {
  6277. // Finalize the clauses that need pre-built expressions for CodeGen.
  6278. for (auto C : Clauses) {
  6279. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6280. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6281. B.NumIterations, *this, CurScope,
  6282. DSAStack))
  6283. return StmtError();
  6284. }
  6285. }
  6286. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6287. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6288. // not appear on the same taskloop directive.
  6289. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6290. return StmtError();
  6291. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6292. // If a reduction clause is present on the taskloop directive, the nogroup
  6293. // clause must not be specified.
  6294. if (checkReductionClauseWithNogroup(*this, Clauses))
  6295. return StmtError();
  6296. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6297. return StmtError();
  6298. getCurFunction()->setHasBranchProtectedScope();
  6299. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6300. NestedLoopCount, Clauses, AStmt, B);
  6301. }
  6302. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6303. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6304. SourceLocation EndLoc,
  6305. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6306. if (!AStmt)
  6307. return StmtError();
  6308. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6309. OMPLoopDirective::HelperExprs B;
  6310. // In presence of clause 'collapse' with number of loops, it will
  6311. // define the nested loops number.
  6312. unsigned NestedLoopCount =
  6313. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6314. nullptr /*ordered not a clause on distribute*/, AStmt,
  6315. *this, *DSAStack, VarsWithImplicitDSA, B);
  6316. if (NestedLoopCount == 0)
  6317. return StmtError();
  6318. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6319. "omp for loop exprs were not built");
  6320. getCurFunction()->setHasBranchProtectedScope();
  6321. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6322. NestedLoopCount, Clauses, AStmt, B);
  6323. }
  6324. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6325. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6326. SourceLocation EndLoc,
  6327. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6328. if (!AStmt)
  6329. return StmtError();
  6330. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6331. // 1.2.2 OpenMP Language Terminology
  6332. // Structured block - An executable statement with a single entry at the
  6333. // top and a single exit at the bottom.
  6334. // The point of exit cannot be a branch out of the structured block.
  6335. // longjmp() and throw() must not violate the entry/exit criteria.
  6336. CS->getCapturedDecl()->setNothrow();
  6337. for (int ThisCaptureLevel =
  6338. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  6339. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6340. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6341. // 1.2.2 OpenMP Language Terminology
  6342. // Structured block - An executable statement with a single entry at the
  6343. // top and a single exit at the bottom.
  6344. // The point of exit cannot be a branch out of the structured block.
  6345. // longjmp() and throw() must not violate the entry/exit criteria.
  6346. CS->getCapturedDecl()->setNothrow();
  6347. }
  6348. OMPLoopDirective::HelperExprs B;
  6349. // In presence of clause 'collapse' with number of loops, it will
  6350. // define the nested loops number.
  6351. unsigned NestedLoopCount = CheckOpenMPLoop(
  6352. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6353. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6354. VarsWithImplicitDSA, B);
  6355. if (NestedLoopCount == 0)
  6356. return StmtError();
  6357. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6358. "omp for loop exprs were not built");
  6359. getCurFunction()->setHasBranchProtectedScope();
  6360. return OMPDistributeParallelForDirective::Create(
  6361. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6362. DSAStack->isCancelRegion());
  6363. }
  6364. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6365. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6366. SourceLocation EndLoc,
  6367. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6368. if (!AStmt)
  6369. return StmtError();
  6370. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6371. // 1.2.2 OpenMP Language Terminology
  6372. // Structured block - An executable statement with a single entry at the
  6373. // top and a single exit at the bottom.
  6374. // The point of exit cannot be a branch out of the structured block.
  6375. // longjmp() and throw() must not violate the entry/exit criteria.
  6376. CS->getCapturedDecl()->setNothrow();
  6377. for (int ThisCaptureLevel =
  6378. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  6379. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6380. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6381. // 1.2.2 OpenMP Language Terminology
  6382. // Structured block - An executable statement with a single entry at the
  6383. // top and a single exit at the bottom.
  6384. // The point of exit cannot be a branch out of the structured block.
  6385. // longjmp() and throw() must not violate the entry/exit criteria.
  6386. CS->getCapturedDecl()->setNothrow();
  6387. }
  6388. OMPLoopDirective::HelperExprs B;
  6389. // In presence of clause 'collapse' with number of loops, it will
  6390. // define the nested loops number.
  6391. unsigned NestedLoopCount = CheckOpenMPLoop(
  6392. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6393. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6394. VarsWithImplicitDSA, B);
  6395. if (NestedLoopCount == 0)
  6396. return StmtError();
  6397. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6398. "omp for loop exprs were not built");
  6399. if (!CurContext->isDependentContext()) {
  6400. // Finalize the clauses that need pre-built expressions for CodeGen.
  6401. for (auto C : Clauses) {
  6402. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6403. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6404. B.NumIterations, *this, CurScope,
  6405. DSAStack))
  6406. return StmtError();
  6407. }
  6408. }
  6409. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6410. return StmtError();
  6411. getCurFunction()->setHasBranchProtectedScope();
  6412. return OMPDistributeParallelForSimdDirective::Create(
  6413. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6414. }
  6415. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6416. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6417. SourceLocation EndLoc,
  6418. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6419. if (!AStmt)
  6420. return StmtError();
  6421. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6422. // 1.2.2 OpenMP Language Terminology
  6423. // Structured block - An executable statement with a single entry at the
  6424. // top and a single exit at the bottom.
  6425. // The point of exit cannot be a branch out of the structured block.
  6426. // longjmp() and throw() must not violate the entry/exit criteria.
  6427. CS->getCapturedDecl()->setNothrow();
  6428. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  6429. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6430. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6431. // 1.2.2 OpenMP Language Terminology
  6432. // Structured block - An executable statement with a single entry at the
  6433. // top and a single exit at the bottom.
  6434. // The point of exit cannot be a branch out of the structured block.
  6435. // longjmp() and throw() must not violate the entry/exit criteria.
  6436. CS->getCapturedDecl()->setNothrow();
  6437. }
  6438. OMPLoopDirective::HelperExprs B;
  6439. // In presence of clause 'collapse' with number of loops, it will
  6440. // define the nested loops number.
  6441. unsigned NestedLoopCount =
  6442. CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  6443. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6444. *DSAStack, VarsWithImplicitDSA, B);
  6445. if (NestedLoopCount == 0)
  6446. return StmtError();
  6447. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6448. "omp for loop exprs were not built");
  6449. if (!CurContext->isDependentContext()) {
  6450. // Finalize the clauses that need pre-built expressions for CodeGen.
  6451. for (auto C : Clauses) {
  6452. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6453. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6454. B.NumIterations, *this, CurScope,
  6455. DSAStack))
  6456. return StmtError();
  6457. }
  6458. }
  6459. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6460. return StmtError();
  6461. getCurFunction()->setHasBranchProtectedScope();
  6462. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  6463. NestedLoopCount, Clauses, AStmt, B);
  6464. }
  6465. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  6466. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6467. SourceLocation EndLoc,
  6468. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6469. if (!AStmt)
  6470. return StmtError();
  6471. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6472. // 1.2.2 OpenMP Language Terminology
  6473. // Structured block - An executable statement with a single entry at the
  6474. // top and a single exit at the bottom.
  6475. // The point of exit cannot be a branch out of the structured block.
  6476. // longjmp() and throw() must not violate the entry/exit criteria.
  6477. CS->getCapturedDecl()->setNothrow();
  6478. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6479. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6480. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6481. // 1.2.2 OpenMP Language Terminology
  6482. // Structured block - An executable statement with a single entry at the
  6483. // top and a single exit at the bottom.
  6484. // The point of exit cannot be a branch out of the structured block.
  6485. // longjmp() and throw() must not violate the entry/exit criteria.
  6486. CS->getCapturedDecl()->setNothrow();
  6487. }
  6488. OMPLoopDirective::HelperExprs B;
  6489. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6490. // define the nested loops number.
  6491. unsigned NestedLoopCount = CheckOpenMPLoop(
  6492. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6493. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6494. VarsWithImplicitDSA, B);
  6495. if (NestedLoopCount == 0)
  6496. return StmtError();
  6497. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6498. "omp target parallel for simd loop exprs were not built");
  6499. if (!CurContext->isDependentContext()) {
  6500. // Finalize the clauses that need pre-built expressions for CodeGen.
  6501. for (auto C : Clauses) {
  6502. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6503. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6504. B.NumIterations, *this, CurScope,
  6505. DSAStack))
  6506. return StmtError();
  6507. }
  6508. }
  6509. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6510. return StmtError();
  6511. getCurFunction()->setHasBranchProtectedScope();
  6512. return OMPTargetParallelForSimdDirective::Create(
  6513. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6514. }
  6515. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  6516. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6517. SourceLocation EndLoc,
  6518. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6519. if (!AStmt)
  6520. return StmtError();
  6521. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6522. // 1.2.2 OpenMP Language Terminology
  6523. // Structured block - An executable statement with a single entry at the
  6524. // top and a single exit at the bottom.
  6525. // The point of exit cannot be a branch out of the structured block.
  6526. // longjmp() and throw() must not violate the entry/exit criteria.
  6527. CS->getCapturedDecl()->setNothrow();
  6528. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  6529. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6530. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6531. // 1.2.2 OpenMP Language Terminology
  6532. // Structured block - An executable statement with a single entry at the
  6533. // top and a single exit at the bottom.
  6534. // The point of exit cannot be a branch out of the structured block.
  6535. // longjmp() and throw() must not violate the entry/exit criteria.
  6536. CS->getCapturedDecl()->setNothrow();
  6537. }
  6538. OMPLoopDirective::HelperExprs B;
  6539. // In presence of clause 'collapse' with number of loops, it will define the
  6540. // nested loops number.
  6541. unsigned NestedLoopCount =
  6542. CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  6543. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6544. VarsWithImplicitDSA, B);
  6545. if (NestedLoopCount == 0)
  6546. return StmtError();
  6547. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6548. "omp target simd loop exprs were not built");
  6549. if (!CurContext->isDependentContext()) {
  6550. // Finalize the clauses that need pre-built expressions for CodeGen.
  6551. for (auto C : Clauses) {
  6552. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6553. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6554. B.NumIterations, *this, CurScope,
  6555. DSAStack))
  6556. return StmtError();
  6557. }
  6558. }
  6559. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6560. return StmtError();
  6561. getCurFunction()->setHasBranchProtectedScope();
  6562. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  6563. NestedLoopCount, Clauses, AStmt, B);
  6564. }
  6565. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  6566. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6567. SourceLocation EndLoc,
  6568. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6569. if (!AStmt)
  6570. return StmtError();
  6571. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  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. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  6579. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6580. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6581. // 1.2.2 OpenMP Language Terminology
  6582. // Structured block - An executable statement with a single entry at the
  6583. // top and a single exit at the bottom.
  6584. // The point of exit cannot be a branch out of the structured block.
  6585. // longjmp() and throw() must not violate the entry/exit criteria.
  6586. CS->getCapturedDecl()->setNothrow();
  6587. }
  6588. OMPLoopDirective::HelperExprs B;
  6589. // In presence of clause 'collapse' with number of loops, it will
  6590. // define the nested loops number.
  6591. unsigned NestedLoopCount =
  6592. CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  6593. nullptr /*ordered not a clause on distribute*/, CS, *this,
  6594. *DSAStack, VarsWithImplicitDSA, B);
  6595. if (NestedLoopCount == 0)
  6596. return StmtError();
  6597. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6598. "omp teams distribute loop exprs were not built");
  6599. getCurFunction()->setHasBranchProtectedScope();
  6600. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6601. return OMPTeamsDistributeDirective::Create(
  6602. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6603. }
  6604. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  6605. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6606. SourceLocation EndLoc,
  6607. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6608. if (!AStmt)
  6609. return StmtError();
  6610. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6611. // 1.2.2 OpenMP Language Terminology
  6612. // Structured block - An executable statement with a single entry at the
  6613. // top and a single exit at the bottom.
  6614. // The point of exit cannot be a branch out of the structured block.
  6615. // longjmp() and throw() must not violate the entry/exit criteria.
  6616. CS->getCapturedDecl()->setNothrow();
  6617. OMPLoopDirective::HelperExprs B;
  6618. // In presence of clause 'collapse' with number of loops, it will
  6619. // define the nested loops number.
  6620. unsigned NestedLoopCount = CheckOpenMPLoop(
  6621. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6622. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6623. VarsWithImplicitDSA, B);
  6624. if (NestedLoopCount == 0)
  6625. return StmtError();
  6626. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6627. "omp teams distribute simd loop exprs were not built");
  6628. if (!CurContext->isDependentContext()) {
  6629. // Finalize the clauses that need pre-built expressions for CodeGen.
  6630. for (auto C : Clauses) {
  6631. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6632. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6633. B.NumIterations, *this, CurScope,
  6634. DSAStack))
  6635. return StmtError();
  6636. }
  6637. }
  6638. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6639. return StmtError();
  6640. getCurFunction()->setHasBranchProtectedScope();
  6641. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6642. return OMPTeamsDistributeSimdDirective::Create(
  6643. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6644. }
  6645. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6646. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6647. SourceLocation EndLoc,
  6648. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6649. if (!AStmt)
  6650. return StmtError();
  6651. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6652. // 1.2.2 OpenMP Language Terminology
  6653. // Structured block - An executable statement with a single entry at the
  6654. // top and a single exit at the bottom.
  6655. // The point of exit cannot be a branch out of the structured block.
  6656. // longjmp() and throw() must not violate the entry/exit criteria.
  6657. CS->getCapturedDecl()->setNothrow();
  6658. for (int ThisCaptureLevel =
  6659. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  6660. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6661. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6662. // 1.2.2 OpenMP Language Terminology
  6663. // Structured block - An executable statement with a single entry at the
  6664. // top and a single exit at the bottom.
  6665. // The point of exit cannot be a branch out of the structured block.
  6666. // longjmp() and throw() must not violate the entry/exit criteria.
  6667. CS->getCapturedDecl()->setNothrow();
  6668. }
  6669. OMPLoopDirective::HelperExprs B;
  6670. // In presence of clause 'collapse' with number of loops, it will
  6671. // define the nested loops number.
  6672. auto NestedLoopCount = CheckOpenMPLoop(
  6673. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6674. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6675. VarsWithImplicitDSA, B);
  6676. if (NestedLoopCount == 0)
  6677. return StmtError();
  6678. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6679. "omp for loop exprs were not built");
  6680. if (!CurContext->isDependentContext()) {
  6681. // Finalize the clauses that need pre-built expressions for CodeGen.
  6682. for (auto C : Clauses) {
  6683. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6684. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6685. B.NumIterations, *this, CurScope,
  6686. DSAStack))
  6687. return StmtError();
  6688. }
  6689. }
  6690. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6691. return StmtError();
  6692. getCurFunction()->setHasBranchProtectedScope();
  6693. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6694. return OMPTeamsDistributeParallelForSimdDirective::Create(
  6695. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6696. }
  6697. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  6698. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6699. SourceLocation EndLoc,
  6700. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6701. if (!AStmt)
  6702. return StmtError();
  6703. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6704. // 1.2.2 OpenMP Language Terminology
  6705. // Structured block - An executable statement with a single entry at the
  6706. // top and a single exit at the bottom.
  6707. // The point of exit cannot be a branch out of the structured block.
  6708. // longjmp() and throw() must not violate the entry/exit criteria.
  6709. CS->getCapturedDecl()->setNothrow();
  6710. for (int ThisCaptureLevel =
  6711. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  6712. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6713. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6714. // 1.2.2 OpenMP Language Terminology
  6715. // Structured block - An executable statement with a single entry at the
  6716. // top and a single exit at the bottom.
  6717. // The point of exit cannot be a branch out of the structured block.
  6718. // longjmp() and throw() must not violate the entry/exit criteria.
  6719. CS->getCapturedDecl()->setNothrow();
  6720. }
  6721. OMPLoopDirective::HelperExprs B;
  6722. // In presence of clause 'collapse' with number of loops, it will
  6723. // define the nested loops number.
  6724. unsigned NestedLoopCount = CheckOpenMPLoop(
  6725. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6726. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  6727. VarsWithImplicitDSA, B);
  6728. if (NestedLoopCount == 0)
  6729. return StmtError();
  6730. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6731. "omp for loop exprs were not built");
  6732. getCurFunction()->setHasBranchProtectedScope();
  6733. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6734. return OMPTeamsDistributeParallelForDirective::Create(
  6735. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6736. DSAStack->isCancelRegion());
  6737. }
  6738. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6739. Stmt *AStmt,
  6740. SourceLocation StartLoc,
  6741. SourceLocation EndLoc) {
  6742. if (!AStmt)
  6743. return StmtError();
  6744. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6745. // 1.2.2 OpenMP Language Terminology
  6746. // Structured block - An executable statement with a single entry at the
  6747. // top and a single exit at the bottom.
  6748. // The point of exit cannot be a branch out of the structured block.
  6749. // longjmp() and throw() must not violate the entry/exit criteria.
  6750. CS->getCapturedDecl()->setNothrow();
  6751. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  6752. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6753. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6754. // 1.2.2 OpenMP Language Terminology
  6755. // Structured block - An executable statement with a single entry at the
  6756. // top and a single exit at the bottom.
  6757. // The point of exit cannot be a branch out of the structured block.
  6758. // longjmp() and throw() must not violate the entry/exit criteria.
  6759. CS->getCapturedDecl()->setNothrow();
  6760. }
  6761. getCurFunction()->setHasBranchProtectedScope();
  6762. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6763. AStmt);
  6764. }
  6765. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  6766. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6767. SourceLocation EndLoc,
  6768. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6769. if (!AStmt)
  6770. return StmtError();
  6771. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6772. // 1.2.2 OpenMP Language Terminology
  6773. // Structured block - An executable statement with a single entry at the
  6774. // top and a single exit at the bottom.
  6775. // The point of exit cannot be a branch out of the structured block.
  6776. // longjmp() and throw() must not violate the entry/exit criteria.
  6777. CS->getCapturedDecl()->setNothrow();
  6778. OMPLoopDirective::HelperExprs B;
  6779. // In presence of clause 'collapse' with number of loops, it will
  6780. // define the nested loops number.
  6781. auto NestedLoopCount = CheckOpenMPLoop(
  6782. OMPD_target_teams_distribute,
  6783. getCollapseNumberExpr(Clauses),
  6784. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6785. VarsWithImplicitDSA, B);
  6786. if (NestedLoopCount == 0)
  6787. return StmtError();
  6788. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6789. "omp target teams distribute loop exprs were not built");
  6790. getCurFunction()->setHasBranchProtectedScope();
  6791. return OMPTargetTeamsDistributeDirective::Create(
  6792. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6793. }
  6794. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  6795. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6796. SourceLocation EndLoc,
  6797. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6798. if (!AStmt)
  6799. return StmtError();
  6800. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6801. // 1.2.2 OpenMP Language Terminology
  6802. // Structured block - An executable statement with a single entry at the
  6803. // top and a single exit at the bottom.
  6804. // The point of exit cannot be a branch out of the structured block.
  6805. // longjmp() and throw() must not violate the entry/exit criteria.
  6806. CS->getCapturedDecl()->setNothrow();
  6807. OMPLoopDirective::HelperExprs B;
  6808. // In presence of clause 'collapse' with number of loops, it will
  6809. // define the nested loops number.
  6810. auto NestedLoopCount = CheckOpenMPLoop(
  6811. OMPD_target_teams_distribute_parallel_for,
  6812. getCollapseNumberExpr(Clauses),
  6813. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6814. VarsWithImplicitDSA, B);
  6815. if (NestedLoopCount == 0)
  6816. return StmtError();
  6817. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6818. "omp target teams distribute parallel for loop exprs were not built");
  6819. getCurFunction()->setHasBranchProtectedScope();
  6820. return OMPTargetTeamsDistributeParallelForDirective::Create(
  6821. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  6822. DSAStack->isCancelRegion());
  6823. }
  6824. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  6825. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6826. SourceLocation EndLoc,
  6827. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6828. if (!AStmt)
  6829. return StmtError();
  6830. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6831. // 1.2.2 OpenMP Language Terminology
  6832. // Structured block - An executable statement with a single entry at the
  6833. // top and a single exit at the bottom.
  6834. // The point of exit cannot be a branch out of the structured block.
  6835. // longjmp() and throw() must not violate the entry/exit criteria.
  6836. CS->getCapturedDecl()->setNothrow();
  6837. OMPLoopDirective::HelperExprs B;
  6838. // In presence of clause 'collapse' with number of loops, it will
  6839. // define the nested loops number.
  6840. auto NestedLoopCount = CheckOpenMPLoop(
  6841. OMPD_target_teams_distribute_parallel_for_simd,
  6842. getCollapseNumberExpr(Clauses),
  6843. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6844. VarsWithImplicitDSA, B);
  6845. if (NestedLoopCount == 0)
  6846. return StmtError();
  6847. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6848. "omp target teams distribute parallel for simd loop exprs were not "
  6849. "built");
  6850. if (!CurContext->isDependentContext()) {
  6851. // Finalize the clauses that need pre-built expressions for CodeGen.
  6852. for (auto C : Clauses) {
  6853. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6854. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6855. B.NumIterations, *this, CurScope,
  6856. DSAStack))
  6857. return StmtError();
  6858. }
  6859. }
  6860. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6861. return StmtError();
  6862. getCurFunction()->setHasBranchProtectedScope();
  6863. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  6864. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6865. }
  6866. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  6867. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6868. SourceLocation EndLoc,
  6869. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6870. if (!AStmt)
  6871. return StmtError();
  6872. auto *CS = cast<CapturedStmt>(AStmt);
  6873. // 1.2.2 OpenMP Language Terminology
  6874. // Structured block - An executable statement with a single entry at the
  6875. // top and a single exit at the bottom.
  6876. // The point of exit cannot be a branch out of the structured block.
  6877. // longjmp() and throw() must not violate the entry/exit criteria.
  6878. CS->getCapturedDecl()->setNothrow();
  6879. OMPLoopDirective::HelperExprs B;
  6880. // In presence of clause 'collapse' with number of loops, it will
  6881. // define the nested loops number.
  6882. auto NestedLoopCount = CheckOpenMPLoop(
  6883. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6884. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6885. VarsWithImplicitDSA, B);
  6886. if (NestedLoopCount == 0)
  6887. return StmtError();
  6888. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6889. "omp target teams distribute simd loop exprs were not built");
  6890. if (!CurContext->isDependentContext()) {
  6891. // Finalize the clauses that need pre-built expressions for CodeGen.
  6892. for (auto C : Clauses) {
  6893. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6894. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6895. B.NumIterations, *this, CurScope,
  6896. DSAStack))
  6897. return StmtError();
  6898. }
  6899. }
  6900. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6901. return StmtError();
  6902. getCurFunction()->setHasBranchProtectedScope();
  6903. return OMPTargetTeamsDistributeSimdDirective::Create(
  6904. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6905. }
  6906. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  6907. SourceLocation StartLoc,
  6908. SourceLocation LParenLoc,
  6909. SourceLocation EndLoc) {
  6910. OMPClause *Res = nullptr;
  6911. switch (Kind) {
  6912. case OMPC_final:
  6913. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  6914. break;
  6915. case OMPC_num_threads:
  6916. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6917. break;
  6918. case OMPC_safelen:
  6919. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6920. break;
  6921. case OMPC_simdlen:
  6922. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6923. break;
  6924. case OMPC_collapse:
  6925. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  6926. break;
  6927. case OMPC_ordered:
  6928. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  6929. break;
  6930. case OMPC_device:
  6931. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  6932. break;
  6933. case OMPC_num_teams:
  6934. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6935. break;
  6936. case OMPC_thread_limit:
  6937. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  6938. break;
  6939. case OMPC_priority:
  6940. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  6941. break;
  6942. case OMPC_grainsize:
  6943. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  6944. break;
  6945. case OMPC_num_tasks:
  6946. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  6947. break;
  6948. case OMPC_hint:
  6949. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  6950. break;
  6951. case OMPC_if:
  6952. case OMPC_default:
  6953. case OMPC_proc_bind:
  6954. case OMPC_schedule:
  6955. case OMPC_private:
  6956. case OMPC_firstprivate:
  6957. case OMPC_lastprivate:
  6958. case OMPC_shared:
  6959. case OMPC_reduction:
  6960. case OMPC_task_reduction:
  6961. case OMPC_in_reduction:
  6962. case OMPC_linear:
  6963. case OMPC_aligned:
  6964. case OMPC_copyin:
  6965. case OMPC_copyprivate:
  6966. case OMPC_nowait:
  6967. case OMPC_untied:
  6968. case OMPC_mergeable:
  6969. case OMPC_threadprivate:
  6970. case OMPC_flush:
  6971. case OMPC_read:
  6972. case OMPC_write:
  6973. case OMPC_update:
  6974. case OMPC_capture:
  6975. case OMPC_seq_cst:
  6976. case OMPC_depend:
  6977. case OMPC_threads:
  6978. case OMPC_simd:
  6979. case OMPC_map:
  6980. case OMPC_nogroup:
  6981. case OMPC_dist_schedule:
  6982. case OMPC_defaultmap:
  6983. case OMPC_unknown:
  6984. case OMPC_uniform:
  6985. case OMPC_to:
  6986. case OMPC_from:
  6987. case OMPC_use_device_ptr:
  6988. case OMPC_is_device_ptr:
  6989. llvm_unreachable("Clause is not allowed.");
  6990. }
  6991. return Res;
  6992. }
  6993. // An OpenMP directive such as 'target parallel' has two captured regions:
  6994. // for the 'target' and 'parallel' respectively. This function returns
  6995. // the region in which to capture expressions associated with a clause.
  6996. // A return value of OMPD_unknown signifies that the expression should not
  6997. // be captured.
  6998. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  6999. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7000. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7001. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7002. switch (CKind) {
  7003. case OMPC_if:
  7004. switch (DKind) {
  7005. case OMPD_target_parallel:
  7006. case OMPD_target_parallel_for:
  7007. case OMPD_target_parallel_for_simd:
  7008. case OMPD_target_teams_distribute_parallel_for:
  7009. case OMPD_target_teams_distribute_parallel_for_simd:
  7010. // If this clause applies to the nested 'parallel' region, capture within
  7011. // the 'target' region, otherwise do not capture.
  7012. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7013. CaptureRegion = OMPD_target;
  7014. break;
  7015. case OMPD_teams_distribute_parallel_for:
  7016. case OMPD_teams_distribute_parallel_for_simd:
  7017. CaptureRegion = OMPD_teams;
  7018. break;
  7019. case OMPD_cancel:
  7020. case OMPD_parallel:
  7021. case OMPD_parallel_sections:
  7022. case OMPD_parallel_for:
  7023. case OMPD_parallel_for_simd:
  7024. case OMPD_target:
  7025. case OMPD_target_simd:
  7026. case OMPD_target_teams:
  7027. case OMPD_target_teams_distribute:
  7028. case OMPD_target_teams_distribute_simd:
  7029. case OMPD_distribute_parallel_for:
  7030. case OMPD_distribute_parallel_for_simd:
  7031. case OMPD_task:
  7032. case OMPD_taskloop:
  7033. case OMPD_taskloop_simd:
  7034. case OMPD_target_data:
  7035. case OMPD_target_enter_data:
  7036. case OMPD_target_exit_data:
  7037. case OMPD_target_update:
  7038. // Do not capture if-clause expressions.
  7039. break;
  7040. case OMPD_threadprivate:
  7041. case OMPD_taskyield:
  7042. case OMPD_barrier:
  7043. case OMPD_taskwait:
  7044. case OMPD_cancellation_point:
  7045. case OMPD_flush:
  7046. case OMPD_declare_reduction:
  7047. case OMPD_declare_simd:
  7048. case OMPD_declare_target:
  7049. case OMPD_end_declare_target:
  7050. case OMPD_teams:
  7051. case OMPD_simd:
  7052. case OMPD_for:
  7053. case OMPD_for_simd:
  7054. case OMPD_sections:
  7055. case OMPD_section:
  7056. case OMPD_single:
  7057. case OMPD_master:
  7058. case OMPD_critical:
  7059. case OMPD_taskgroup:
  7060. case OMPD_distribute:
  7061. case OMPD_ordered:
  7062. case OMPD_atomic:
  7063. case OMPD_distribute_simd:
  7064. case OMPD_teams_distribute:
  7065. case OMPD_teams_distribute_simd:
  7066. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7067. case OMPD_unknown:
  7068. llvm_unreachable("Unknown OpenMP directive");
  7069. }
  7070. break;
  7071. case OMPC_num_threads:
  7072. switch (DKind) {
  7073. case OMPD_target_parallel:
  7074. case OMPD_target_parallel_for:
  7075. case OMPD_target_parallel_for_simd:
  7076. case OMPD_target_teams_distribute_parallel_for:
  7077. case OMPD_target_teams_distribute_parallel_for_simd:
  7078. CaptureRegion = OMPD_target;
  7079. break;
  7080. case OMPD_teams_distribute_parallel_for:
  7081. case OMPD_teams_distribute_parallel_for_simd:
  7082. CaptureRegion = OMPD_teams;
  7083. break;
  7084. case OMPD_parallel:
  7085. case OMPD_parallel_sections:
  7086. case OMPD_parallel_for:
  7087. case OMPD_parallel_for_simd:
  7088. case OMPD_distribute_parallel_for:
  7089. case OMPD_distribute_parallel_for_simd:
  7090. // Do not capture num_threads-clause expressions.
  7091. break;
  7092. case OMPD_target_data:
  7093. case OMPD_target_enter_data:
  7094. case OMPD_target_exit_data:
  7095. case OMPD_target_update:
  7096. case OMPD_target:
  7097. case OMPD_target_simd:
  7098. case OMPD_target_teams:
  7099. case OMPD_target_teams_distribute:
  7100. case OMPD_target_teams_distribute_simd:
  7101. case OMPD_cancel:
  7102. case OMPD_task:
  7103. case OMPD_taskloop:
  7104. case OMPD_taskloop_simd:
  7105. case OMPD_threadprivate:
  7106. case OMPD_taskyield:
  7107. case OMPD_barrier:
  7108. case OMPD_taskwait:
  7109. case OMPD_cancellation_point:
  7110. case OMPD_flush:
  7111. case OMPD_declare_reduction:
  7112. case OMPD_declare_simd:
  7113. case OMPD_declare_target:
  7114. case OMPD_end_declare_target:
  7115. case OMPD_teams:
  7116. case OMPD_simd:
  7117. case OMPD_for:
  7118. case OMPD_for_simd:
  7119. case OMPD_sections:
  7120. case OMPD_section:
  7121. case OMPD_single:
  7122. case OMPD_master:
  7123. case OMPD_critical:
  7124. case OMPD_taskgroup:
  7125. case OMPD_distribute:
  7126. case OMPD_ordered:
  7127. case OMPD_atomic:
  7128. case OMPD_distribute_simd:
  7129. case OMPD_teams_distribute:
  7130. case OMPD_teams_distribute_simd:
  7131. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7132. case OMPD_unknown:
  7133. llvm_unreachable("Unknown OpenMP directive");
  7134. }
  7135. break;
  7136. case OMPC_num_teams:
  7137. switch (DKind) {
  7138. case OMPD_target_teams:
  7139. case OMPD_target_teams_distribute:
  7140. case OMPD_target_teams_distribute_simd:
  7141. case OMPD_target_teams_distribute_parallel_for:
  7142. case OMPD_target_teams_distribute_parallel_for_simd:
  7143. CaptureRegion = OMPD_target;
  7144. break;
  7145. case OMPD_teams_distribute_parallel_for:
  7146. case OMPD_teams_distribute_parallel_for_simd:
  7147. case OMPD_teams:
  7148. case OMPD_teams_distribute:
  7149. case OMPD_teams_distribute_simd:
  7150. // Do not capture num_teams-clause expressions.
  7151. break;
  7152. case OMPD_distribute_parallel_for:
  7153. case OMPD_distribute_parallel_for_simd:
  7154. case OMPD_task:
  7155. case OMPD_taskloop:
  7156. case OMPD_taskloop_simd:
  7157. case OMPD_target_data:
  7158. case OMPD_target_enter_data:
  7159. case OMPD_target_exit_data:
  7160. case OMPD_target_update:
  7161. case OMPD_cancel:
  7162. case OMPD_parallel:
  7163. case OMPD_parallel_sections:
  7164. case OMPD_parallel_for:
  7165. case OMPD_parallel_for_simd:
  7166. case OMPD_target:
  7167. case OMPD_target_simd:
  7168. case OMPD_target_parallel:
  7169. case OMPD_target_parallel_for:
  7170. case OMPD_target_parallel_for_simd:
  7171. case OMPD_threadprivate:
  7172. case OMPD_taskyield:
  7173. case OMPD_barrier:
  7174. case OMPD_taskwait:
  7175. case OMPD_cancellation_point:
  7176. case OMPD_flush:
  7177. case OMPD_declare_reduction:
  7178. case OMPD_declare_simd:
  7179. case OMPD_declare_target:
  7180. case OMPD_end_declare_target:
  7181. case OMPD_simd:
  7182. case OMPD_for:
  7183. case OMPD_for_simd:
  7184. case OMPD_sections:
  7185. case OMPD_section:
  7186. case OMPD_single:
  7187. case OMPD_master:
  7188. case OMPD_critical:
  7189. case OMPD_taskgroup:
  7190. case OMPD_distribute:
  7191. case OMPD_ordered:
  7192. case OMPD_atomic:
  7193. case OMPD_distribute_simd:
  7194. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7195. case OMPD_unknown:
  7196. llvm_unreachable("Unknown OpenMP directive");
  7197. }
  7198. break;
  7199. case OMPC_thread_limit:
  7200. switch (DKind) {
  7201. case OMPD_target_teams:
  7202. case OMPD_target_teams_distribute:
  7203. case OMPD_target_teams_distribute_simd:
  7204. case OMPD_target_teams_distribute_parallel_for:
  7205. case OMPD_target_teams_distribute_parallel_for_simd:
  7206. CaptureRegion = OMPD_target;
  7207. break;
  7208. case OMPD_teams_distribute_parallel_for:
  7209. case OMPD_teams_distribute_parallel_for_simd:
  7210. case OMPD_teams:
  7211. case OMPD_teams_distribute:
  7212. case OMPD_teams_distribute_simd:
  7213. // Do not capture thread_limit-clause expressions.
  7214. break;
  7215. case OMPD_distribute_parallel_for:
  7216. case OMPD_distribute_parallel_for_simd:
  7217. case OMPD_task:
  7218. case OMPD_taskloop:
  7219. case OMPD_taskloop_simd:
  7220. case OMPD_target_data:
  7221. case OMPD_target_enter_data:
  7222. case OMPD_target_exit_data:
  7223. case OMPD_target_update:
  7224. case OMPD_cancel:
  7225. case OMPD_parallel:
  7226. case OMPD_parallel_sections:
  7227. case OMPD_parallel_for:
  7228. case OMPD_parallel_for_simd:
  7229. case OMPD_target:
  7230. case OMPD_target_simd:
  7231. case OMPD_target_parallel:
  7232. case OMPD_target_parallel_for:
  7233. case OMPD_target_parallel_for_simd:
  7234. case OMPD_threadprivate:
  7235. case OMPD_taskyield:
  7236. case OMPD_barrier:
  7237. case OMPD_taskwait:
  7238. case OMPD_cancellation_point:
  7239. case OMPD_flush:
  7240. case OMPD_declare_reduction:
  7241. case OMPD_declare_simd:
  7242. case OMPD_declare_target:
  7243. case OMPD_end_declare_target:
  7244. case OMPD_simd:
  7245. case OMPD_for:
  7246. case OMPD_for_simd:
  7247. case OMPD_sections:
  7248. case OMPD_section:
  7249. case OMPD_single:
  7250. case OMPD_master:
  7251. case OMPD_critical:
  7252. case OMPD_taskgroup:
  7253. case OMPD_distribute:
  7254. case OMPD_ordered:
  7255. case OMPD_atomic:
  7256. case OMPD_distribute_simd:
  7257. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7258. case OMPD_unknown:
  7259. llvm_unreachable("Unknown OpenMP directive");
  7260. }
  7261. break;
  7262. case OMPC_schedule:
  7263. switch (DKind) {
  7264. case OMPD_target_parallel_for:
  7265. case OMPD_target_parallel_for_simd:
  7266. case OMPD_target_teams_distribute_parallel_for:
  7267. case OMPD_target_teams_distribute_parallel_for_simd:
  7268. CaptureRegion = OMPD_target;
  7269. break;
  7270. case OMPD_teams_distribute_parallel_for:
  7271. case OMPD_teams_distribute_parallel_for_simd:
  7272. CaptureRegion = OMPD_teams;
  7273. break;
  7274. case OMPD_parallel_for:
  7275. case OMPD_parallel_for_simd:
  7276. case OMPD_distribute_parallel_for:
  7277. case OMPD_distribute_parallel_for_simd:
  7278. CaptureRegion = OMPD_parallel;
  7279. break;
  7280. case OMPD_for:
  7281. case OMPD_for_simd:
  7282. // Do not capture schedule-clause expressions.
  7283. break;
  7284. case OMPD_task:
  7285. case OMPD_taskloop:
  7286. case OMPD_taskloop_simd:
  7287. case OMPD_target_data:
  7288. case OMPD_target_enter_data:
  7289. case OMPD_target_exit_data:
  7290. case OMPD_target_update:
  7291. case OMPD_teams:
  7292. case OMPD_teams_distribute:
  7293. case OMPD_teams_distribute_simd:
  7294. case OMPD_target_teams_distribute:
  7295. case OMPD_target_teams_distribute_simd:
  7296. case OMPD_target:
  7297. case OMPD_target_simd:
  7298. case OMPD_target_parallel:
  7299. case OMPD_cancel:
  7300. case OMPD_parallel:
  7301. case OMPD_parallel_sections:
  7302. case OMPD_threadprivate:
  7303. case OMPD_taskyield:
  7304. case OMPD_barrier:
  7305. case OMPD_taskwait:
  7306. case OMPD_cancellation_point:
  7307. case OMPD_flush:
  7308. case OMPD_declare_reduction:
  7309. case OMPD_declare_simd:
  7310. case OMPD_declare_target:
  7311. case OMPD_end_declare_target:
  7312. case OMPD_simd:
  7313. case OMPD_sections:
  7314. case OMPD_section:
  7315. case OMPD_single:
  7316. case OMPD_master:
  7317. case OMPD_critical:
  7318. case OMPD_taskgroup:
  7319. case OMPD_distribute:
  7320. case OMPD_ordered:
  7321. case OMPD_atomic:
  7322. case OMPD_distribute_simd:
  7323. case OMPD_target_teams:
  7324. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7325. case OMPD_unknown:
  7326. llvm_unreachable("Unknown OpenMP directive");
  7327. }
  7328. break;
  7329. case OMPC_dist_schedule:
  7330. switch (DKind) {
  7331. case OMPD_teams_distribute_parallel_for:
  7332. case OMPD_teams_distribute_parallel_for_simd:
  7333. case OMPD_teams_distribute:
  7334. case OMPD_teams_distribute_simd:
  7335. CaptureRegion = OMPD_teams;
  7336. break;
  7337. case OMPD_target_teams_distribute_parallel_for:
  7338. case OMPD_target_teams_distribute_parallel_for_simd:
  7339. case OMPD_target_teams_distribute:
  7340. case OMPD_target_teams_distribute_simd:
  7341. CaptureRegion = OMPD_target;
  7342. break;
  7343. case OMPD_distribute_parallel_for:
  7344. case OMPD_distribute_parallel_for_simd:
  7345. CaptureRegion = OMPD_parallel;
  7346. break;
  7347. case OMPD_distribute:
  7348. case OMPD_distribute_simd:
  7349. // Do not capture thread_limit-clause expressions.
  7350. break;
  7351. case OMPD_parallel_for:
  7352. case OMPD_parallel_for_simd:
  7353. case OMPD_target_parallel_for_simd:
  7354. case OMPD_target_parallel_for:
  7355. case OMPD_task:
  7356. case OMPD_taskloop:
  7357. case OMPD_taskloop_simd:
  7358. case OMPD_target_data:
  7359. case OMPD_target_enter_data:
  7360. case OMPD_target_exit_data:
  7361. case OMPD_target_update:
  7362. case OMPD_teams:
  7363. case OMPD_target:
  7364. case OMPD_target_simd:
  7365. case OMPD_target_parallel:
  7366. case OMPD_cancel:
  7367. case OMPD_parallel:
  7368. case OMPD_parallel_sections:
  7369. case OMPD_threadprivate:
  7370. case OMPD_taskyield:
  7371. case OMPD_barrier:
  7372. case OMPD_taskwait:
  7373. case OMPD_cancellation_point:
  7374. case OMPD_flush:
  7375. case OMPD_declare_reduction:
  7376. case OMPD_declare_simd:
  7377. case OMPD_declare_target:
  7378. case OMPD_end_declare_target:
  7379. case OMPD_simd:
  7380. case OMPD_for:
  7381. case OMPD_for_simd:
  7382. case OMPD_sections:
  7383. case OMPD_section:
  7384. case OMPD_single:
  7385. case OMPD_master:
  7386. case OMPD_critical:
  7387. case OMPD_taskgroup:
  7388. case OMPD_ordered:
  7389. case OMPD_atomic:
  7390. case OMPD_target_teams:
  7391. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  7392. case OMPD_unknown:
  7393. llvm_unreachable("Unknown OpenMP directive");
  7394. }
  7395. break;
  7396. case OMPC_device:
  7397. switch (DKind) {
  7398. case OMPD_target_teams:
  7399. case OMPD_target_teams_distribute:
  7400. case OMPD_target_teams_distribute_simd:
  7401. case OMPD_target_teams_distribute_parallel_for:
  7402. case OMPD_target_teams_distribute_parallel_for_simd:
  7403. case OMPD_target_data:
  7404. case OMPD_target_enter_data:
  7405. case OMPD_target_exit_data:
  7406. case OMPD_target_update:
  7407. case OMPD_target:
  7408. case OMPD_target_simd:
  7409. case OMPD_target_parallel:
  7410. case OMPD_target_parallel_for:
  7411. case OMPD_target_parallel_for_simd:
  7412. // Do not capture device-clause expressions.
  7413. break;
  7414. case OMPD_teams_distribute_parallel_for:
  7415. case OMPD_teams_distribute_parallel_for_simd:
  7416. case OMPD_teams:
  7417. case OMPD_teams_distribute:
  7418. case OMPD_teams_distribute_simd:
  7419. case OMPD_distribute_parallel_for:
  7420. case OMPD_distribute_parallel_for_simd:
  7421. case OMPD_task:
  7422. case OMPD_taskloop:
  7423. case OMPD_taskloop_simd:
  7424. case OMPD_cancel:
  7425. case OMPD_parallel:
  7426. case OMPD_parallel_sections:
  7427. case OMPD_parallel_for:
  7428. case OMPD_parallel_for_simd:
  7429. case OMPD_threadprivate:
  7430. case OMPD_taskyield:
  7431. case OMPD_barrier:
  7432. case OMPD_taskwait:
  7433. case OMPD_cancellation_point:
  7434. case OMPD_flush:
  7435. case OMPD_declare_reduction:
  7436. case OMPD_declare_simd:
  7437. case OMPD_declare_target:
  7438. case OMPD_end_declare_target:
  7439. case OMPD_simd:
  7440. case OMPD_for:
  7441. case OMPD_for_simd:
  7442. case OMPD_sections:
  7443. case OMPD_section:
  7444. case OMPD_single:
  7445. case OMPD_master:
  7446. case OMPD_critical:
  7447. case OMPD_taskgroup:
  7448. case OMPD_distribute:
  7449. case OMPD_ordered:
  7450. case OMPD_atomic:
  7451. case OMPD_distribute_simd:
  7452. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  7453. case OMPD_unknown:
  7454. llvm_unreachable("Unknown OpenMP directive");
  7455. }
  7456. break;
  7457. case OMPC_firstprivate:
  7458. case OMPC_lastprivate:
  7459. case OMPC_reduction:
  7460. case OMPC_task_reduction:
  7461. case OMPC_in_reduction:
  7462. case OMPC_linear:
  7463. case OMPC_default:
  7464. case OMPC_proc_bind:
  7465. case OMPC_final:
  7466. case OMPC_safelen:
  7467. case OMPC_simdlen:
  7468. case OMPC_collapse:
  7469. case OMPC_private:
  7470. case OMPC_shared:
  7471. case OMPC_aligned:
  7472. case OMPC_copyin:
  7473. case OMPC_copyprivate:
  7474. case OMPC_ordered:
  7475. case OMPC_nowait:
  7476. case OMPC_untied:
  7477. case OMPC_mergeable:
  7478. case OMPC_threadprivate:
  7479. case OMPC_flush:
  7480. case OMPC_read:
  7481. case OMPC_write:
  7482. case OMPC_update:
  7483. case OMPC_capture:
  7484. case OMPC_seq_cst:
  7485. case OMPC_depend:
  7486. case OMPC_threads:
  7487. case OMPC_simd:
  7488. case OMPC_map:
  7489. case OMPC_priority:
  7490. case OMPC_grainsize:
  7491. case OMPC_nogroup:
  7492. case OMPC_num_tasks:
  7493. case OMPC_hint:
  7494. case OMPC_defaultmap:
  7495. case OMPC_unknown:
  7496. case OMPC_uniform:
  7497. case OMPC_to:
  7498. case OMPC_from:
  7499. case OMPC_use_device_ptr:
  7500. case OMPC_is_device_ptr:
  7501. llvm_unreachable("Unexpected OpenMP clause.");
  7502. }
  7503. return CaptureRegion;
  7504. }
  7505. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  7506. Expr *Condition, SourceLocation StartLoc,
  7507. SourceLocation LParenLoc,
  7508. SourceLocation NameModifierLoc,
  7509. SourceLocation ColonLoc,
  7510. SourceLocation EndLoc) {
  7511. Expr *ValExpr = Condition;
  7512. Stmt *HelperValStmt = nullptr;
  7513. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7514. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7515. !Condition->isInstantiationDependent() &&
  7516. !Condition->containsUnexpandedParameterPack()) {
  7517. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7518. if (Val.isInvalid())
  7519. return nullptr;
  7520. ValExpr = MakeFullExpr(Val.get()).get();
  7521. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7522. CaptureRegion =
  7523. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  7524. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7525. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7526. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7527. HelperValStmt = buildPreInits(Context, Captures);
  7528. }
  7529. }
  7530. return new (Context)
  7531. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  7532. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  7533. }
  7534. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  7535. SourceLocation StartLoc,
  7536. SourceLocation LParenLoc,
  7537. SourceLocation EndLoc) {
  7538. Expr *ValExpr = Condition;
  7539. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7540. !Condition->isInstantiationDependent() &&
  7541. !Condition->containsUnexpandedParameterPack()) {
  7542. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7543. if (Val.isInvalid())
  7544. return nullptr;
  7545. ValExpr = MakeFullExpr(Val.get()).get();
  7546. }
  7547. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  7548. }
  7549. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  7550. Expr *Op) {
  7551. if (!Op)
  7552. return ExprError();
  7553. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  7554. public:
  7555. IntConvertDiagnoser()
  7556. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  7557. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  7558. QualType T) override {
  7559. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  7560. }
  7561. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  7562. QualType T) override {
  7563. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  7564. }
  7565. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  7566. QualType T,
  7567. QualType ConvTy) override {
  7568. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  7569. }
  7570. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  7571. QualType ConvTy) override {
  7572. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7573. << ConvTy->isEnumeralType() << ConvTy;
  7574. }
  7575. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  7576. QualType T) override {
  7577. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  7578. }
  7579. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  7580. QualType ConvTy) override {
  7581. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7582. << ConvTy->isEnumeralType() << ConvTy;
  7583. }
  7584. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  7585. QualType) override {
  7586. llvm_unreachable("conversion functions are permitted");
  7587. }
  7588. } ConvertDiagnoser;
  7589. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  7590. }
  7591. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  7592. OpenMPClauseKind CKind,
  7593. bool StrictlyPositive) {
  7594. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  7595. !ValExpr->isInstantiationDependent()) {
  7596. SourceLocation Loc = ValExpr->getExprLoc();
  7597. ExprResult Value =
  7598. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  7599. if (Value.isInvalid())
  7600. return false;
  7601. ValExpr = Value.get();
  7602. // The expression must evaluate to a non-negative integer value.
  7603. llvm::APSInt Result;
  7604. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  7605. Result.isSigned() &&
  7606. !((!StrictlyPositive && Result.isNonNegative()) ||
  7607. (StrictlyPositive && Result.isStrictlyPositive()))) {
  7608. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  7609. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7610. << ValExpr->getSourceRange();
  7611. return false;
  7612. }
  7613. }
  7614. return true;
  7615. }
  7616. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  7617. SourceLocation StartLoc,
  7618. SourceLocation LParenLoc,
  7619. SourceLocation EndLoc) {
  7620. Expr *ValExpr = NumThreads;
  7621. Stmt *HelperValStmt = nullptr;
  7622. // OpenMP [2.5, Restrictions]
  7623. // The num_threads expression must evaluate to a positive integer value.
  7624. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  7625. /*StrictlyPositive=*/true))
  7626. return nullptr;
  7627. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7628. OpenMPDirectiveKind CaptureRegion =
  7629. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  7630. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  7631. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7632. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7633. HelperValStmt = buildPreInits(Context, Captures);
  7634. }
  7635. return new (Context) OMPNumThreadsClause(
  7636. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  7637. }
  7638. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  7639. OpenMPClauseKind CKind,
  7640. bool StrictlyPositive) {
  7641. if (!E)
  7642. return ExprError();
  7643. if (E->isValueDependent() || E->isTypeDependent() ||
  7644. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  7645. return E;
  7646. llvm::APSInt Result;
  7647. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  7648. if (ICE.isInvalid())
  7649. return ExprError();
  7650. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  7651. (!StrictlyPositive && !Result.isNonNegative())) {
  7652. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  7653. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7654. << E->getSourceRange();
  7655. return ExprError();
  7656. }
  7657. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  7658. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  7659. << E->getSourceRange();
  7660. return ExprError();
  7661. }
  7662. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  7663. DSAStack->setAssociatedLoops(Result.getExtValue());
  7664. else if (CKind == OMPC_ordered)
  7665. DSAStack->setAssociatedLoops(Result.getExtValue());
  7666. return ICE;
  7667. }
  7668. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  7669. SourceLocation LParenLoc,
  7670. SourceLocation EndLoc) {
  7671. // OpenMP [2.8.1, simd construct, Description]
  7672. // The parameter of the safelen clause must be a constant
  7673. // positive integer expression.
  7674. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  7675. if (Safelen.isInvalid())
  7676. return nullptr;
  7677. return new (Context)
  7678. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  7679. }
  7680. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  7681. SourceLocation LParenLoc,
  7682. SourceLocation EndLoc) {
  7683. // OpenMP [2.8.1, simd construct, Description]
  7684. // The parameter of the simdlen clause must be a constant
  7685. // positive integer expression.
  7686. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  7687. if (Simdlen.isInvalid())
  7688. return nullptr;
  7689. return new (Context)
  7690. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  7691. }
  7692. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  7693. SourceLocation StartLoc,
  7694. SourceLocation LParenLoc,
  7695. SourceLocation EndLoc) {
  7696. // OpenMP [2.7.1, loop construct, Description]
  7697. // OpenMP [2.8.1, simd construct, Description]
  7698. // OpenMP [2.9.6, distribute construct, Description]
  7699. // The parameter of the collapse clause must be a constant
  7700. // positive integer expression.
  7701. ExprResult NumForLoopsResult =
  7702. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  7703. if (NumForLoopsResult.isInvalid())
  7704. return nullptr;
  7705. return new (Context)
  7706. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  7707. }
  7708. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  7709. SourceLocation EndLoc,
  7710. SourceLocation LParenLoc,
  7711. Expr *NumForLoops) {
  7712. // OpenMP [2.7.1, loop construct, Description]
  7713. // OpenMP [2.8.1, simd construct, Description]
  7714. // OpenMP [2.9.6, distribute construct, Description]
  7715. // The parameter of the ordered clause must be a constant
  7716. // positive integer expression if any.
  7717. if (NumForLoops && LParenLoc.isValid()) {
  7718. ExprResult NumForLoopsResult =
  7719. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  7720. if (NumForLoopsResult.isInvalid())
  7721. return nullptr;
  7722. NumForLoops = NumForLoopsResult.get();
  7723. } else
  7724. NumForLoops = nullptr;
  7725. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  7726. return new (Context)
  7727. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  7728. }
  7729. OMPClause *Sema::ActOnOpenMPSimpleClause(
  7730. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  7731. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  7732. OMPClause *Res = nullptr;
  7733. switch (Kind) {
  7734. case OMPC_default:
  7735. Res =
  7736. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  7737. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  7738. break;
  7739. case OMPC_proc_bind:
  7740. Res = ActOnOpenMPProcBindClause(
  7741. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  7742. LParenLoc, EndLoc);
  7743. break;
  7744. case OMPC_if:
  7745. case OMPC_final:
  7746. case OMPC_num_threads:
  7747. case OMPC_safelen:
  7748. case OMPC_simdlen:
  7749. case OMPC_collapse:
  7750. case OMPC_schedule:
  7751. case OMPC_private:
  7752. case OMPC_firstprivate:
  7753. case OMPC_lastprivate:
  7754. case OMPC_shared:
  7755. case OMPC_reduction:
  7756. case OMPC_task_reduction:
  7757. case OMPC_in_reduction:
  7758. case OMPC_linear:
  7759. case OMPC_aligned:
  7760. case OMPC_copyin:
  7761. case OMPC_copyprivate:
  7762. case OMPC_ordered:
  7763. case OMPC_nowait:
  7764. case OMPC_untied:
  7765. case OMPC_mergeable:
  7766. case OMPC_threadprivate:
  7767. case OMPC_flush:
  7768. case OMPC_read:
  7769. case OMPC_write:
  7770. case OMPC_update:
  7771. case OMPC_capture:
  7772. case OMPC_seq_cst:
  7773. case OMPC_depend:
  7774. case OMPC_device:
  7775. case OMPC_threads:
  7776. case OMPC_simd:
  7777. case OMPC_map:
  7778. case OMPC_num_teams:
  7779. case OMPC_thread_limit:
  7780. case OMPC_priority:
  7781. case OMPC_grainsize:
  7782. case OMPC_nogroup:
  7783. case OMPC_num_tasks:
  7784. case OMPC_hint:
  7785. case OMPC_dist_schedule:
  7786. case OMPC_defaultmap:
  7787. case OMPC_unknown:
  7788. case OMPC_uniform:
  7789. case OMPC_to:
  7790. case OMPC_from:
  7791. case OMPC_use_device_ptr:
  7792. case OMPC_is_device_ptr:
  7793. llvm_unreachable("Clause is not allowed.");
  7794. }
  7795. return Res;
  7796. }
  7797. static std::string
  7798. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  7799. ArrayRef<unsigned> Exclude = llvm::None) {
  7800. std::string Values;
  7801. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  7802. unsigned Skipped = Exclude.size();
  7803. auto S = Exclude.begin(), E = Exclude.end();
  7804. for (unsigned i = First; i < Last; ++i) {
  7805. if (std::find(S, E, i) != E) {
  7806. --Skipped;
  7807. continue;
  7808. }
  7809. Values += "'";
  7810. Values += getOpenMPSimpleClauseTypeName(K, i);
  7811. Values += "'";
  7812. if (i == Bound - Skipped)
  7813. Values += " or ";
  7814. else if (i != Bound + 1 - Skipped)
  7815. Values += ", ";
  7816. }
  7817. return Values;
  7818. }
  7819. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  7820. SourceLocation KindKwLoc,
  7821. SourceLocation StartLoc,
  7822. SourceLocation LParenLoc,
  7823. SourceLocation EndLoc) {
  7824. if (Kind == OMPC_DEFAULT_unknown) {
  7825. static_assert(OMPC_DEFAULT_unknown > 0,
  7826. "OMPC_DEFAULT_unknown not greater than 0");
  7827. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7828. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  7829. /*Last=*/OMPC_DEFAULT_unknown)
  7830. << getOpenMPClauseName(OMPC_default);
  7831. return nullptr;
  7832. }
  7833. switch (Kind) {
  7834. case OMPC_DEFAULT_none:
  7835. DSAStack->setDefaultDSANone(KindKwLoc);
  7836. break;
  7837. case OMPC_DEFAULT_shared:
  7838. DSAStack->setDefaultDSAShared(KindKwLoc);
  7839. break;
  7840. case OMPC_DEFAULT_unknown:
  7841. llvm_unreachable("Clause kind is not allowed.");
  7842. break;
  7843. }
  7844. return new (Context)
  7845. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7846. }
  7847. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  7848. SourceLocation KindKwLoc,
  7849. SourceLocation StartLoc,
  7850. SourceLocation LParenLoc,
  7851. SourceLocation EndLoc) {
  7852. if (Kind == OMPC_PROC_BIND_unknown) {
  7853. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7854. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  7855. /*Last=*/OMPC_PROC_BIND_unknown)
  7856. << getOpenMPClauseName(OMPC_proc_bind);
  7857. return nullptr;
  7858. }
  7859. return new (Context)
  7860. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7861. }
  7862. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  7863. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  7864. SourceLocation StartLoc, SourceLocation LParenLoc,
  7865. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  7866. SourceLocation EndLoc) {
  7867. OMPClause *Res = nullptr;
  7868. switch (Kind) {
  7869. case OMPC_schedule:
  7870. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  7871. assert(Argument.size() == NumberOfElements &&
  7872. ArgumentLoc.size() == NumberOfElements);
  7873. Res = ActOnOpenMPScheduleClause(
  7874. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  7875. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  7876. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  7877. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  7878. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  7879. break;
  7880. case OMPC_if:
  7881. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  7882. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  7883. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  7884. DelimLoc, EndLoc);
  7885. break;
  7886. case OMPC_dist_schedule:
  7887. Res = ActOnOpenMPDistScheduleClause(
  7888. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  7889. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  7890. break;
  7891. case OMPC_defaultmap:
  7892. enum { Modifier, DefaultmapKind };
  7893. Res = ActOnOpenMPDefaultmapClause(
  7894. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  7895. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  7896. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  7897. EndLoc);
  7898. break;
  7899. case OMPC_final:
  7900. case OMPC_num_threads:
  7901. case OMPC_safelen:
  7902. case OMPC_simdlen:
  7903. case OMPC_collapse:
  7904. case OMPC_default:
  7905. case OMPC_proc_bind:
  7906. case OMPC_private:
  7907. case OMPC_firstprivate:
  7908. case OMPC_lastprivate:
  7909. case OMPC_shared:
  7910. case OMPC_reduction:
  7911. case OMPC_task_reduction:
  7912. case OMPC_in_reduction:
  7913. case OMPC_linear:
  7914. case OMPC_aligned:
  7915. case OMPC_copyin:
  7916. case OMPC_copyprivate:
  7917. case OMPC_ordered:
  7918. case OMPC_nowait:
  7919. case OMPC_untied:
  7920. case OMPC_mergeable:
  7921. case OMPC_threadprivate:
  7922. case OMPC_flush:
  7923. case OMPC_read:
  7924. case OMPC_write:
  7925. case OMPC_update:
  7926. case OMPC_capture:
  7927. case OMPC_seq_cst:
  7928. case OMPC_depend:
  7929. case OMPC_device:
  7930. case OMPC_threads:
  7931. case OMPC_simd:
  7932. case OMPC_map:
  7933. case OMPC_num_teams:
  7934. case OMPC_thread_limit:
  7935. case OMPC_priority:
  7936. case OMPC_grainsize:
  7937. case OMPC_nogroup:
  7938. case OMPC_num_tasks:
  7939. case OMPC_hint:
  7940. case OMPC_unknown:
  7941. case OMPC_uniform:
  7942. case OMPC_to:
  7943. case OMPC_from:
  7944. case OMPC_use_device_ptr:
  7945. case OMPC_is_device_ptr:
  7946. llvm_unreachable("Clause is not allowed.");
  7947. }
  7948. return Res;
  7949. }
  7950. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  7951. OpenMPScheduleClauseModifier M2,
  7952. SourceLocation M1Loc, SourceLocation M2Loc) {
  7953. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  7954. SmallVector<unsigned, 2> Excluded;
  7955. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  7956. Excluded.push_back(M2);
  7957. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  7958. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  7959. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  7960. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  7961. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  7962. << getListOfPossibleValues(OMPC_schedule,
  7963. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  7964. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  7965. Excluded)
  7966. << getOpenMPClauseName(OMPC_schedule);
  7967. return true;
  7968. }
  7969. return false;
  7970. }
  7971. OMPClause *Sema::ActOnOpenMPScheduleClause(
  7972. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  7973. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  7974. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  7975. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  7976. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  7977. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  7978. return nullptr;
  7979. // OpenMP, 2.7.1, Loop Construct, Restrictions
  7980. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  7981. // but not both.
  7982. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  7983. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  7984. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  7985. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  7986. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  7987. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  7988. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  7989. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  7990. return nullptr;
  7991. }
  7992. if (Kind == OMPC_SCHEDULE_unknown) {
  7993. std::string Values;
  7994. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  7995. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  7996. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  7997. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  7998. Exclude);
  7999. } else {
  8000. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8001. /*Last=*/OMPC_SCHEDULE_unknown);
  8002. }
  8003. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8004. << Values << getOpenMPClauseName(OMPC_schedule);
  8005. return nullptr;
  8006. }
  8007. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8008. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8009. // schedule(guided).
  8010. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8011. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8012. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8013. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8014. diag::err_omp_schedule_nonmonotonic_static);
  8015. return nullptr;
  8016. }
  8017. Expr *ValExpr = ChunkSize;
  8018. Stmt *HelperValStmt = nullptr;
  8019. if (ChunkSize) {
  8020. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8021. !ChunkSize->isInstantiationDependent() &&
  8022. !ChunkSize->containsUnexpandedParameterPack()) {
  8023. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  8024. ExprResult Val =
  8025. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8026. if (Val.isInvalid())
  8027. return nullptr;
  8028. ValExpr = Val.get();
  8029. // OpenMP [2.7.1, Restrictions]
  8030. // chunk_size must be a loop invariant integer expression with a positive
  8031. // value.
  8032. llvm::APSInt Result;
  8033. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8034. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8035. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8036. << "schedule" << 1 << ChunkSize->getSourceRange();
  8037. return nullptr;
  8038. }
  8039. } else if (getOpenMPCaptureRegionForClause(
  8040. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8041. OMPD_unknown &&
  8042. !CurContext->isDependentContext()) {
  8043. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  8044. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8045. HelperValStmt = buildPreInits(Context, Captures);
  8046. }
  8047. }
  8048. }
  8049. return new (Context)
  8050. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8051. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8052. }
  8053. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8054. SourceLocation StartLoc,
  8055. SourceLocation EndLoc) {
  8056. OMPClause *Res = nullptr;
  8057. switch (Kind) {
  8058. case OMPC_ordered:
  8059. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8060. break;
  8061. case OMPC_nowait:
  8062. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8063. break;
  8064. case OMPC_untied:
  8065. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8066. break;
  8067. case OMPC_mergeable:
  8068. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8069. break;
  8070. case OMPC_read:
  8071. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8072. break;
  8073. case OMPC_write:
  8074. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8075. break;
  8076. case OMPC_update:
  8077. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8078. break;
  8079. case OMPC_capture:
  8080. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8081. break;
  8082. case OMPC_seq_cst:
  8083. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8084. break;
  8085. case OMPC_threads:
  8086. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8087. break;
  8088. case OMPC_simd:
  8089. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8090. break;
  8091. case OMPC_nogroup:
  8092. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8093. break;
  8094. case OMPC_if:
  8095. case OMPC_final:
  8096. case OMPC_num_threads:
  8097. case OMPC_safelen:
  8098. case OMPC_simdlen:
  8099. case OMPC_collapse:
  8100. case OMPC_schedule:
  8101. case OMPC_private:
  8102. case OMPC_firstprivate:
  8103. case OMPC_lastprivate:
  8104. case OMPC_shared:
  8105. case OMPC_reduction:
  8106. case OMPC_task_reduction:
  8107. case OMPC_in_reduction:
  8108. case OMPC_linear:
  8109. case OMPC_aligned:
  8110. case OMPC_copyin:
  8111. case OMPC_copyprivate:
  8112. case OMPC_default:
  8113. case OMPC_proc_bind:
  8114. case OMPC_threadprivate:
  8115. case OMPC_flush:
  8116. case OMPC_depend:
  8117. case OMPC_device:
  8118. case OMPC_map:
  8119. case OMPC_num_teams:
  8120. case OMPC_thread_limit:
  8121. case OMPC_priority:
  8122. case OMPC_grainsize:
  8123. case OMPC_num_tasks:
  8124. case OMPC_hint:
  8125. case OMPC_dist_schedule:
  8126. case OMPC_defaultmap:
  8127. case OMPC_unknown:
  8128. case OMPC_uniform:
  8129. case OMPC_to:
  8130. case OMPC_from:
  8131. case OMPC_use_device_ptr:
  8132. case OMPC_is_device_ptr:
  8133. llvm_unreachable("Clause is not allowed.");
  8134. }
  8135. return Res;
  8136. }
  8137. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  8138. SourceLocation EndLoc) {
  8139. DSAStack->setNowaitRegion();
  8140. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  8141. }
  8142. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  8143. SourceLocation EndLoc) {
  8144. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  8145. }
  8146. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  8147. SourceLocation EndLoc) {
  8148. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  8149. }
  8150. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  8151. SourceLocation EndLoc) {
  8152. return new (Context) OMPReadClause(StartLoc, EndLoc);
  8153. }
  8154. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  8155. SourceLocation EndLoc) {
  8156. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  8157. }
  8158. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  8159. SourceLocation EndLoc) {
  8160. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  8161. }
  8162. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  8163. SourceLocation EndLoc) {
  8164. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  8165. }
  8166. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  8167. SourceLocation EndLoc) {
  8168. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  8169. }
  8170. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  8171. SourceLocation EndLoc) {
  8172. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  8173. }
  8174. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  8175. SourceLocation EndLoc) {
  8176. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  8177. }
  8178. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  8179. SourceLocation EndLoc) {
  8180. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  8181. }
  8182. OMPClause *Sema::ActOnOpenMPVarListClause(
  8183. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  8184. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  8185. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  8186. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  8187. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  8188. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8189. SourceLocation DepLinMapLoc) {
  8190. OMPClause *Res = nullptr;
  8191. switch (Kind) {
  8192. case OMPC_private:
  8193. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8194. break;
  8195. case OMPC_firstprivate:
  8196. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8197. break;
  8198. case OMPC_lastprivate:
  8199. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8200. break;
  8201. case OMPC_shared:
  8202. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  8203. break;
  8204. case OMPC_reduction:
  8205. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8206. EndLoc, ReductionIdScopeSpec, ReductionId);
  8207. break;
  8208. case OMPC_task_reduction:
  8209. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8210. EndLoc, ReductionIdScopeSpec,
  8211. ReductionId);
  8212. break;
  8213. case OMPC_in_reduction:
  8214. Res =
  8215. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  8216. EndLoc, ReductionIdScopeSpec, ReductionId);
  8217. break;
  8218. case OMPC_linear:
  8219. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  8220. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  8221. break;
  8222. case OMPC_aligned:
  8223. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  8224. ColonLoc, EndLoc);
  8225. break;
  8226. case OMPC_copyin:
  8227. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  8228. break;
  8229. case OMPC_copyprivate:
  8230. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  8231. break;
  8232. case OMPC_flush:
  8233. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  8234. break;
  8235. case OMPC_depend:
  8236. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  8237. StartLoc, LParenLoc, EndLoc);
  8238. break;
  8239. case OMPC_map:
  8240. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  8241. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  8242. LParenLoc, EndLoc);
  8243. break;
  8244. case OMPC_to:
  8245. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  8246. break;
  8247. case OMPC_from:
  8248. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  8249. break;
  8250. case OMPC_use_device_ptr:
  8251. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8252. break;
  8253. case OMPC_is_device_ptr:
  8254. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  8255. break;
  8256. case OMPC_if:
  8257. case OMPC_final:
  8258. case OMPC_num_threads:
  8259. case OMPC_safelen:
  8260. case OMPC_simdlen:
  8261. case OMPC_collapse:
  8262. case OMPC_default:
  8263. case OMPC_proc_bind:
  8264. case OMPC_schedule:
  8265. case OMPC_ordered:
  8266. case OMPC_nowait:
  8267. case OMPC_untied:
  8268. case OMPC_mergeable:
  8269. case OMPC_threadprivate:
  8270. case OMPC_read:
  8271. case OMPC_write:
  8272. case OMPC_update:
  8273. case OMPC_capture:
  8274. case OMPC_seq_cst:
  8275. case OMPC_device:
  8276. case OMPC_threads:
  8277. case OMPC_simd:
  8278. case OMPC_num_teams:
  8279. case OMPC_thread_limit:
  8280. case OMPC_priority:
  8281. case OMPC_grainsize:
  8282. case OMPC_nogroup:
  8283. case OMPC_num_tasks:
  8284. case OMPC_hint:
  8285. case OMPC_dist_schedule:
  8286. case OMPC_defaultmap:
  8287. case OMPC_unknown:
  8288. case OMPC_uniform:
  8289. llvm_unreachable("Clause is not allowed.");
  8290. }
  8291. return Res;
  8292. }
  8293. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  8294. ExprObjectKind OK, SourceLocation Loc) {
  8295. ExprResult Res = BuildDeclRefExpr(
  8296. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  8297. if (!Res.isUsable())
  8298. return ExprError();
  8299. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  8300. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  8301. if (!Res.isUsable())
  8302. return ExprError();
  8303. }
  8304. if (VK != VK_LValue && Res.get()->isGLValue()) {
  8305. Res = DefaultLvalueConversion(Res.get());
  8306. if (!Res.isUsable())
  8307. return ExprError();
  8308. }
  8309. return Res;
  8310. }
  8311. static std::pair<ValueDecl *, bool>
  8312. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  8313. SourceRange &ERange, bool AllowArraySection = false) {
  8314. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  8315. RefExpr->containsUnexpandedParameterPack())
  8316. return std::make_pair(nullptr, true);
  8317. // OpenMP [3.1, C/C++]
  8318. // A list item is a variable name.
  8319. // OpenMP [2.9.3.3, Restrictions, p.1]
  8320. // A variable that is part of another variable (as an array or
  8321. // structure element) cannot appear in a private clause.
  8322. RefExpr = RefExpr->IgnoreParens();
  8323. enum {
  8324. NoArrayExpr = -1,
  8325. ArraySubscript = 0,
  8326. OMPArraySection = 1
  8327. } IsArrayExpr = NoArrayExpr;
  8328. if (AllowArraySection) {
  8329. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  8330. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  8331. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8332. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8333. RefExpr = Base;
  8334. IsArrayExpr = ArraySubscript;
  8335. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  8336. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  8337. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  8338. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  8339. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  8340. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8341. RefExpr = Base;
  8342. IsArrayExpr = OMPArraySection;
  8343. }
  8344. }
  8345. ELoc = RefExpr->getExprLoc();
  8346. ERange = RefExpr->getSourceRange();
  8347. RefExpr = RefExpr->IgnoreParenImpCasts();
  8348. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  8349. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  8350. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  8351. (S.getCurrentThisType().isNull() || !ME ||
  8352. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  8353. !isa<FieldDecl>(ME->getMemberDecl()))) {
  8354. if (IsArrayExpr != NoArrayExpr)
  8355. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  8356. << ERange;
  8357. else {
  8358. S.Diag(ELoc,
  8359. AllowArraySection
  8360. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  8361. : diag::err_omp_expected_var_name_member_expr)
  8362. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  8363. }
  8364. return std::make_pair(nullptr, false);
  8365. }
  8366. return std::make_pair(
  8367. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  8368. }
  8369. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  8370. SourceLocation StartLoc,
  8371. SourceLocation LParenLoc,
  8372. SourceLocation EndLoc) {
  8373. SmallVector<Expr *, 8> Vars;
  8374. SmallVector<Expr *, 8> PrivateCopies;
  8375. for (auto &RefExpr : VarList) {
  8376. assert(RefExpr && "NULL expr in OpenMP private clause.");
  8377. SourceLocation ELoc;
  8378. SourceRange ERange;
  8379. Expr *SimpleRefExpr = RefExpr;
  8380. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8381. if (Res.second) {
  8382. // It will be analyzed later.
  8383. Vars.push_back(RefExpr);
  8384. PrivateCopies.push_back(nullptr);
  8385. }
  8386. ValueDecl *D = Res.first;
  8387. if (!D)
  8388. continue;
  8389. QualType Type = D->getType();
  8390. auto *VD = dyn_cast<VarDecl>(D);
  8391. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8392. // A variable that appears in a private clause must not have an incomplete
  8393. // type or a reference type.
  8394. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  8395. continue;
  8396. Type = Type.getNonReferenceType();
  8397. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8398. // in a Construct]
  8399. // Variables with the predetermined data-sharing attributes may not be
  8400. // listed in data-sharing attributes clauses, except for the cases
  8401. // listed below. For these exceptions only, listing a predetermined
  8402. // variable in a data-sharing attribute clause is allowed and overrides
  8403. // the variable's predetermined data-sharing attributes.
  8404. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8405. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  8406. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8407. << getOpenMPClauseName(OMPC_private);
  8408. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8409. continue;
  8410. }
  8411. auto CurrDir = DSAStack->getCurrentDirective();
  8412. // Variably modified types are not supported for tasks.
  8413. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8414. isOpenMPTaskingDirective(CurrDir)) {
  8415. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8416. << getOpenMPClauseName(OMPC_private) << Type
  8417. << getOpenMPDirectiveName(CurrDir);
  8418. bool IsDecl =
  8419. !VD ||
  8420. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8421. Diag(D->getLocation(),
  8422. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8423. << D;
  8424. continue;
  8425. }
  8426. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8427. // A list item cannot appear in both a map clause and a data-sharing
  8428. // attribute clause on the same construct
  8429. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  8430. CurrDir == OMPD_target_teams ||
  8431. CurrDir == OMPD_target_teams_distribute ||
  8432. CurrDir == OMPD_target_teams_distribute_parallel_for ||
  8433. CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
  8434. CurrDir == OMPD_target_teams_distribute_simd ||
  8435. CurrDir == OMPD_target_parallel_for_simd ||
  8436. CurrDir == OMPD_target_parallel_for) {
  8437. OpenMPClauseKind ConflictKind;
  8438. if (DSAStack->checkMappableExprComponentListsForDecl(
  8439. VD, /*CurrentRegionOnly=*/true,
  8440. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8441. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8442. ConflictKind = WhereFoundClauseKind;
  8443. return true;
  8444. })) {
  8445. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8446. << getOpenMPClauseName(OMPC_private)
  8447. << getOpenMPClauseName(ConflictKind)
  8448. << getOpenMPDirectiveName(CurrDir);
  8449. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8450. continue;
  8451. }
  8452. }
  8453. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  8454. // A variable of class type (or array thereof) that appears in a private
  8455. // clause requires an accessible, unambiguous default constructor for the
  8456. // class type.
  8457. // Generate helper private variable and initialize it with the default
  8458. // value. The address of the original variable is replaced by the address of
  8459. // the new private variable in CodeGen. This new variable is not added to
  8460. // IdResolver, so the code in the OpenMP region uses original variable for
  8461. // proper diagnostics.
  8462. Type = Type.getUnqualifiedType();
  8463. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8464. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8465. ActOnUninitializedDecl(VDPrivate);
  8466. if (VDPrivate->isInvalidDecl())
  8467. continue;
  8468. auto VDPrivateRefExpr = buildDeclRefExpr(
  8469. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  8470. DeclRefExpr *Ref = nullptr;
  8471. if (!VD && !CurContext->isDependentContext())
  8472. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8473. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  8474. Vars.push_back((VD || CurContext->isDependentContext())
  8475. ? RefExpr->IgnoreParens()
  8476. : Ref);
  8477. PrivateCopies.push_back(VDPrivateRefExpr);
  8478. }
  8479. if (Vars.empty())
  8480. return nullptr;
  8481. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8482. PrivateCopies);
  8483. }
  8484. namespace {
  8485. class DiagsUninitializedSeveretyRAII {
  8486. private:
  8487. DiagnosticsEngine &Diags;
  8488. SourceLocation SavedLoc;
  8489. bool IsIgnored;
  8490. public:
  8491. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  8492. bool IsIgnored)
  8493. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  8494. if (!IsIgnored) {
  8495. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  8496. /*Map*/ diag::Severity::Ignored, Loc);
  8497. }
  8498. }
  8499. ~DiagsUninitializedSeveretyRAII() {
  8500. if (!IsIgnored)
  8501. Diags.popMappings(SavedLoc);
  8502. }
  8503. };
  8504. }
  8505. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  8506. SourceLocation StartLoc,
  8507. SourceLocation LParenLoc,
  8508. SourceLocation EndLoc) {
  8509. SmallVector<Expr *, 8> Vars;
  8510. SmallVector<Expr *, 8> PrivateCopies;
  8511. SmallVector<Expr *, 8> Inits;
  8512. SmallVector<Decl *, 4> ExprCaptures;
  8513. bool IsImplicitClause =
  8514. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  8515. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  8516. for (auto &RefExpr : VarList) {
  8517. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  8518. SourceLocation ELoc;
  8519. SourceRange ERange;
  8520. Expr *SimpleRefExpr = RefExpr;
  8521. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8522. if (Res.second) {
  8523. // It will be analyzed later.
  8524. Vars.push_back(RefExpr);
  8525. PrivateCopies.push_back(nullptr);
  8526. Inits.push_back(nullptr);
  8527. }
  8528. ValueDecl *D = Res.first;
  8529. if (!D)
  8530. continue;
  8531. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  8532. QualType Type = D->getType();
  8533. auto *VD = dyn_cast<VarDecl>(D);
  8534. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8535. // A variable that appears in a private clause must not have an incomplete
  8536. // type or a reference type.
  8537. if (RequireCompleteType(ELoc, Type,
  8538. diag::err_omp_firstprivate_incomplete_type))
  8539. continue;
  8540. Type = Type.getNonReferenceType();
  8541. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  8542. // A variable of class type (or array thereof) that appears in a private
  8543. // clause requires an accessible, unambiguous copy constructor for the
  8544. // class type.
  8545. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8546. // If an implicit firstprivate variable found it was checked already.
  8547. DSAStackTy::DSAVarData TopDVar;
  8548. if (!IsImplicitClause) {
  8549. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8550. TopDVar = DVar;
  8551. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8552. bool IsConstant = ElemType.isConstant(Context);
  8553. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  8554. // A list item that specifies a given variable may not appear in more
  8555. // than one clause on the same directive, except that a variable may be
  8556. // specified in both firstprivate and lastprivate clauses.
  8557. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8558. // A list item may appear in a firstprivate or lastprivate clause but not
  8559. // both.
  8560. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  8561. (isOpenMPDistributeDirective(CurrDir) ||
  8562. DVar.CKind != OMPC_lastprivate) &&
  8563. DVar.RefExpr) {
  8564. Diag(ELoc, diag::err_omp_wrong_dsa)
  8565. << getOpenMPClauseName(DVar.CKind)
  8566. << getOpenMPClauseName(OMPC_firstprivate);
  8567. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8568. continue;
  8569. }
  8570. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8571. // in a Construct]
  8572. // Variables with the predetermined data-sharing attributes may not be
  8573. // listed in data-sharing attributes clauses, except for the cases
  8574. // listed below. For these exceptions only, listing a predetermined
  8575. // variable in a data-sharing attribute clause is allowed and overrides
  8576. // the variable's predetermined data-sharing attributes.
  8577. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8578. // in a Construct, C/C++, p.2]
  8579. // Variables with const-qualified type having no mutable member may be
  8580. // listed in a firstprivate clause, even if they are static data members.
  8581. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  8582. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  8583. Diag(ELoc, diag::err_omp_wrong_dsa)
  8584. << getOpenMPClauseName(DVar.CKind)
  8585. << getOpenMPClauseName(OMPC_firstprivate);
  8586. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8587. continue;
  8588. }
  8589. // OpenMP [2.9.3.4, Restrictions, p.2]
  8590. // A list item that is private within a parallel region must not appear
  8591. // in a firstprivate clause on a worksharing construct if any of the
  8592. // worksharing regions arising from the worksharing construct ever bind
  8593. // to any of the parallel regions arising from the parallel construct.
  8594. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8595. // A list item that is private within a teams region must not appear in a
  8596. // firstprivate clause on a distribute construct if any of the distribute
  8597. // regions arising from the distribute construct ever bind to any of the
  8598. // teams regions arising from the teams construct.
  8599. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8600. // A list item that appears in a reduction clause of a teams construct
  8601. // must not appear in a firstprivate clause on a distribute construct if
  8602. // any of the distribute regions arising from the distribute construct
  8603. // ever bind to any of the teams regions arising from the teams construct.
  8604. if ((isOpenMPWorksharingDirective(CurrDir) ||
  8605. isOpenMPDistributeDirective(CurrDir)) &&
  8606. !isOpenMPParallelDirective(CurrDir) &&
  8607. !isOpenMPTeamsDirective(CurrDir)) {
  8608. DVar = DSAStack->getImplicitDSA(D, true);
  8609. if (DVar.CKind != OMPC_shared &&
  8610. (isOpenMPParallelDirective(DVar.DKind) ||
  8611. isOpenMPTeamsDirective(DVar.DKind) ||
  8612. DVar.DKind == OMPD_unknown)) {
  8613. Diag(ELoc, diag::err_omp_required_access)
  8614. << getOpenMPClauseName(OMPC_firstprivate)
  8615. << getOpenMPClauseName(OMPC_shared);
  8616. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8617. continue;
  8618. }
  8619. }
  8620. // OpenMP [2.9.3.4, Restrictions, p.3]
  8621. // A list item that appears in a reduction clause of a parallel construct
  8622. // must not appear in a firstprivate clause on a worksharing or task
  8623. // construct if any of the worksharing or task regions arising from the
  8624. // worksharing or task construct ever bind to any of the parallel regions
  8625. // arising from the parallel construct.
  8626. // OpenMP [2.9.3.4, Restrictions, p.4]
  8627. // A list item that appears in a reduction clause in worksharing
  8628. // construct must not appear in a firstprivate clause in a task construct
  8629. // encountered during execution of any of the worksharing regions arising
  8630. // from the worksharing construct.
  8631. if (isOpenMPTaskingDirective(CurrDir)) {
  8632. DVar = DSAStack->hasInnermostDSA(
  8633. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  8634. [](OpenMPDirectiveKind K) -> bool {
  8635. return isOpenMPParallelDirective(K) ||
  8636. isOpenMPWorksharingDirective(K) ||
  8637. isOpenMPTeamsDirective(K);
  8638. },
  8639. /*FromParent=*/true);
  8640. if (DVar.CKind == OMPC_reduction &&
  8641. (isOpenMPParallelDirective(DVar.DKind) ||
  8642. isOpenMPWorksharingDirective(DVar.DKind) ||
  8643. isOpenMPTeamsDirective(DVar.DKind))) {
  8644. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  8645. << getOpenMPDirectiveName(DVar.DKind);
  8646. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8647. continue;
  8648. }
  8649. }
  8650. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8651. // A list item cannot appear in both a map clause and a data-sharing
  8652. // attribute clause on the same construct
  8653. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  8654. OpenMPClauseKind ConflictKind;
  8655. if (DSAStack->checkMappableExprComponentListsForDecl(
  8656. VD, /*CurrentRegionOnly=*/true,
  8657. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8658. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8659. ConflictKind = WhereFoundClauseKind;
  8660. return true;
  8661. })) {
  8662. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8663. << getOpenMPClauseName(OMPC_firstprivate)
  8664. << getOpenMPClauseName(ConflictKind)
  8665. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8666. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8667. continue;
  8668. }
  8669. }
  8670. }
  8671. // Variably modified types are not supported for tasks.
  8672. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8673. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  8674. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8675. << getOpenMPClauseName(OMPC_firstprivate) << Type
  8676. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8677. bool IsDecl =
  8678. !VD ||
  8679. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8680. Diag(D->getLocation(),
  8681. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8682. << D;
  8683. continue;
  8684. }
  8685. Type = Type.getUnqualifiedType();
  8686. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8687. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8688. // Generate helper private variable and initialize it with the value of the
  8689. // original variable. The address of the original variable is replaced by
  8690. // the address of the new private variable in the CodeGen. This new variable
  8691. // is not added to IdResolver, so the code in the OpenMP region uses
  8692. // original variable for proper diagnostics and variable capturing.
  8693. Expr *VDInitRefExpr = nullptr;
  8694. // For arrays generate initializer for single element and replace it by the
  8695. // original array element in CodeGen.
  8696. if (Type->isArrayType()) {
  8697. auto VDInit =
  8698. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  8699. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  8700. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  8701. ElemType = ElemType.getUnqualifiedType();
  8702. auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  8703. ".firstprivate.temp");
  8704. InitializedEntity Entity =
  8705. InitializedEntity::InitializeVariable(VDInitTemp);
  8706. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  8707. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  8708. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  8709. if (Result.isInvalid())
  8710. VDPrivate->setInvalidDecl();
  8711. else
  8712. VDPrivate->setInit(Result.getAs<Expr>());
  8713. // Remove temp variable declaration.
  8714. Context.Deallocate(VDInitTemp);
  8715. } else {
  8716. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  8717. ".firstprivate.temp");
  8718. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  8719. RefExpr->getExprLoc());
  8720. AddInitializerToDecl(VDPrivate,
  8721. DefaultLvalueConversion(VDInitRefExpr).get(),
  8722. /*DirectInit=*/false);
  8723. }
  8724. if (VDPrivate->isInvalidDecl()) {
  8725. if (IsImplicitClause) {
  8726. Diag(RefExpr->getExprLoc(),
  8727. diag::note_omp_task_predetermined_firstprivate_here);
  8728. }
  8729. continue;
  8730. }
  8731. CurContext->addDecl(VDPrivate);
  8732. auto VDPrivateRefExpr = buildDeclRefExpr(
  8733. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  8734. RefExpr->getExprLoc());
  8735. DeclRefExpr *Ref = nullptr;
  8736. if (!VD && !CurContext->isDependentContext()) {
  8737. if (TopDVar.CKind == OMPC_lastprivate)
  8738. Ref = TopDVar.PrivateCopy;
  8739. else {
  8740. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8741. if (!IsOpenMPCapturedDecl(D))
  8742. ExprCaptures.push_back(Ref->getDecl());
  8743. }
  8744. }
  8745. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  8746. Vars.push_back((VD || CurContext->isDependentContext())
  8747. ? RefExpr->IgnoreParens()
  8748. : Ref);
  8749. PrivateCopies.push_back(VDPrivateRefExpr);
  8750. Inits.push_back(VDInitRefExpr);
  8751. }
  8752. if (Vars.empty())
  8753. return nullptr;
  8754. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8755. Vars, PrivateCopies, Inits,
  8756. buildPreInits(Context, ExprCaptures));
  8757. }
  8758. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  8759. SourceLocation StartLoc,
  8760. SourceLocation LParenLoc,
  8761. SourceLocation EndLoc) {
  8762. SmallVector<Expr *, 8> Vars;
  8763. SmallVector<Expr *, 8> SrcExprs;
  8764. SmallVector<Expr *, 8> DstExprs;
  8765. SmallVector<Expr *, 8> AssignmentOps;
  8766. SmallVector<Decl *, 4> ExprCaptures;
  8767. SmallVector<Expr *, 4> ExprPostUpdates;
  8768. for (auto &RefExpr : VarList) {
  8769. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8770. SourceLocation ELoc;
  8771. SourceRange ERange;
  8772. Expr *SimpleRefExpr = RefExpr;
  8773. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8774. if (Res.second) {
  8775. // It will be analyzed later.
  8776. Vars.push_back(RefExpr);
  8777. SrcExprs.push_back(nullptr);
  8778. DstExprs.push_back(nullptr);
  8779. AssignmentOps.push_back(nullptr);
  8780. }
  8781. ValueDecl *D = Res.first;
  8782. if (!D)
  8783. continue;
  8784. QualType Type = D->getType();
  8785. auto *VD = dyn_cast<VarDecl>(D);
  8786. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  8787. // A variable that appears in a lastprivate clause must not have an
  8788. // incomplete type or a reference type.
  8789. if (RequireCompleteType(ELoc, Type,
  8790. diag::err_omp_lastprivate_incomplete_type))
  8791. continue;
  8792. Type = Type.getNonReferenceType();
  8793. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8794. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  8795. // in a Construct]
  8796. // Variables with the predetermined data-sharing attributes may not be
  8797. // listed in data-sharing attributes clauses, except for the cases
  8798. // listed below.
  8799. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8800. // A list item may appear in a firstprivate or lastprivate clause but not
  8801. // both.
  8802. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8803. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  8804. (isOpenMPDistributeDirective(CurrDir) ||
  8805. DVar.CKind != OMPC_firstprivate) &&
  8806. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  8807. Diag(ELoc, diag::err_omp_wrong_dsa)
  8808. << getOpenMPClauseName(DVar.CKind)
  8809. << getOpenMPClauseName(OMPC_lastprivate);
  8810. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8811. continue;
  8812. }
  8813. // OpenMP [2.14.3.5, Restrictions, p.2]
  8814. // A list item that is private within a parallel region, or that appears in
  8815. // the reduction clause of a parallel construct, must not appear in a
  8816. // lastprivate clause on a worksharing construct if any of the corresponding
  8817. // worksharing regions ever binds to any of the corresponding parallel
  8818. // regions.
  8819. DSAStackTy::DSAVarData TopDVar = DVar;
  8820. if (isOpenMPWorksharingDirective(CurrDir) &&
  8821. !isOpenMPParallelDirective(CurrDir) &&
  8822. !isOpenMPTeamsDirective(CurrDir)) {
  8823. DVar = DSAStack->getImplicitDSA(D, true);
  8824. if (DVar.CKind != OMPC_shared) {
  8825. Diag(ELoc, diag::err_omp_required_access)
  8826. << getOpenMPClauseName(OMPC_lastprivate)
  8827. << getOpenMPClauseName(OMPC_shared);
  8828. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8829. continue;
  8830. }
  8831. }
  8832. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  8833. // A variable of class type (or array thereof) that appears in a
  8834. // lastprivate clause requires an accessible, unambiguous default
  8835. // constructor for the class type, unless the list item is also specified
  8836. // in a firstprivate clause.
  8837. // A variable of class type (or array thereof) that appears in a
  8838. // lastprivate clause requires an accessible, unambiguous copy assignment
  8839. // operator for the class type.
  8840. Type = Context.getBaseElementType(Type).getNonReferenceType();
  8841. auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  8842. Type.getUnqualifiedType(), ".lastprivate.src",
  8843. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8844. auto *PseudoSrcExpr =
  8845. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  8846. auto *DstVD =
  8847. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  8848. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8849. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  8850. // For arrays generate assignment operation for single element and replace
  8851. // it by the original array element in CodeGen.
  8852. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  8853. PseudoDstExpr, PseudoSrcExpr);
  8854. if (AssignmentOp.isInvalid())
  8855. continue;
  8856. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  8857. /*DiscardedValue=*/true);
  8858. if (AssignmentOp.isInvalid())
  8859. continue;
  8860. DeclRefExpr *Ref = nullptr;
  8861. if (!VD && !CurContext->isDependentContext()) {
  8862. if (TopDVar.CKind == OMPC_firstprivate)
  8863. Ref = TopDVar.PrivateCopy;
  8864. else {
  8865. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8866. if (!IsOpenMPCapturedDecl(D))
  8867. ExprCaptures.push_back(Ref->getDecl());
  8868. }
  8869. if (TopDVar.CKind == OMPC_firstprivate ||
  8870. (!IsOpenMPCapturedDecl(D) &&
  8871. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  8872. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8873. if (!RefRes.isUsable())
  8874. continue;
  8875. ExprResult PostUpdateRes =
  8876. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  8877. RefRes.get());
  8878. if (!PostUpdateRes.isUsable())
  8879. continue;
  8880. ExprPostUpdates.push_back(
  8881. IgnoredValueConversions(PostUpdateRes.get()).get());
  8882. }
  8883. }
  8884. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  8885. Vars.push_back((VD || CurContext->isDependentContext())
  8886. ? RefExpr->IgnoreParens()
  8887. : Ref);
  8888. SrcExprs.push_back(PseudoSrcExpr);
  8889. DstExprs.push_back(PseudoDstExpr);
  8890. AssignmentOps.push_back(AssignmentOp.get());
  8891. }
  8892. if (Vars.empty())
  8893. return nullptr;
  8894. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8895. Vars, SrcExprs, DstExprs, AssignmentOps,
  8896. buildPreInits(Context, ExprCaptures),
  8897. buildPostUpdate(*this, ExprPostUpdates));
  8898. }
  8899. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  8900. SourceLocation StartLoc,
  8901. SourceLocation LParenLoc,
  8902. SourceLocation EndLoc) {
  8903. SmallVector<Expr *, 8> Vars;
  8904. for (auto &RefExpr : VarList) {
  8905. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8906. SourceLocation ELoc;
  8907. SourceRange ERange;
  8908. Expr *SimpleRefExpr = RefExpr;
  8909. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8910. if (Res.second) {
  8911. // It will be analyzed later.
  8912. Vars.push_back(RefExpr);
  8913. }
  8914. ValueDecl *D = Res.first;
  8915. if (!D)
  8916. continue;
  8917. auto *VD = dyn_cast<VarDecl>(D);
  8918. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8919. // in a Construct]
  8920. // Variables with the predetermined data-sharing attributes may not be
  8921. // listed in data-sharing attributes clauses, except for the cases
  8922. // listed below. For these exceptions only, listing a predetermined
  8923. // variable in a data-sharing attribute clause is allowed and overrides
  8924. // the variable's predetermined data-sharing attributes.
  8925. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8926. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  8927. DVar.RefExpr) {
  8928. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8929. << getOpenMPClauseName(OMPC_shared);
  8930. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8931. continue;
  8932. }
  8933. DeclRefExpr *Ref = nullptr;
  8934. if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  8935. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8936. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  8937. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  8938. ? RefExpr->IgnoreParens()
  8939. : Ref);
  8940. }
  8941. if (Vars.empty())
  8942. return nullptr;
  8943. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  8944. }
  8945. namespace {
  8946. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  8947. DSAStackTy *Stack;
  8948. public:
  8949. bool VisitDeclRefExpr(DeclRefExpr *E) {
  8950. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  8951. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  8952. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  8953. return false;
  8954. if (DVar.CKind != OMPC_unknown)
  8955. return true;
  8956. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  8957. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  8958. /*FromParent=*/true);
  8959. if (DVarPrivate.CKind != OMPC_unknown)
  8960. return true;
  8961. return false;
  8962. }
  8963. return false;
  8964. }
  8965. bool VisitStmt(Stmt *S) {
  8966. for (auto Child : S->children()) {
  8967. if (Child && Visit(Child))
  8968. return true;
  8969. }
  8970. return false;
  8971. }
  8972. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  8973. };
  8974. } // namespace
  8975. namespace {
  8976. // Transform MemberExpression for specified FieldDecl of current class to
  8977. // DeclRefExpr to specified OMPCapturedExprDecl.
  8978. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  8979. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  8980. ValueDecl *Field;
  8981. DeclRefExpr *CapturedExpr;
  8982. public:
  8983. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  8984. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  8985. ExprResult TransformMemberExpr(MemberExpr *E) {
  8986. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  8987. E->getMemberDecl() == Field) {
  8988. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  8989. return CapturedExpr;
  8990. }
  8991. return BaseTransform::TransformMemberExpr(E);
  8992. }
  8993. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  8994. };
  8995. } // namespace
  8996. template <typename T>
  8997. static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
  8998. const llvm::function_ref<T(ValueDecl *)> &Gen) {
  8999. for (auto &Set : Lookups) {
  9000. for (auto *D : Set) {
  9001. if (auto Res = Gen(cast<ValueDecl>(D)))
  9002. return Res;
  9003. }
  9004. }
  9005. return T();
  9006. }
  9007. static ExprResult
  9008. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  9009. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  9010. const DeclarationNameInfo &ReductionId, QualType Ty,
  9011. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  9012. if (ReductionIdScopeSpec.isInvalid())
  9013. return ExprError();
  9014. SmallVector<UnresolvedSet<8>, 4> Lookups;
  9015. if (S) {
  9016. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  9017. Lookup.suppressDiagnostics();
  9018. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  9019. auto *D = Lookup.getRepresentativeDecl();
  9020. do {
  9021. S = S->getParent();
  9022. } while (S && !S->isDeclScope(D));
  9023. if (S)
  9024. S = S->getParent();
  9025. Lookups.push_back(UnresolvedSet<8>());
  9026. Lookups.back().append(Lookup.begin(), Lookup.end());
  9027. Lookup.clear();
  9028. }
  9029. } else if (auto *ULE =
  9030. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  9031. Lookups.push_back(UnresolvedSet<8>());
  9032. Decl *PrevD = nullptr;
  9033. for (auto *D : ULE->decls()) {
  9034. if (D == PrevD)
  9035. Lookups.push_back(UnresolvedSet<8>());
  9036. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  9037. Lookups.back().addDecl(DRD);
  9038. PrevD = D;
  9039. }
  9040. }
  9041. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  9042. Ty->isInstantiationDependentType() ||
  9043. Ty->containsUnexpandedParameterPack() ||
  9044. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
  9045. return !D->isInvalidDecl() &&
  9046. (D->getType()->isDependentType() ||
  9047. D->getType()->isInstantiationDependentType() ||
  9048. D->getType()->containsUnexpandedParameterPack());
  9049. })) {
  9050. UnresolvedSet<8> ResSet;
  9051. for (auto &Set : Lookups) {
  9052. ResSet.append(Set.begin(), Set.end());
  9053. // The last item marks the end of all declarations at the specified scope.
  9054. ResSet.addDecl(Set[Set.size() - 1]);
  9055. }
  9056. return UnresolvedLookupExpr::Create(
  9057. SemaRef.Context, /*NamingClass=*/nullptr,
  9058. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  9059. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  9060. }
  9061. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9062. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  9063. if (!D->isInvalidDecl() &&
  9064. SemaRef.Context.hasSameType(D->getType(), Ty))
  9065. return D;
  9066. return nullptr;
  9067. }))
  9068. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9069. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  9070. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  9071. if (!D->isInvalidDecl() &&
  9072. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  9073. !Ty.isMoreQualifiedThan(D->getType()))
  9074. return D;
  9075. return nullptr;
  9076. })) {
  9077. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  9078. /*DetectVirtual=*/false);
  9079. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  9080. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  9081. VD->getType().getUnqualifiedType()))) {
  9082. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  9083. /*DiagID=*/0) !=
  9084. Sema::AR_inaccessible) {
  9085. SemaRef.BuildBasePathArray(Paths, BasePath);
  9086. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  9087. }
  9088. }
  9089. }
  9090. }
  9091. if (ReductionIdScopeSpec.isSet()) {
  9092. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  9093. return ExprError();
  9094. }
  9095. return ExprEmpty();
  9096. }
  9097. namespace {
  9098. /// Data for the reduction-based clauses.
  9099. struct ReductionData {
  9100. /// List of original reduction items.
  9101. SmallVector<Expr *, 8> Vars;
  9102. /// List of private copies of the reduction items.
  9103. SmallVector<Expr *, 8> Privates;
  9104. /// LHS expressions for the reduction_op expressions.
  9105. SmallVector<Expr *, 8> LHSs;
  9106. /// RHS expressions for the reduction_op expressions.
  9107. SmallVector<Expr *, 8> RHSs;
  9108. /// Reduction operation expression.
  9109. SmallVector<Expr *, 8> ReductionOps;
  9110. /// Taskgroup descriptors for the corresponding reduction items in
  9111. /// in_reduction clauses.
  9112. SmallVector<Expr *, 8> TaskgroupDescriptors;
  9113. /// List of captures for clause.
  9114. SmallVector<Decl *, 4> ExprCaptures;
  9115. /// List of postupdate expressions.
  9116. SmallVector<Expr *, 4> ExprPostUpdates;
  9117. ReductionData() = delete;
  9118. /// Reserves required memory for the reduction data.
  9119. ReductionData(unsigned Size) {
  9120. Vars.reserve(Size);
  9121. Privates.reserve(Size);
  9122. LHSs.reserve(Size);
  9123. RHSs.reserve(Size);
  9124. ReductionOps.reserve(Size);
  9125. TaskgroupDescriptors.reserve(Size);
  9126. ExprCaptures.reserve(Size);
  9127. ExprPostUpdates.reserve(Size);
  9128. }
  9129. /// Stores reduction item and reduction operation only (required for dependent
  9130. /// reduction item).
  9131. void push(Expr *Item, Expr *ReductionOp) {
  9132. Vars.emplace_back(Item);
  9133. Privates.emplace_back(nullptr);
  9134. LHSs.emplace_back(nullptr);
  9135. RHSs.emplace_back(nullptr);
  9136. ReductionOps.emplace_back(ReductionOp);
  9137. TaskgroupDescriptors.emplace_back(nullptr);
  9138. }
  9139. /// Stores reduction data.
  9140. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  9141. Expr *TaskgroupDescriptor) {
  9142. Vars.emplace_back(Item);
  9143. Privates.emplace_back(Private);
  9144. LHSs.emplace_back(LHS);
  9145. RHSs.emplace_back(RHS);
  9146. ReductionOps.emplace_back(ReductionOp);
  9147. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  9148. }
  9149. };
  9150. } // namespace
  9151. static bool CheckOMPArraySectionConstantForReduction(
  9152. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  9153. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  9154. const Expr *Length = OASE->getLength();
  9155. if (Length == nullptr) {
  9156. // For array sections of the form [1:] or [:], we would need to analyze
  9157. // the lower bound...
  9158. if (OASE->getColonLoc().isValid())
  9159. return false;
  9160. // This is an array subscript which has implicit length 1!
  9161. SingleElement = true;
  9162. ArraySizes.push_back(llvm::APSInt::get(1));
  9163. } else {
  9164. llvm::APSInt ConstantLengthValue;
  9165. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  9166. return false;
  9167. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  9168. ArraySizes.push_back(ConstantLengthValue);
  9169. }
  9170. // Get the base of this array section and walk up from there.
  9171. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9172. // We require length = 1 for all array sections except the right-most to
  9173. // guarantee that the memory region is contiguous and has no holes in it.
  9174. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  9175. Length = TempOASE->getLength();
  9176. if (Length == nullptr) {
  9177. // For array sections of the form [1:] or [:], we would need to analyze
  9178. // the lower bound...
  9179. if (OASE->getColonLoc().isValid())
  9180. return false;
  9181. // This is an array subscript which has implicit length 1!
  9182. ArraySizes.push_back(llvm::APSInt::get(1));
  9183. } else {
  9184. llvm::APSInt ConstantLengthValue;
  9185. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  9186. ConstantLengthValue.getSExtValue() != 1)
  9187. return false;
  9188. ArraySizes.push_back(ConstantLengthValue);
  9189. }
  9190. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9191. }
  9192. // If we have a single element, we don't need to add the implicit lengths.
  9193. if (!SingleElement) {
  9194. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  9195. // Has implicit length 1!
  9196. ArraySizes.push_back(llvm::APSInt::get(1));
  9197. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9198. }
  9199. }
  9200. // This array section can be privatized as a single value or as a constant
  9201. // sized array.
  9202. return true;
  9203. }
  9204. static bool ActOnOMPReductionKindClause(
  9205. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  9206. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9207. SourceLocation ColonLoc, SourceLocation EndLoc,
  9208. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9209. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  9210. auto DN = ReductionId.getName();
  9211. auto OOK = DN.getCXXOverloadedOperator();
  9212. BinaryOperatorKind BOK = BO_Comma;
  9213. ASTContext &Context = S.Context;
  9214. // OpenMP [2.14.3.6, reduction clause]
  9215. // C
  9216. // reduction-identifier is either an identifier or one of the following
  9217. // operators: +, -, *, &, |, ^, && and ||
  9218. // C++
  9219. // reduction-identifier is either an id-expression or one of the following
  9220. // operators: +, -, *, &, |, ^, && and ||
  9221. switch (OOK) {
  9222. case OO_Plus:
  9223. case OO_Minus:
  9224. BOK = BO_Add;
  9225. break;
  9226. case OO_Star:
  9227. BOK = BO_Mul;
  9228. break;
  9229. case OO_Amp:
  9230. BOK = BO_And;
  9231. break;
  9232. case OO_Pipe:
  9233. BOK = BO_Or;
  9234. break;
  9235. case OO_Caret:
  9236. BOK = BO_Xor;
  9237. break;
  9238. case OO_AmpAmp:
  9239. BOK = BO_LAnd;
  9240. break;
  9241. case OO_PipePipe:
  9242. BOK = BO_LOr;
  9243. break;
  9244. case OO_New:
  9245. case OO_Delete:
  9246. case OO_Array_New:
  9247. case OO_Array_Delete:
  9248. case OO_Slash:
  9249. case OO_Percent:
  9250. case OO_Tilde:
  9251. case OO_Exclaim:
  9252. case OO_Equal:
  9253. case OO_Less:
  9254. case OO_Greater:
  9255. case OO_LessEqual:
  9256. case OO_GreaterEqual:
  9257. case OO_PlusEqual:
  9258. case OO_MinusEqual:
  9259. case OO_StarEqual:
  9260. case OO_SlashEqual:
  9261. case OO_PercentEqual:
  9262. case OO_CaretEqual:
  9263. case OO_AmpEqual:
  9264. case OO_PipeEqual:
  9265. case OO_LessLess:
  9266. case OO_GreaterGreater:
  9267. case OO_LessLessEqual:
  9268. case OO_GreaterGreaterEqual:
  9269. case OO_EqualEqual:
  9270. case OO_ExclaimEqual:
  9271. case OO_Spaceship:
  9272. case OO_PlusPlus:
  9273. case OO_MinusMinus:
  9274. case OO_Comma:
  9275. case OO_ArrowStar:
  9276. case OO_Arrow:
  9277. case OO_Call:
  9278. case OO_Subscript:
  9279. case OO_Conditional:
  9280. case OO_Coawait:
  9281. case NUM_OVERLOADED_OPERATORS:
  9282. llvm_unreachable("Unexpected reduction identifier");
  9283. case OO_None:
  9284. if (auto *II = DN.getAsIdentifierInfo()) {
  9285. if (II->isStr("max"))
  9286. BOK = BO_GT;
  9287. else if (II->isStr("min"))
  9288. BOK = BO_LT;
  9289. }
  9290. break;
  9291. }
  9292. SourceRange ReductionIdRange;
  9293. if (ReductionIdScopeSpec.isValid())
  9294. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  9295. else
  9296. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  9297. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  9298. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  9299. bool FirstIter = true;
  9300. for (auto RefExpr : VarList) {
  9301. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  9302. // OpenMP [2.1, C/C++]
  9303. // A list item is a variable or array section, subject to the restrictions
  9304. // specified in Section 2.4 on page 42 and in each of the sections
  9305. // describing clauses and directives for which a list appears.
  9306. // OpenMP [2.14.3.3, Restrictions, p.1]
  9307. // A variable that is part of another variable (as an array or
  9308. // structure element) cannot appear in a private clause.
  9309. if (!FirstIter && IR != ER)
  9310. ++IR;
  9311. FirstIter = false;
  9312. SourceLocation ELoc;
  9313. SourceRange ERange;
  9314. Expr *SimpleRefExpr = RefExpr;
  9315. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  9316. /*AllowArraySection=*/true);
  9317. if (Res.second) {
  9318. // Try to find 'declare reduction' corresponding construct before using
  9319. // builtin/overloaded operators.
  9320. QualType Type = Context.DependentTy;
  9321. CXXCastPath BasePath;
  9322. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9323. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9324. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9325. Expr *ReductionOp = nullptr;
  9326. if (S.CurContext->isDependentContext() &&
  9327. (DeclareReductionRef.isUnset() ||
  9328. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  9329. ReductionOp = DeclareReductionRef.get();
  9330. // It will be analyzed later.
  9331. RD.push(RefExpr, ReductionOp);
  9332. }
  9333. ValueDecl *D = Res.first;
  9334. if (!D)
  9335. continue;
  9336. Expr *TaskgroupDescriptor = nullptr;
  9337. QualType Type;
  9338. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  9339. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  9340. if (ASE)
  9341. Type = ASE->getType().getNonReferenceType();
  9342. else if (OASE) {
  9343. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  9344. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  9345. Type = ATy->getElementType();
  9346. else
  9347. Type = BaseType->getPointeeType();
  9348. Type = Type.getNonReferenceType();
  9349. } else
  9350. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  9351. auto *VD = dyn_cast<VarDecl>(D);
  9352. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9353. // A variable that appears in a private clause must not have an incomplete
  9354. // type or a reference type.
  9355. if (S.RequireCompleteType(ELoc, Type,
  9356. diag::err_omp_reduction_incomplete_type))
  9357. continue;
  9358. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9359. // A list item that appears in a reduction clause must not be
  9360. // const-qualified.
  9361. if (Type.getNonReferenceType().isConstant(Context)) {
  9362. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  9363. if (!ASE && !OASE) {
  9364. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9365. VarDecl::DeclarationOnly;
  9366. S.Diag(D->getLocation(),
  9367. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9368. << D;
  9369. }
  9370. continue;
  9371. }
  9372. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  9373. // If a list-item is a reference type then it must bind to the same object
  9374. // for all threads of the team.
  9375. if (!ASE && !OASE && VD) {
  9376. VarDecl *VDDef = VD->getDefinition();
  9377. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  9378. DSARefChecker Check(Stack);
  9379. if (Check.Visit(VDDef->getInit())) {
  9380. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  9381. << getOpenMPClauseName(ClauseKind) << ERange;
  9382. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  9383. continue;
  9384. }
  9385. }
  9386. }
  9387. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9388. // in a Construct]
  9389. // Variables with the predetermined data-sharing attributes may not be
  9390. // listed in data-sharing attributes clauses, except for the cases
  9391. // listed below. For these exceptions only, listing a predetermined
  9392. // variable in a data-sharing attribute clause is allowed and overrides
  9393. // the variable's predetermined data-sharing attributes.
  9394. // OpenMP [2.14.3.6, Restrictions, p.3]
  9395. // Any number of reduction clauses can be specified on the directive,
  9396. // but a list item can appear only once in the reduction clauses for that
  9397. // directive.
  9398. DSAStackTy::DSAVarData DVar;
  9399. DVar = Stack->getTopDSA(D, false);
  9400. if (DVar.CKind == OMPC_reduction) {
  9401. S.Diag(ELoc, diag::err_omp_once_referenced)
  9402. << getOpenMPClauseName(ClauseKind);
  9403. if (DVar.RefExpr)
  9404. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  9405. continue;
  9406. } else if (DVar.CKind != OMPC_unknown) {
  9407. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  9408. << getOpenMPClauseName(DVar.CKind)
  9409. << getOpenMPClauseName(OMPC_reduction);
  9410. ReportOriginalDSA(S, Stack, D, DVar);
  9411. continue;
  9412. }
  9413. // OpenMP [2.14.3.6, Restrictions, p.1]
  9414. // A list item that appears in a reduction clause of a worksharing
  9415. // construct must be shared in the parallel regions to which any of the
  9416. // worksharing regions arising from the worksharing construct bind.
  9417. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  9418. if (isOpenMPWorksharingDirective(CurrDir) &&
  9419. !isOpenMPParallelDirective(CurrDir) &&
  9420. !isOpenMPTeamsDirective(CurrDir)) {
  9421. DVar = Stack->getImplicitDSA(D, true);
  9422. if (DVar.CKind != OMPC_shared) {
  9423. S.Diag(ELoc, diag::err_omp_required_access)
  9424. << getOpenMPClauseName(OMPC_reduction)
  9425. << getOpenMPClauseName(OMPC_shared);
  9426. ReportOriginalDSA(S, Stack, D, DVar);
  9427. continue;
  9428. }
  9429. }
  9430. // Try to find 'declare reduction' corresponding construct before using
  9431. // builtin/overloaded operators.
  9432. CXXCastPath BasePath;
  9433. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  9434. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  9435. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  9436. if (DeclareReductionRef.isInvalid())
  9437. continue;
  9438. if (S.CurContext->isDependentContext() &&
  9439. (DeclareReductionRef.isUnset() ||
  9440. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  9441. RD.push(RefExpr, DeclareReductionRef.get());
  9442. continue;
  9443. }
  9444. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  9445. // Not allowed reduction identifier is found.
  9446. S.Diag(ReductionId.getLocStart(),
  9447. diag::err_omp_unknown_reduction_identifier)
  9448. << Type << ReductionIdRange;
  9449. continue;
  9450. }
  9451. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9452. // The type of a list item that appears in a reduction clause must be valid
  9453. // for the reduction-identifier. For a max or min reduction in C, the type
  9454. // of the list item must be an allowed arithmetic data type: char, int,
  9455. // float, double, or _Bool, possibly modified with long, short, signed, or
  9456. // unsigned. For a max or min reduction in C++, the type of the list item
  9457. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  9458. // double, or bool, possibly modified with long, short, signed, or unsigned.
  9459. if (DeclareReductionRef.isUnset()) {
  9460. if ((BOK == BO_GT || BOK == BO_LT) &&
  9461. !(Type->isScalarType() ||
  9462. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  9463. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  9464. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  9465. if (!ASE && !OASE) {
  9466. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9467. VarDecl::DeclarationOnly;
  9468. S.Diag(D->getLocation(),
  9469. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9470. << D;
  9471. }
  9472. continue;
  9473. }
  9474. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  9475. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  9476. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  9477. << getOpenMPClauseName(ClauseKind);
  9478. if (!ASE && !OASE) {
  9479. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9480. VarDecl::DeclarationOnly;
  9481. S.Diag(D->getLocation(),
  9482. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9483. << D;
  9484. }
  9485. continue;
  9486. }
  9487. }
  9488. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  9489. auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  9490. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9491. auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  9492. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9493. auto PrivateTy = Type;
  9494. // Try if we can determine constant lengths for all array sections and avoid
  9495. // the VLA.
  9496. bool ConstantLengthOASE = false;
  9497. if (OASE) {
  9498. bool SingleElement;
  9499. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  9500. ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
  9501. Context, OASE, SingleElement, ArraySizes);
  9502. // If we don't have a single element, we must emit a constant array type.
  9503. if (ConstantLengthOASE && !SingleElement) {
  9504. for (auto &Size : ArraySizes) {
  9505. PrivateTy = Context.getConstantArrayType(
  9506. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  9507. }
  9508. }
  9509. }
  9510. if ((OASE && !ConstantLengthOASE) ||
  9511. (!OASE && !ASE &&
  9512. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  9513. if (!Context.getTargetInfo().isVLASupported() &&
  9514. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  9515. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  9516. S.Diag(ELoc, diag::note_vla_unsupported);
  9517. continue;
  9518. }
  9519. // For arrays/array sections only:
  9520. // Create pseudo array type for private copy. The size for this array will
  9521. // be generated during codegen.
  9522. // For array subscripts or single variables Private Ty is the same as Type
  9523. // (type of the variable or single array element).
  9524. PrivateTy = Context.getVariableArrayType(
  9525. Type,
  9526. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  9527. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  9528. } else if (!ASE && !OASE &&
  9529. Context.getAsArrayType(D->getType().getNonReferenceType()))
  9530. PrivateTy = D->getType().getNonReferenceType();
  9531. // Private copy.
  9532. auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  9533. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9534. // Add initializer for private variable.
  9535. Expr *Init = nullptr;
  9536. auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  9537. auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  9538. if (DeclareReductionRef.isUsable()) {
  9539. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  9540. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  9541. if (DRD->getInitializer()) {
  9542. Init = DRDRef;
  9543. RHSVD->setInit(DRDRef);
  9544. RHSVD->setInitStyle(VarDecl::CallInit);
  9545. }
  9546. } else {
  9547. switch (BOK) {
  9548. case BO_Add:
  9549. case BO_Xor:
  9550. case BO_Or:
  9551. case BO_LOr:
  9552. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  9553. if (Type->isScalarType() || Type->isAnyComplexType())
  9554. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  9555. break;
  9556. case BO_Mul:
  9557. case BO_LAnd:
  9558. if (Type->isScalarType() || Type->isAnyComplexType()) {
  9559. // '*' and '&&' reduction ops - initializer is '1'.
  9560. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  9561. }
  9562. break;
  9563. case BO_And: {
  9564. // '&' reduction op - initializer is '~0'.
  9565. QualType OrigType = Type;
  9566. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  9567. Type = ComplexTy->getElementType();
  9568. if (Type->isRealFloatingType()) {
  9569. llvm::APFloat InitValue =
  9570. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  9571. /*isIEEE=*/true);
  9572. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9573. Type, ELoc);
  9574. } else if (Type->isScalarType()) {
  9575. auto Size = Context.getTypeSize(Type);
  9576. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  9577. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  9578. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9579. }
  9580. if (Init && OrigType->isAnyComplexType()) {
  9581. // Init = 0xFFFF + 0xFFFFi;
  9582. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  9583. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  9584. }
  9585. Type = OrigType;
  9586. break;
  9587. }
  9588. case BO_LT:
  9589. case BO_GT: {
  9590. // 'min' reduction op - initializer is 'Largest representable number in
  9591. // the reduction list item type'.
  9592. // 'max' reduction op - initializer is 'Least representable number in
  9593. // the reduction list item type'.
  9594. if (Type->isIntegerType() || Type->isPointerType()) {
  9595. bool IsSigned = Type->hasSignedIntegerRepresentation();
  9596. auto Size = Context.getTypeSize(Type);
  9597. QualType IntTy =
  9598. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  9599. llvm::APInt InitValue =
  9600. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  9601. : llvm::APInt::getMinValue(Size)
  9602. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  9603. : llvm::APInt::getMaxValue(Size);
  9604. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9605. if (Type->isPointerType()) {
  9606. // Cast to pointer type.
  9607. auto CastExpr = S.BuildCStyleCastExpr(
  9608. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  9609. if (CastExpr.isInvalid())
  9610. continue;
  9611. Init = CastExpr.get();
  9612. }
  9613. } else if (Type->isRealFloatingType()) {
  9614. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  9615. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  9616. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9617. Type, ELoc);
  9618. }
  9619. break;
  9620. }
  9621. case BO_PtrMemD:
  9622. case BO_PtrMemI:
  9623. case BO_MulAssign:
  9624. case BO_Div:
  9625. case BO_Rem:
  9626. case BO_Sub:
  9627. case BO_Shl:
  9628. case BO_Shr:
  9629. case BO_LE:
  9630. case BO_GE:
  9631. case BO_EQ:
  9632. case BO_NE:
  9633. case BO_AndAssign:
  9634. case BO_XorAssign:
  9635. case BO_OrAssign:
  9636. case BO_Assign:
  9637. case BO_AddAssign:
  9638. case BO_SubAssign:
  9639. case BO_DivAssign:
  9640. case BO_RemAssign:
  9641. case BO_ShlAssign:
  9642. case BO_ShrAssign:
  9643. case BO_Comma:
  9644. llvm_unreachable("Unexpected reduction operation");
  9645. }
  9646. }
  9647. if (Init && DeclareReductionRef.isUnset())
  9648. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  9649. else if (!Init)
  9650. S.ActOnUninitializedDecl(RHSVD);
  9651. if (RHSVD->isInvalidDecl())
  9652. continue;
  9653. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  9654. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  9655. << Type << ReductionIdRange;
  9656. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9657. VarDecl::DeclarationOnly;
  9658. S.Diag(D->getLocation(),
  9659. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9660. << D;
  9661. continue;
  9662. }
  9663. // Store initializer for single element in private copy. Will be used during
  9664. // codegen.
  9665. PrivateVD->setInit(RHSVD->getInit());
  9666. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  9667. auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  9668. ExprResult ReductionOp;
  9669. if (DeclareReductionRef.isUsable()) {
  9670. QualType RedTy = DeclareReductionRef.get()->getType();
  9671. QualType PtrRedTy = Context.getPointerType(RedTy);
  9672. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  9673. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  9674. if (!BasePath.empty()) {
  9675. LHS = S.DefaultLvalueConversion(LHS.get());
  9676. RHS = S.DefaultLvalueConversion(RHS.get());
  9677. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9678. CK_UncheckedDerivedToBase, LHS.get(),
  9679. &BasePath, LHS.get()->getValueKind());
  9680. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9681. CK_UncheckedDerivedToBase, RHS.get(),
  9682. &BasePath, RHS.get()->getValueKind());
  9683. }
  9684. FunctionProtoType::ExtProtoInfo EPI;
  9685. QualType Params[] = {PtrRedTy, PtrRedTy};
  9686. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  9687. auto *OVE = new (Context) OpaqueValueExpr(
  9688. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  9689. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  9690. Expr *Args[] = {LHS.get(), RHS.get()};
  9691. ReductionOp = new (Context)
  9692. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  9693. } else {
  9694. ReductionOp = S.BuildBinOp(
  9695. Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  9696. if (ReductionOp.isUsable()) {
  9697. if (BOK != BO_LT && BOK != BO_GT) {
  9698. ReductionOp =
  9699. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9700. BO_Assign, LHSDRE, ReductionOp.get());
  9701. } else {
  9702. auto *ConditionalOp = new (Context)
  9703. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  9704. Type, VK_LValue, OK_Ordinary);
  9705. ReductionOp =
  9706. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9707. BO_Assign, LHSDRE, ConditionalOp);
  9708. }
  9709. if (ReductionOp.isUsable())
  9710. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  9711. }
  9712. if (!ReductionOp.isUsable())
  9713. continue;
  9714. }
  9715. // OpenMP [2.15.4.6, Restrictions, p.2]
  9716. // A list item that appears in an in_reduction clause of a task construct
  9717. // must appear in a task_reduction clause of a construct associated with a
  9718. // taskgroup region that includes the participating task in its taskgroup
  9719. // set. The construct associated with the innermost region that meets this
  9720. // condition must specify the same reduction-identifier as the in_reduction
  9721. // clause.
  9722. if (ClauseKind == OMPC_in_reduction) {
  9723. SourceRange ParentSR;
  9724. BinaryOperatorKind ParentBOK;
  9725. const Expr *ParentReductionOp;
  9726. Expr *ParentBOKTD, *ParentReductionOpTD;
  9727. DSAStackTy::DSAVarData ParentBOKDSA =
  9728. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  9729. ParentBOKTD);
  9730. DSAStackTy::DSAVarData ParentReductionOpDSA =
  9731. Stack->getTopMostTaskgroupReductionData(
  9732. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  9733. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  9734. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  9735. if (!IsParentBOK && !IsParentReductionOp) {
  9736. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  9737. continue;
  9738. }
  9739. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  9740. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  9741. IsParentReductionOp) {
  9742. bool EmitError = true;
  9743. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  9744. llvm::FoldingSetNodeID RedId, ParentRedId;
  9745. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  9746. DeclareReductionRef.get()->Profile(RedId, Context,
  9747. /*Canonical=*/true);
  9748. EmitError = RedId != ParentRedId;
  9749. }
  9750. if (EmitError) {
  9751. S.Diag(ReductionId.getLocStart(),
  9752. diag::err_omp_reduction_identifier_mismatch)
  9753. << ReductionIdRange << RefExpr->getSourceRange();
  9754. S.Diag(ParentSR.getBegin(),
  9755. diag::note_omp_previous_reduction_identifier)
  9756. << ParentSR
  9757. << (IsParentBOK ? ParentBOKDSA.RefExpr
  9758. : ParentReductionOpDSA.RefExpr)
  9759. ->getSourceRange();
  9760. continue;
  9761. }
  9762. }
  9763. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  9764. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  9765. }
  9766. DeclRefExpr *Ref = nullptr;
  9767. Expr *VarsExpr = RefExpr->IgnoreParens();
  9768. if (!VD && !S.CurContext->isDependentContext()) {
  9769. if (ASE || OASE) {
  9770. TransformExprToCaptures RebuildToCapture(S, D);
  9771. VarsExpr =
  9772. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  9773. Ref = RebuildToCapture.getCapturedExpr();
  9774. } else {
  9775. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  9776. }
  9777. if (!S.IsOpenMPCapturedDecl(D)) {
  9778. RD.ExprCaptures.emplace_back(Ref->getDecl());
  9779. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9780. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  9781. if (!RefRes.isUsable())
  9782. continue;
  9783. ExprResult PostUpdateRes =
  9784. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9785. RefRes.get());
  9786. if (!PostUpdateRes.isUsable())
  9787. continue;
  9788. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  9789. Stack->getCurrentDirective() == OMPD_taskgroup) {
  9790. S.Diag(RefExpr->getExprLoc(),
  9791. diag::err_omp_reduction_non_addressable_expression)
  9792. << RefExpr->getSourceRange();
  9793. continue;
  9794. }
  9795. RD.ExprPostUpdates.emplace_back(
  9796. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  9797. }
  9798. }
  9799. }
  9800. // All reduction items are still marked as reduction (to do not increase
  9801. // code base size).
  9802. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  9803. if (CurrDir == OMPD_taskgroup) {
  9804. if (DeclareReductionRef.isUsable())
  9805. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  9806. DeclareReductionRef.get());
  9807. else
  9808. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  9809. }
  9810. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  9811. TaskgroupDescriptor);
  9812. }
  9813. return RD.Vars.empty();
  9814. }
  9815. OMPClause *Sema::ActOnOpenMPReductionClause(
  9816. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9817. SourceLocation ColonLoc, SourceLocation EndLoc,
  9818. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9819. ArrayRef<Expr *> UnresolvedReductions) {
  9820. ReductionData RD(VarList.size());
  9821. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  9822. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9823. ReductionIdScopeSpec, ReductionId,
  9824. UnresolvedReductions, RD))
  9825. return nullptr;
  9826. return OMPReductionClause::Create(
  9827. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9828. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9829. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9830. buildPreInits(Context, RD.ExprCaptures),
  9831. buildPostUpdate(*this, RD.ExprPostUpdates));
  9832. }
  9833. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  9834. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9835. SourceLocation ColonLoc, SourceLocation EndLoc,
  9836. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9837. ArrayRef<Expr *> UnresolvedReductions) {
  9838. ReductionData RD(VarList.size());
  9839. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
  9840. VarList, StartLoc, LParenLoc, ColonLoc,
  9841. EndLoc, ReductionIdScopeSpec, ReductionId,
  9842. UnresolvedReductions, RD))
  9843. return nullptr;
  9844. return OMPTaskReductionClause::Create(
  9845. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9846. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9847. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9848. buildPreInits(Context, RD.ExprCaptures),
  9849. buildPostUpdate(*this, RD.ExprPostUpdates));
  9850. }
  9851. OMPClause *Sema::ActOnOpenMPInReductionClause(
  9852. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9853. SourceLocation ColonLoc, SourceLocation EndLoc,
  9854. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9855. ArrayRef<Expr *> UnresolvedReductions) {
  9856. ReductionData RD(VarList.size());
  9857. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  9858. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9859. ReductionIdScopeSpec, ReductionId,
  9860. UnresolvedReductions, RD))
  9861. return nullptr;
  9862. return OMPInReductionClause::Create(
  9863. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9864. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9865. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  9866. buildPreInits(Context, RD.ExprCaptures),
  9867. buildPostUpdate(*this, RD.ExprPostUpdates));
  9868. }
  9869. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  9870. SourceLocation LinLoc) {
  9871. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  9872. LinKind == OMPC_LINEAR_unknown) {
  9873. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  9874. return true;
  9875. }
  9876. return false;
  9877. }
  9878. bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
  9879. OpenMPLinearClauseKind LinKind,
  9880. QualType Type) {
  9881. auto *VD = dyn_cast_or_null<VarDecl>(D);
  9882. // A variable must not have an incomplete type or a reference type.
  9883. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  9884. return true;
  9885. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  9886. !Type->isReferenceType()) {
  9887. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  9888. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  9889. return true;
  9890. }
  9891. Type = Type.getNonReferenceType();
  9892. // A list item must not be const-qualified.
  9893. if (Type.isConstant(Context)) {
  9894. Diag(ELoc, diag::err_omp_const_variable)
  9895. << getOpenMPClauseName(OMPC_linear);
  9896. if (D) {
  9897. bool IsDecl =
  9898. !VD ||
  9899. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9900. Diag(D->getLocation(),
  9901. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9902. << D;
  9903. }
  9904. return true;
  9905. }
  9906. // A list item must be of integral or pointer type.
  9907. Type = Type.getUnqualifiedType().getCanonicalType();
  9908. const auto *Ty = Type.getTypePtrOrNull();
  9909. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  9910. !Ty->isPointerType())) {
  9911. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  9912. if (D) {
  9913. bool IsDecl =
  9914. !VD ||
  9915. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9916. Diag(D->getLocation(),
  9917. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9918. << D;
  9919. }
  9920. return true;
  9921. }
  9922. return false;
  9923. }
  9924. OMPClause *Sema::ActOnOpenMPLinearClause(
  9925. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  9926. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  9927. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  9928. SmallVector<Expr *, 8> Vars;
  9929. SmallVector<Expr *, 8> Privates;
  9930. SmallVector<Expr *, 8> Inits;
  9931. SmallVector<Decl *, 4> ExprCaptures;
  9932. SmallVector<Expr *, 4> ExprPostUpdates;
  9933. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  9934. LinKind = OMPC_LINEAR_val;
  9935. for (auto &RefExpr : VarList) {
  9936. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9937. SourceLocation ELoc;
  9938. SourceRange ERange;
  9939. Expr *SimpleRefExpr = RefExpr;
  9940. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9941. /*AllowArraySection=*/false);
  9942. if (Res.second) {
  9943. // It will be analyzed later.
  9944. Vars.push_back(RefExpr);
  9945. Privates.push_back(nullptr);
  9946. Inits.push_back(nullptr);
  9947. }
  9948. ValueDecl *D = Res.first;
  9949. if (!D)
  9950. continue;
  9951. QualType Type = D->getType();
  9952. auto *VD = dyn_cast<VarDecl>(D);
  9953. // OpenMP [2.14.3.7, linear clause]
  9954. // A list-item cannot appear in more than one linear clause.
  9955. // A list-item that appears in a linear clause cannot appear in any
  9956. // other data-sharing attribute clause.
  9957. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  9958. if (DVar.RefExpr) {
  9959. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9960. << getOpenMPClauseName(OMPC_linear);
  9961. ReportOriginalDSA(*this, DSAStack, D, DVar);
  9962. continue;
  9963. }
  9964. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  9965. continue;
  9966. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  9967. // Build private copy of original var.
  9968. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
  9969. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9970. auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  9971. // Build var to save initial value.
  9972. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  9973. Expr *InitExpr;
  9974. DeclRefExpr *Ref = nullptr;
  9975. if (!VD && !CurContext->isDependentContext()) {
  9976. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9977. if (!IsOpenMPCapturedDecl(D)) {
  9978. ExprCaptures.push_back(Ref->getDecl());
  9979. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9980. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9981. if (!RefRes.isUsable())
  9982. continue;
  9983. ExprResult PostUpdateRes =
  9984. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  9985. SimpleRefExpr, RefRes.get());
  9986. if (!PostUpdateRes.isUsable())
  9987. continue;
  9988. ExprPostUpdates.push_back(
  9989. IgnoredValueConversions(PostUpdateRes.get()).get());
  9990. }
  9991. }
  9992. }
  9993. if (LinKind == OMPC_LINEAR_uval)
  9994. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  9995. else
  9996. InitExpr = VD ? SimpleRefExpr : Ref;
  9997. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  9998. /*DirectInit=*/false);
  9999. auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  10000. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  10001. Vars.push_back((VD || CurContext->isDependentContext())
  10002. ? RefExpr->IgnoreParens()
  10003. : Ref);
  10004. Privates.push_back(PrivateRef);
  10005. Inits.push_back(InitRef);
  10006. }
  10007. if (Vars.empty())
  10008. return nullptr;
  10009. Expr *StepExpr = Step;
  10010. Expr *CalcStepExpr = nullptr;
  10011. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  10012. !Step->isInstantiationDependent() &&
  10013. !Step->containsUnexpandedParameterPack()) {
  10014. SourceLocation StepLoc = Step->getLocStart();
  10015. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  10016. if (Val.isInvalid())
  10017. return nullptr;
  10018. StepExpr = Val.get();
  10019. // Build var to save the step value.
  10020. VarDecl *SaveVar =
  10021. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  10022. ExprResult SaveRef =
  10023. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  10024. ExprResult CalcStep =
  10025. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  10026. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  10027. // Warn about zero linear step (it would be probably better specified as
  10028. // making corresponding variables 'const').
  10029. llvm::APSInt Result;
  10030. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  10031. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  10032. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  10033. << (Vars.size() > 1);
  10034. if (!IsConstant && CalcStep.isUsable()) {
  10035. // Calculate the step beforehand instead of doing this on each iteration.
  10036. // (This is not used if the number of iterations may be kfold-ed).
  10037. CalcStepExpr = CalcStep.get();
  10038. }
  10039. }
  10040. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  10041. ColonLoc, EndLoc, Vars, Privates, Inits,
  10042. StepExpr, CalcStepExpr,
  10043. buildPreInits(Context, ExprCaptures),
  10044. buildPostUpdate(*this, ExprPostUpdates));
  10045. }
  10046. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  10047. Expr *NumIterations, Sema &SemaRef,
  10048. Scope *S, DSAStackTy *Stack) {
  10049. // Walk the vars and build update/final expressions for the CodeGen.
  10050. SmallVector<Expr *, 8> Updates;
  10051. SmallVector<Expr *, 8> Finals;
  10052. Expr *Step = Clause.getStep();
  10053. Expr *CalcStep = Clause.getCalcStep();
  10054. // OpenMP [2.14.3.7, linear clause]
  10055. // If linear-step is not specified it is assumed to be 1.
  10056. if (Step == nullptr)
  10057. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  10058. else if (CalcStep) {
  10059. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  10060. }
  10061. bool HasErrors = false;
  10062. auto CurInit = Clause.inits().begin();
  10063. auto CurPrivate = Clause.privates().begin();
  10064. auto LinKind = Clause.getModifier();
  10065. for (auto &RefExpr : Clause.varlists()) {
  10066. SourceLocation ELoc;
  10067. SourceRange ERange;
  10068. Expr *SimpleRefExpr = RefExpr;
  10069. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  10070. /*AllowArraySection=*/false);
  10071. ValueDecl *D = Res.first;
  10072. if (Res.second || !D) {
  10073. Updates.push_back(nullptr);
  10074. Finals.push_back(nullptr);
  10075. HasErrors = true;
  10076. continue;
  10077. }
  10078. auto &&Info = Stack->isLoopControlVariable(D);
  10079. // OpenMP [2.15.11, distribute simd Construct]
  10080. // A list item may not appear in a linear clause, unless it is the loop
  10081. // iteration variable.
  10082. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  10083. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  10084. SemaRef.Diag(ELoc,
  10085. diag::err_omp_linear_distribute_var_non_loop_iteration);
  10086. Updates.push_back(nullptr);
  10087. Finals.push_back(nullptr);
  10088. HasErrors = true;
  10089. continue;
  10090. }
  10091. Expr *InitExpr = *CurInit;
  10092. // Build privatized reference to the current linear var.
  10093. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  10094. Expr *CapturedRef;
  10095. if (LinKind == OMPC_LINEAR_uval)
  10096. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  10097. else
  10098. CapturedRef =
  10099. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  10100. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  10101. /*RefersToCapture=*/true);
  10102. // Build update: Var = InitExpr + IV * Step
  10103. ExprResult Update;
  10104. if (!Info.first) {
  10105. Update =
  10106. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  10107. InitExpr, IV, Step, /* Subtract */ false);
  10108. } else
  10109. Update = *CurPrivate;
  10110. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  10111. /*DiscardedValue=*/true);
  10112. // Build final: Var = InitExpr + NumIterations * Step
  10113. ExprResult Final;
  10114. if (!Info.first) {
  10115. Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  10116. InitExpr, NumIterations, Step,
  10117. /* Subtract */ false);
  10118. } else
  10119. Final = *CurPrivate;
  10120. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  10121. /*DiscardedValue=*/true);
  10122. if (!Update.isUsable() || !Final.isUsable()) {
  10123. Updates.push_back(nullptr);
  10124. Finals.push_back(nullptr);
  10125. HasErrors = true;
  10126. } else {
  10127. Updates.push_back(Update.get());
  10128. Finals.push_back(Final.get());
  10129. }
  10130. ++CurInit;
  10131. ++CurPrivate;
  10132. }
  10133. Clause.setUpdates(Updates);
  10134. Clause.setFinals(Finals);
  10135. return HasErrors;
  10136. }
  10137. OMPClause *Sema::ActOnOpenMPAlignedClause(
  10138. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  10139. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10140. SmallVector<Expr *, 8> Vars;
  10141. for (auto &RefExpr : VarList) {
  10142. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10143. SourceLocation ELoc;
  10144. SourceRange ERange;
  10145. Expr *SimpleRefExpr = RefExpr;
  10146. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10147. /*AllowArraySection=*/false);
  10148. if (Res.second) {
  10149. // It will be analyzed later.
  10150. Vars.push_back(RefExpr);
  10151. }
  10152. ValueDecl *D = Res.first;
  10153. if (!D)
  10154. continue;
  10155. QualType QType = D->getType();
  10156. auto *VD = dyn_cast<VarDecl>(D);
  10157. // OpenMP [2.8.1, simd construct, Restrictions]
  10158. // The type of list items appearing in the aligned clause must be
  10159. // array, pointer, reference to array, or reference to pointer.
  10160. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  10161. const Type *Ty = QType.getTypePtrOrNull();
  10162. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  10163. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  10164. << QType << getLangOpts().CPlusPlus << ERange;
  10165. bool IsDecl =
  10166. !VD ||
  10167. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10168. Diag(D->getLocation(),
  10169. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10170. << D;
  10171. continue;
  10172. }
  10173. // OpenMP [2.8.1, simd construct, Restrictions]
  10174. // A list-item cannot appear in more than one aligned clause.
  10175. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  10176. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  10177. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  10178. << getOpenMPClauseName(OMPC_aligned);
  10179. continue;
  10180. }
  10181. DeclRefExpr *Ref = nullptr;
  10182. if (!VD && IsOpenMPCapturedDecl(D))
  10183. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10184. Vars.push_back(DefaultFunctionArrayConversion(
  10185. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  10186. .get());
  10187. }
  10188. // OpenMP [2.8.1, simd construct, Description]
  10189. // The parameter of the aligned clause, alignment, must be a constant
  10190. // positive integer expression.
  10191. // If no optional parameter is specified, implementation-defined default
  10192. // alignments for SIMD instructions on the target platforms are assumed.
  10193. if (Alignment != nullptr) {
  10194. ExprResult AlignResult =
  10195. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  10196. if (AlignResult.isInvalid())
  10197. return nullptr;
  10198. Alignment = AlignResult.get();
  10199. }
  10200. if (Vars.empty())
  10201. return nullptr;
  10202. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  10203. EndLoc, Vars, Alignment);
  10204. }
  10205. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  10206. SourceLocation StartLoc,
  10207. SourceLocation LParenLoc,
  10208. SourceLocation EndLoc) {
  10209. SmallVector<Expr *, 8> Vars;
  10210. SmallVector<Expr *, 8> SrcExprs;
  10211. SmallVector<Expr *, 8> DstExprs;
  10212. SmallVector<Expr *, 8> AssignmentOps;
  10213. for (auto &RefExpr : VarList) {
  10214. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  10215. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10216. // It will be analyzed later.
  10217. Vars.push_back(RefExpr);
  10218. SrcExprs.push_back(nullptr);
  10219. DstExprs.push_back(nullptr);
  10220. AssignmentOps.push_back(nullptr);
  10221. continue;
  10222. }
  10223. SourceLocation ELoc = RefExpr->getExprLoc();
  10224. // OpenMP [2.1, C/C++]
  10225. // A list item is a variable name.
  10226. // OpenMP [2.14.4.1, Restrictions, p.1]
  10227. // A list item that appears in a copyin clause must be threadprivate.
  10228. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  10229. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  10230. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  10231. << 0 << RefExpr->getSourceRange();
  10232. continue;
  10233. }
  10234. Decl *D = DE->getDecl();
  10235. VarDecl *VD = cast<VarDecl>(D);
  10236. QualType Type = VD->getType();
  10237. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  10238. // It will be analyzed later.
  10239. Vars.push_back(DE);
  10240. SrcExprs.push_back(nullptr);
  10241. DstExprs.push_back(nullptr);
  10242. AssignmentOps.push_back(nullptr);
  10243. continue;
  10244. }
  10245. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  10246. // A list item that appears in a copyin clause must be threadprivate.
  10247. if (!DSAStack->isThreadPrivate(VD)) {
  10248. Diag(ELoc, diag::err_omp_required_access)
  10249. << getOpenMPClauseName(OMPC_copyin)
  10250. << getOpenMPDirectiveName(OMPD_threadprivate);
  10251. continue;
  10252. }
  10253. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10254. // A variable of class type (or array thereof) that appears in a
  10255. // copyin clause requires an accessible, unambiguous copy assignment
  10256. // operator for the class type.
  10257. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  10258. auto *SrcVD =
  10259. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  10260. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10261. auto *PseudoSrcExpr = buildDeclRefExpr(
  10262. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  10263. auto *DstVD =
  10264. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  10265. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  10266. auto *PseudoDstExpr =
  10267. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  10268. // For arrays generate assignment operation for single element and replace
  10269. // it by the original array element in CodeGen.
  10270. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  10271. PseudoDstExpr, PseudoSrcExpr);
  10272. if (AssignmentOp.isInvalid())
  10273. continue;
  10274. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  10275. /*DiscardedValue=*/true);
  10276. if (AssignmentOp.isInvalid())
  10277. continue;
  10278. DSAStack->addDSA(VD, DE, OMPC_copyin);
  10279. Vars.push_back(DE);
  10280. SrcExprs.push_back(PseudoSrcExpr);
  10281. DstExprs.push_back(PseudoDstExpr);
  10282. AssignmentOps.push_back(AssignmentOp.get());
  10283. }
  10284. if (Vars.empty())
  10285. return nullptr;
  10286. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  10287. SrcExprs, DstExprs, AssignmentOps);
  10288. }
  10289. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  10290. SourceLocation StartLoc,
  10291. SourceLocation LParenLoc,
  10292. SourceLocation EndLoc) {
  10293. SmallVector<Expr *, 8> Vars;
  10294. SmallVector<Expr *, 8> SrcExprs;
  10295. SmallVector<Expr *, 8> DstExprs;
  10296. SmallVector<Expr *, 8> AssignmentOps;
  10297. for (auto &RefExpr : VarList) {
  10298. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10299. SourceLocation ELoc;
  10300. SourceRange ERange;
  10301. Expr *SimpleRefExpr = RefExpr;
  10302. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  10303. /*AllowArraySection=*/false);
  10304. if (Res.second) {
  10305. // It will be analyzed later.
  10306. Vars.push_back(RefExpr);
  10307. SrcExprs.push_back(nullptr);
  10308. DstExprs.push_back(nullptr);
  10309. AssignmentOps.push_back(nullptr);
  10310. }
  10311. ValueDecl *D = Res.first;
  10312. if (!D)
  10313. continue;
  10314. QualType Type = D->getType();
  10315. auto *VD = dyn_cast<VarDecl>(D);
  10316. // OpenMP [2.14.4.2, Restrictions, p.2]
  10317. // A list item that appears in a copyprivate clause may not appear in a
  10318. // private or firstprivate clause on the single construct.
  10319. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  10320. auto DVar = DSAStack->getTopDSA(D, false);
  10321. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  10322. DVar.RefExpr) {
  10323. Diag(ELoc, diag::err_omp_wrong_dsa)
  10324. << getOpenMPClauseName(DVar.CKind)
  10325. << getOpenMPClauseName(OMPC_copyprivate);
  10326. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10327. continue;
  10328. }
  10329. // OpenMP [2.11.4.2, Restrictions, p.1]
  10330. // All list items that appear in a copyprivate clause must be either
  10331. // threadprivate or private in the enclosing context.
  10332. if (DVar.CKind == OMPC_unknown) {
  10333. DVar = DSAStack->getImplicitDSA(D, false);
  10334. if (DVar.CKind == OMPC_shared) {
  10335. Diag(ELoc, diag::err_omp_required_access)
  10336. << getOpenMPClauseName(OMPC_copyprivate)
  10337. << "threadprivate or private in the enclosing context";
  10338. ReportOriginalDSA(*this, DSAStack, D, DVar);
  10339. continue;
  10340. }
  10341. }
  10342. }
  10343. // Variably modified types are not supported.
  10344. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  10345. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10346. << getOpenMPClauseName(OMPC_copyprivate) << Type
  10347. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10348. bool IsDecl =
  10349. !VD ||
  10350. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10351. Diag(D->getLocation(),
  10352. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10353. << D;
  10354. continue;
  10355. }
  10356. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  10357. // A variable of class type (or array thereof) that appears in a
  10358. // copyin clause requires an accessible, unambiguous copy assignment
  10359. // operator for the class type.
  10360. Type = Context.getBaseElementType(Type.getNonReferenceType())
  10361. .getUnqualifiedType();
  10362. auto *SrcVD =
  10363. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  10364. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10365. auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  10366. auto *DstVD =
  10367. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  10368. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10369. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10370. auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  10371. PseudoDstExpr, PseudoSrcExpr);
  10372. if (AssignmentOp.isInvalid())
  10373. continue;
  10374. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  10375. /*DiscardedValue=*/true);
  10376. if (AssignmentOp.isInvalid())
  10377. continue;
  10378. // No need to mark vars as copyprivate, they are already threadprivate or
  10379. // implicitly private.
  10380. assert(VD || IsOpenMPCapturedDecl(D));
  10381. Vars.push_back(
  10382. VD ? RefExpr->IgnoreParens()
  10383. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  10384. SrcExprs.push_back(PseudoSrcExpr);
  10385. DstExprs.push_back(PseudoDstExpr);
  10386. AssignmentOps.push_back(AssignmentOp.get());
  10387. }
  10388. if (Vars.empty())
  10389. return nullptr;
  10390. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10391. Vars, SrcExprs, DstExprs, AssignmentOps);
  10392. }
  10393. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  10394. SourceLocation StartLoc,
  10395. SourceLocation LParenLoc,
  10396. SourceLocation EndLoc) {
  10397. if (VarList.empty())
  10398. return nullptr;
  10399. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  10400. }
  10401. OMPClause *
  10402. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  10403. SourceLocation DepLoc, SourceLocation ColonLoc,
  10404. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  10405. SourceLocation LParenLoc, SourceLocation EndLoc) {
  10406. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  10407. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  10408. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10409. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  10410. return nullptr;
  10411. }
  10412. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  10413. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  10414. DepKind == OMPC_DEPEND_sink)) {
  10415. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  10416. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  10417. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  10418. /*Last=*/OMPC_DEPEND_unknown, Except)
  10419. << getOpenMPClauseName(OMPC_depend);
  10420. return nullptr;
  10421. }
  10422. SmallVector<Expr *, 8> Vars;
  10423. DSAStackTy::OperatorOffsetTy OpsOffs;
  10424. llvm::APSInt DepCounter(/*BitWidth=*/32);
  10425. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  10426. if (DepKind == OMPC_DEPEND_sink) {
  10427. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  10428. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  10429. TotalDepCount.setIsUnsigned(/*Val=*/true);
  10430. }
  10431. }
  10432. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  10433. DSAStack->getParentOrderedRegionParam()) {
  10434. for (auto &RefExpr : VarList) {
  10435. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  10436. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  10437. // It will be analyzed later.
  10438. Vars.push_back(RefExpr);
  10439. continue;
  10440. }
  10441. SourceLocation ELoc = RefExpr->getExprLoc();
  10442. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  10443. if (DepKind == OMPC_DEPEND_sink) {
  10444. if (DepCounter >= TotalDepCount) {
  10445. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  10446. continue;
  10447. }
  10448. ++DepCounter;
  10449. // OpenMP [2.13.9, Summary]
  10450. // depend(dependence-type : vec), where dependence-type is:
  10451. // 'sink' and where vec is the iteration vector, which has the form:
  10452. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  10453. // where n is the value specified by the ordered clause in the loop
  10454. // directive, xi denotes the loop iteration variable of the i-th nested
  10455. // loop associated with the loop directive, and di is a constant
  10456. // non-negative integer.
  10457. if (CurContext->isDependentContext()) {
  10458. // It will be analyzed later.
  10459. Vars.push_back(RefExpr);
  10460. continue;
  10461. }
  10462. SimpleExpr = SimpleExpr->IgnoreImplicit();
  10463. OverloadedOperatorKind OOK = OO_None;
  10464. SourceLocation OOLoc;
  10465. Expr *LHS = SimpleExpr;
  10466. Expr *RHS = nullptr;
  10467. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  10468. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  10469. OOLoc = BO->getOperatorLoc();
  10470. LHS = BO->getLHS()->IgnoreParenImpCasts();
  10471. RHS = BO->getRHS()->IgnoreParenImpCasts();
  10472. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  10473. OOK = OCE->getOperator();
  10474. OOLoc = OCE->getOperatorLoc();
  10475. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10476. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  10477. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  10478. OOK = MCE->getMethodDecl()
  10479. ->getNameInfo()
  10480. .getName()
  10481. .getCXXOverloadedOperator();
  10482. OOLoc = MCE->getCallee()->getExprLoc();
  10483. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  10484. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10485. }
  10486. SourceLocation ELoc;
  10487. SourceRange ERange;
  10488. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  10489. /*AllowArraySection=*/false);
  10490. if (Res.second) {
  10491. // It will be analyzed later.
  10492. Vars.push_back(RefExpr);
  10493. }
  10494. ValueDecl *D = Res.first;
  10495. if (!D)
  10496. continue;
  10497. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  10498. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  10499. continue;
  10500. }
  10501. if (RHS) {
  10502. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  10503. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  10504. if (RHSRes.isInvalid())
  10505. continue;
  10506. }
  10507. if (!CurContext->isDependentContext() &&
  10508. DSAStack->getParentOrderedRegionParam() &&
  10509. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  10510. ValueDecl* VD = DSAStack->getParentLoopControlVariable(
  10511. DepCounter.getZExtValue());
  10512. if (VD) {
  10513. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10514. << 1 << VD;
  10515. } else {
  10516. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  10517. }
  10518. continue;
  10519. }
  10520. OpsOffs.push_back({RHS, OOK});
  10521. } else {
  10522. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  10523. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  10524. (ASE &&
  10525. !ASE->getBase()
  10526. ->getType()
  10527. .getNonReferenceType()
  10528. ->isPointerType() &&
  10529. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  10530. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10531. << RefExpr->getSourceRange();
  10532. continue;
  10533. }
  10534. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  10535. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  10536. ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  10537. RefExpr->IgnoreParenImpCasts());
  10538. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  10539. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  10540. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10541. << RefExpr->getSourceRange();
  10542. continue;
  10543. }
  10544. }
  10545. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  10546. }
  10547. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  10548. TotalDepCount > VarList.size() &&
  10549. DSAStack->getParentOrderedRegionParam() &&
  10550. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  10551. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
  10552. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  10553. }
  10554. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  10555. Vars.empty())
  10556. return nullptr;
  10557. }
  10558. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10559. DepKind, DepLoc, ColonLoc, Vars);
  10560. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
  10561. DSAStack->addDoacrossDependClause(C, OpsOffs);
  10562. return C;
  10563. }
  10564. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  10565. SourceLocation LParenLoc,
  10566. SourceLocation EndLoc) {
  10567. Expr *ValExpr = Device;
  10568. Stmt *HelperValStmt = nullptr;
  10569. // OpenMP [2.9.1, Restrictions]
  10570. // The device expression must evaluate to a non-negative integer value.
  10571. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  10572. /*StrictlyPositive=*/false))
  10573. return nullptr;
  10574. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10575. OpenMPDirectiveKind CaptureRegion =
  10576. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  10577. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  10578. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  10579. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10580. HelperValStmt = buildPreInits(Context, Captures);
  10581. }
  10582. return new (Context)
  10583. OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
  10584. }
  10585. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  10586. DSAStackTy *Stack, QualType QTy) {
  10587. NamedDecl *ND;
  10588. if (QTy->isIncompleteType(&ND)) {
  10589. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  10590. return false;
  10591. }
  10592. return true;
  10593. }
  10594. /// \brief Return true if it can be proven that the provided array expression
  10595. /// (array section or array subscript) does NOT specify the whole size of the
  10596. /// array whose base type is \a BaseQTy.
  10597. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  10598. const Expr *E,
  10599. QualType BaseQTy) {
  10600. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10601. // If this is an array subscript, it refers to the whole size if the size of
  10602. // the dimension is constant and equals 1. Also, an array section assumes the
  10603. // format of an array subscript if no colon is used.
  10604. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  10605. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10606. return ATy->getSize().getSExtValue() != 1;
  10607. // Size can't be evaluated statically.
  10608. return false;
  10609. }
  10610. assert(OASE && "Expecting array section if not an array subscript.");
  10611. auto *LowerBound = OASE->getLowerBound();
  10612. auto *Length = OASE->getLength();
  10613. // If there is a lower bound that does not evaluates to zero, we are not
  10614. // covering the whole dimension.
  10615. if (LowerBound) {
  10616. llvm::APSInt ConstLowerBound;
  10617. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  10618. return false; // Can't get the integer value as a constant.
  10619. if (ConstLowerBound.getSExtValue())
  10620. return true;
  10621. }
  10622. // If we don't have a length we covering the whole dimension.
  10623. if (!Length)
  10624. return false;
  10625. // If the base is a pointer, we don't have a way to get the size of the
  10626. // pointee.
  10627. if (BaseQTy->isPointerType())
  10628. return false;
  10629. // We can only check if the length is the same as the size of the dimension
  10630. // if we have a constant array.
  10631. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  10632. if (!CATy)
  10633. return false;
  10634. llvm::APSInt ConstLength;
  10635. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10636. return false; // Can't get the integer value as a constant.
  10637. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  10638. }
  10639. // Return true if it can be proven that the provided array expression (array
  10640. // section or array subscript) does NOT specify a single element of the array
  10641. // whose base type is \a BaseQTy.
  10642. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  10643. const Expr *E,
  10644. QualType BaseQTy) {
  10645. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10646. // An array subscript always refer to a single element. Also, an array section
  10647. // assumes the format of an array subscript if no colon is used.
  10648. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  10649. return false;
  10650. assert(OASE && "Expecting array section if not an array subscript.");
  10651. auto *Length = OASE->getLength();
  10652. // If we don't have a length we have to check if the array has unitary size
  10653. // for this dimension. Also, we should always expect a length if the base type
  10654. // is pointer.
  10655. if (!Length) {
  10656. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10657. return ATy->getSize().getSExtValue() != 1;
  10658. // We cannot assume anything.
  10659. return false;
  10660. }
  10661. // Check if the length evaluates to 1.
  10662. llvm::APSInt ConstLength;
  10663. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10664. return false; // Can't get the integer value as a constant.
  10665. return ConstLength.getSExtValue() != 1;
  10666. }
  10667. // Return the expression of the base of the mappable expression or null if it
  10668. // cannot be determined and do all the necessary checks to see if the expression
  10669. // is valid as a standalone mappable expression. In the process, record all the
  10670. // components of the expression.
  10671. static Expr *CheckMapClauseExpressionBase(
  10672. Sema &SemaRef, Expr *E,
  10673. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  10674. OpenMPClauseKind CKind) {
  10675. SourceLocation ELoc = E->getExprLoc();
  10676. SourceRange ERange = E->getSourceRange();
  10677. // The base of elements of list in a map clause have to be either:
  10678. // - a reference to variable or field.
  10679. // - a member expression.
  10680. // - an array expression.
  10681. //
  10682. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  10683. // reference to 'r'.
  10684. //
  10685. // If we have:
  10686. //
  10687. // struct SS {
  10688. // Bla S;
  10689. // foo() {
  10690. // #pragma omp target map (S.Arr[:12]);
  10691. // }
  10692. // }
  10693. //
  10694. // We want to retrieve the member expression 'this->S';
  10695. Expr *RelevantExpr = nullptr;
  10696. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  10697. // If a list item is an array section, it must specify contiguous storage.
  10698. //
  10699. // For this restriction it is sufficient that we make sure only references
  10700. // to variables or fields and array expressions, and that no array sections
  10701. // exist except in the rightmost expression (unless they cover the whole
  10702. // dimension of the array). E.g. these would be invalid:
  10703. //
  10704. // r.ArrS[3:5].Arr[6:7]
  10705. //
  10706. // r.ArrS[3:5].x
  10707. //
  10708. // but these would be valid:
  10709. // r.ArrS[3].Arr[6:7]
  10710. //
  10711. // r.ArrS[3].x
  10712. bool AllowUnitySizeArraySection = true;
  10713. bool AllowWholeSizeArraySection = true;
  10714. while (!RelevantExpr) {
  10715. E = E->IgnoreParenImpCasts();
  10716. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  10717. if (!isa<VarDecl>(CurE->getDecl()))
  10718. break;
  10719. RelevantExpr = CurE;
  10720. // If we got a reference to a declaration, we should not expect any array
  10721. // section before that.
  10722. AllowUnitySizeArraySection = false;
  10723. AllowWholeSizeArraySection = false;
  10724. // Record the component.
  10725. CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
  10726. CurE, CurE->getDecl()));
  10727. continue;
  10728. }
  10729. if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  10730. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  10731. if (isa<CXXThisExpr>(BaseE))
  10732. // We found a base expression: this->Val.
  10733. RelevantExpr = CurE;
  10734. else
  10735. E = BaseE;
  10736. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  10737. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  10738. << CurE->getSourceRange();
  10739. break;
  10740. }
  10741. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  10742. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  10743. // A bit-field cannot appear in a map clause.
  10744. //
  10745. if (FD->isBitField()) {
  10746. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  10747. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  10748. break;
  10749. }
  10750. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10751. // If the type of a list item is a reference to a type T then the type
  10752. // will be considered to be T for all purposes of this clause.
  10753. QualType CurType = BaseE->getType().getNonReferenceType();
  10754. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  10755. // A list item cannot be a variable that is a member of a structure with
  10756. // a union type.
  10757. //
  10758. if (auto *RT = CurType->getAs<RecordType>())
  10759. if (RT->isUnionType()) {
  10760. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  10761. << CurE->getSourceRange();
  10762. break;
  10763. }
  10764. // If we got a member expression, we should not expect any array section
  10765. // before that:
  10766. //
  10767. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  10768. // If a list item is an element of a structure, only the rightmost symbol
  10769. // of the variable reference can be an array section.
  10770. //
  10771. AllowUnitySizeArraySection = false;
  10772. AllowWholeSizeArraySection = false;
  10773. // Record the component.
  10774. CurComponents.push_back(
  10775. OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
  10776. continue;
  10777. }
  10778. if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  10779. E = CurE->getBase()->IgnoreParenImpCasts();
  10780. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  10781. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10782. << 0 << CurE->getSourceRange();
  10783. break;
  10784. }
  10785. // If we got an array subscript that express the whole dimension we
  10786. // can have any array expressions before. If it only expressing part of
  10787. // the dimension, we can only have unitary-size array expressions.
  10788. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  10789. E->getType()))
  10790. AllowWholeSizeArraySection = false;
  10791. // Record the component - we don't have any declaration associated.
  10792. CurComponents.push_back(
  10793. OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
  10794. continue;
  10795. }
  10796. if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  10797. E = CurE->getBase()->IgnoreParenImpCasts();
  10798. auto CurType =
  10799. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10800. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10801. // If the type of a list item is a reference to a type T then the type
  10802. // will be considered to be T for all purposes of this clause.
  10803. if (CurType->isReferenceType())
  10804. CurType = CurType->getPointeeType();
  10805. bool IsPointer = CurType->isAnyPointerType();
  10806. if (!IsPointer && !CurType->isArrayType()) {
  10807. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10808. << 0 << CurE->getSourceRange();
  10809. break;
  10810. }
  10811. bool NotWhole =
  10812. CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  10813. bool NotUnity =
  10814. CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  10815. if (AllowWholeSizeArraySection) {
  10816. // Any array section is currently allowed. Allowing a whole size array
  10817. // section implies allowing a unity array section as well.
  10818. //
  10819. // If this array section refers to the whole dimension we can still
  10820. // accept other array sections before this one, except if the base is a
  10821. // pointer. Otherwise, only unitary sections are accepted.
  10822. if (NotWhole || IsPointer)
  10823. AllowWholeSizeArraySection = false;
  10824. } else if (AllowUnitySizeArraySection && NotUnity) {
  10825. // A unity or whole array section is not allowed and that is not
  10826. // compatible with the properties of the current array section.
  10827. SemaRef.Diag(
  10828. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  10829. << CurE->getSourceRange();
  10830. break;
  10831. }
  10832. // Record the component - we don't have any declaration associated.
  10833. CurComponents.push_back(
  10834. OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
  10835. continue;
  10836. }
  10837. // If nothing else worked, this is not a valid map clause expression.
  10838. SemaRef.Diag(ELoc,
  10839. diag::err_omp_expected_named_var_member_or_array_expression)
  10840. << ERange;
  10841. break;
  10842. }
  10843. return RelevantExpr;
  10844. }
  10845. // Return true if expression E associated with value VD has conflicts with other
  10846. // map information.
  10847. static bool CheckMapConflicts(
  10848. Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
  10849. bool CurrentRegionOnly,
  10850. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  10851. OpenMPClauseKind CKind) {
  10852. assert(VD && E);
  10853. SourceLocation ELoc = E->getExprLoc();
  10854. SourceRange ERange = E->getSourceRange();
  10855. // In order to easily check the conflicts we need to match each component of
  10856. // the expression under test with the components of the expressions that are
  10857. // already in the stack.
  10858. assert(!CurComponents.empty() && "Map clause expression with no components!");
  10859. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  10860. "Map clause expression with unexpected base!");
  10861. // Variables to help detecting enclosing problems in data environment nests.
  10862. bool IsEnclosedByDataEnvironmentExpr = false;
  10863. const Expr *EnclosingExpr = nullptr;
  10864. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  10865. VD, CurrentRegionOnly,
  10866. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  10867. StackComponents,
  10868. OpenMPClauseKind) -> bool {
  10869. assert(!StackComponents.empty() &&
  10870. "Map clause expression with no components!");
  10871. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  10872. "Map clause expression with unexpected base!");
  10873. // The whole expression in the stack.
  10874. auto *RE = StackComponents.front().getAssociatedExpression();
  10875. // Expressions must start from the same base. Here we detect at which
  10876. // point both expressions diverge from each other and see if we can
  10877. // detect if the memory referred to both expressions is contiguous and
  10878. // do not overlap.
  10879. auto CI = CurComponents.rbegin();
  10880. auto CE = CurComponents.rend();
  10881. auto SI = StackComponents.rbegin();
  10882. auto SE = StackComponents.rend();
  10883. for (; CI != CE && SI != SE; ++CI, ++SI) {
  10884. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  10885. // At most one list item can be an array item derived from a given
  10886. // variable in map clauses of the same construct.
  10887. if (CurrentRegionOnly &&
  10888. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  10889. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  10890. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  10891. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  10892. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  10893. diag::err_omp_multiple_array_items_in_map_clause)
  10894. << CI->getAssociatedExpression()->getSourceRange();
  10895. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  10896. diag::note_used_here)
  10897. << SI->getAssociatedExpression()->getSourceRange();
  10898. return true;
  10899. }
  10900. // Do both expressions have the same kind?
  10901. if (CI->getAssociatedExpression()->getStmtClass() !=
  10902. SI->getAssociatedExpression()->getStmtClass())
  10903. break;
  10904. // Are we dealing with different variables/fields?
  10905. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  10906. break;
  10907. }
  10908. // Check if the extra components of the expressions in the enclosing
  10909. // data environment are redundant for the current base declaration.
  10910. // If they are, the maps completely overlap, which is legal.
  10911. for (; SI != SE; ++SI) {
  10912. QualType Type;
  10913. if (auto *ASE =
  10914. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  10915. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  10916. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
  10917. SI->getAssociatedExpression())) {
  10918. auto *E = OASE->getBase()->IgnoreParenImpCasts();
  10919. Type =
  10920. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10921. }
  10922. if (Type.isNull() || Type->isAnyPointerType() ||
  10923. CheckArrayExpressionDoesNotReferToWholeSize(
  10924. SemaRef, SI->getAssociatedExpression(), Type))
  10925. break;
  10926. }
  10927. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10928. // List items of map clauses in the same construct must not share
  10929. // original storage.
  10930. //
  10931. // If the expressions are exactly the same or one is a subset of the
  10932. // other, it means they are sharing storage.
  10933. if (CI == CE && SI == SE) {
  10934. if (CurrentRegionOnly) {
  10935. if (CKind == OMPC_map)
  10936. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10937. else {
  10938. assert(CKind == OMPC_to || CKind == OMPC_from);
  10939. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  10940. << ERange;
  10941. }
  10942. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  10943. << RE->getSourceRange();
  10944. return true;
  10945. } else {
  10946. // If we find the same expression in the enclosing data environment,
  10947. // that is legal.
  10948. IsEnclosedByDataEnvironmentExpr = true;
  10949. return false;
  10950. }
  10951. }
  10952. QualType DerivedType =
  10953. std::prev(CI)->getAssociatedDeclaration()->getType();
  10954. SourceLocation DerivedLoc =
  10955. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  10956. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10957. // If the type of a list item is a reference to a type T then the type
  10958. // will be considered to be T for all purposes of this clause.
  10959. DerivedType = DerivedType.getNonReferenceType();
  10960. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  10961. // A variable for which the type is pointer and an array section
  10962. // derived from that variable must not appear as list items of map
  10963. // clauses of the same construct.
  10964. //
  10965. // Also, cover one of the cases in:
  10966. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  10967. // If any part of the original storage of a list item has corresponding
  10968. // storage in the device data environment, all of the original storage
  10969. // must have corresponding storage in the device data environment.
  10970. //
  10971. if (DerivedType->isAnyPointerType()) {
  10972. if (CI == CE || SI == SE) {
  10973. SemaRef.Diag(
  10974. DerivedLoc,
  10975. diag::err_omp_pointer_mapped_along_with_derived_section)
  10976. << DerivedLoc;
  10977. } else {
  10978. assert(CI != CE && SI != SE);
  10979. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  10980. << DerivedLoc;
  10981. }
  10982. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  10983. << RE->getSourceRange();
  10984. return true;
  10985. }
  10986. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10987. // List items of map clauses in the same construct must not share
  10988. // original storage.
  10989. //
  10990. // An expression is a subset of the other.
  10991. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  10992. if (CKind == OMPC_map)
  10993. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10994. else {
  10995. assert(CKind == OMPC_to || CKind == OMPC_from);
  10996. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  10997. << ERange;
  10998. }
  10999. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  11000. << RE->getSourceRange();
  11001. return true;
  11002. }
  11003. // The current expression uses the same base as other expression in the
  11004. // data environment but does not contain it completely.
  11005. if (!CurrentRegionOnly && SI != SE)
  11006. EnclosingExpr = RE;
  11007. // The current expression is a subset of the expression in the data
  11008. // environment.
  11009. IsEnclosedByDataEnvironmentExpr |=
  11010. (!CurrentRegionOnly && CI != CE && SI == SE);
  11011. return false;
  11012. });
  11013. if (CurrentRegionOnly)
  11014. return FoundError;
  11015. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  11016. // If any part of the original storage of a list item has corresponding
  11017. // storage in the device data environment, all of the original storage must
  11018. // have corresponding storage in the device data environment.
  11019. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  11020. // If a list item is an element of a structure, and a different element of
  11021. // the structure has a corresponding list item in the device data environment
  11022. // prior to a task encountering the construct associated with the map clause,
  11023. // then the list item must also have a corresponding list item in the device
  11024. // data environment prior to the task encountering the construct.
  11025. //
  11026. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  11027. SemaRef.Diag(ELoc,
  11028. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  11029. << ERange;
  11030. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  11031. << EnclosingExpr->getSourceRange();
  11032. return true;
  11033. }
  11034. return FoundError;
  11035. }
  11036. namespace {
  11037. // Utility struct that gathers all the related lists associated with a mappable
  11038. // expression.
  11039. struct MappableVarListInfo final {
  11040. // The list of expressions.
  11041. ArrayRef<Expr *> VarList;
  11042. // The list of processed expressions.
  11043. SmallVector<Expr *, 16> ProcessedVarList;
  11044. // The mappble components for each expression.
  11045. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  11046. // The base declaration of the variable.
  11047. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  11048. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  11049. // We have a list of components and base declarations for each entry in the
  11050. // variable list.
  11051. VarComponents.reserve(VarList.size());
  11052. VarBaseDeclarations.reserve(VarList.size());
  11053. }
  11054. };
  11055. }
  11056. // Check the validity of the provided variable list for the provided clause kind
  11057. // \a CKind. In the check process the valid expressions, and mappable expression
  11058. // components and variables are extracted and used to fill \a Vars,
  11059. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  11060. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  11061. static void
  11062. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  11063. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  11064. SourceLocation StartLoc,
  11065. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  11066. bool IsMapTypeImplicit = false) {
  11067. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  11068. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  11069. "Unexpected clause kind with mappable expressions!");
  11070. // Keep track of the mappable components and base declarations in this clause.
  11071. // Each entry in the list is going to have a list of components associated. We
  11072. // record each set of the components so that we can build the clause later on.
  11073. // In the end we should have the same amount of declarations and component
  11074. // lists.
  11075. for (auto &RE : MVLI.VarList) {
  11076. assert(RE && "Null expr in omp to/from/map clause");
  11077. SourceLocation ELoc = RE->getExprLoc();
  11078. auto *VE = RE->IgnoreParenLValueCasts();
  11079. if (VE->isValueDependent() || VE->isTypeDependent() ||
  11080. VE->isInstantiationDependent() ||
  11081. VE->containsUnexpandedParameterPack()) {
  11082. // We can only analyze this information once the missing information is
  11083. // resolved.
  11084. MVLI.ProcessedVarList.push_back(RE);
  11085. continue;
  11086. }
  11087. auto *SimpleExpr = RE->IgnoreParenCasts();
  11088. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  11089. SemaRef.Diag(ELoc,
  11090. diag::err_omp_expected_named_var_member_or_array_expression)
  11091. << RE->getSourceRange();
  11092. continue;
  11093. }
  11094. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  11095. ValueDecl *CurDeclaration = nullptr;
  11096. // Obtain the array or member expression bases if required. Also, fill the
  11097. // components array with all the components identified in the process.
  11098. auto *BE =
  11099. CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
  11100. if (!BE)
  11101. continue;
  11102. assert(!CurComponents.empty() &&
  11103. "Invalid mappable expression information.");
  11104. // For the following checks, we rely on the base declaration which is
  11105. // expected to be associated with the last component. The declaration is
  11106. // expected to be a variable or a field (if 'this' is being mapped).
  11107. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  11108. assert(CurDeclaration && "Null decl on map clause.");
  11109. assert(
  11110. CurDeclaration->isCanonicalDecl() &&
  11111. "Expecting components to have associated only canonical declarations.");
  11112. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  11113. auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  11114. assert((VD || FD) && "Only variables or fields are expected here!");
  11115. (void)FD;
  11116. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  11117. // threadprivate variables cannot appear in a map clause.
  11118. // OpenMP 4.5 [2.10.5, target update Construct]
  11119. // threadprivate variables cannot appear in a from clause.
  11120. if (VD && DSAS->isThreadPrivate(VD)) {
  11121. auto DVar = DSAS->getTopDSA(VD, false);
  11122. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  11123. << getOpenMPClauseName(CKind);
  11124. ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
  11125. continue;
  11126. }
  11127. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11128. // A list item cannot appear in both a map clause and a data-sharing
  11129. // attribute clause on the same construct.
  11130. // Check conflicts with other map clause expressions. We check the conflicts
  11131. // with the current construct separately from the enclosing data
  11132. // environment, because the restrictions are different. We only have to
  11133. // check conflicts across regions for the map clauses.
  11134. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11135. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  11136. break;
  11137. if (CKind == OMPC_map &&
  11138. CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  11139. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  11140. break;
  11141. // OpenMP 4.5 [2.10.5, target update Construct]
  11142. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11143. // If the type of a list item is a reference to a type T then the type will
  11144. // be considered to be T for all purposes of this clause.
  11145. QualType Type = CurDeclaration->getType().getNonReferenceType();
  11146. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  11147. // A list item in a to or from clause must have a mappable type.
  11148. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  11149. // A list item must have a mappable type.
  11150. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  11151. DSAS, Type))
  11152. continue;
  11153. if (CKind == OMPC_map) {
  11154. // target enter data
  11155. // OpenMP [2.10.2, Restrictions, p. 99]
  11156. // A map-type must be specified in all map clauses and must be either
  11157. // to or alloc.
  11158. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  11159. if (DKind == OMPD_target_enter_data &&
  11160. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  11161. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11162. << (IsMapTypeImplicit ? 1 : 0)
  11163. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11164. << getOpenMPDirectiveName(DKind);
  11165. continue;
  11166. }
  11167. // target exit_data
  11168. // OpenMP [2.10.3, Restrictions, p. 102]
  11169. // A map-type must be specified in all map clauses and must be either
  11170. // from, release, or delete.
  11171. if (DKind == OMPD_target_exit_data &&
  11172. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  11173. MapType == OMPC_MAP_delete)) {
  11174. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  11175. << (IsMapTypeImplicit ? 1 : 0)
  11176. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  11177. << getOpenMPDirectiveName(DKind);
  11178. continue;
  11179. }
  11180. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  11181. // A list item cannot appear in both a map clause and a data-sharing
  11182. // attribute clause on the same construct
  11183. if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
  11184. DKind == OMPD_target_teams_distribute ||
  11185. DKind == OMPD_target_teams_distribute_parallel_for ||
  11186. DKind == OMPD_target_teams_distribute_parallel_for_simd ||
  11187. DKind == OMPD_target_teams_distribute_simd) && VD) {
  11188. auto DVar = DSAS->getTopDSA(VD, false);
  11189. if (isOpenMPPrivate(DVar.CKind)) {
  11190. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11191. << getOpenMPClauseName(DVar.CKind)
  11192. << getOpenMPClauseName(OMPC_map)
  11193. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  11194. ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
  11195. continue;
  11196. }
  11197. }
  11198. }
  11199. // Save the current expression.
  11200. MVLI.ProcessedVarList.push_back(RE);
  11201. // Store the components in the stack so that they can be used to check
  11202. // against other clauses later on.
  11203. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  11204. /*WhereFoundClauseKind=*/OMPC_map);
  11205. // Save the components and declaration to create the clause. For purposes of
  11206. // the clause creation, any component list that has has base 'this' uses
  11207. // null as base declaration.
  11208. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11209. MVLI.VarComponents.back().append(CurComponents.begin(),
  11210. CurComponents.end());
  11211. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  11212. : CurDeclaration);
  11213. }
  11214. }
  11215. OMPClause *
  11216. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  11217. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  11218. SourceLocation MapLoc, SourceLocation ColonLoc,
  11219. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11220. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11221. MappableVarListInfo MVLI(VarList);
  11222. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  11223. MapType, IsMapTypeImplicit);
  11224. // We need to produce a map clause even if we don't have variables so that
  11225. // other diagnostics related with non-existing map clauses are accurate.
  11226. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11227. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11228. MVLI.VarComponents, MapTypeModifier, MapType,
  11229. IsMapTypeImplicit, MapLoc);
  11230. }
  11231. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  11232. TypeResult ParsedType) {
  11233. assert(ParsedType.isUsable());
  11234. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  11235. if (ReductionType.isNull())
  11236. return QualType();
  11237. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  11238. // A type name in a declare reduction directive cannot be a function type, an
  11239. // array type, a reference type, or a type qualified with const, volatile or
  11240. // restrict.
  11241. if (ReductionType.hasQualifiers()) {
  11242. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  11243. return QualType();
  11244. }
  11245. if (ReductionType->isFunctionType()) {
  11246. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  11247. return QualType();
  11248. }
  11249. if (ReductionType->isReferenceType()) {
  11250. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  11251. return QualType();
  11252. }
  11253. if (ReductionType->isArrayType()) {
  11254. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  11255. return QualType();
  11256. }
  11257. return ReductionType;
  11258. }
  11259. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  11260. Scope *S, DeclContext *DC, DeclarationName Name,
  11261. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  11262. AccessSpecifier AS, Decl *PrevDeclInScope) {
  11263. SmallVector<Decl *, 8> Decls;
  11264. Decls.reserve(ReductionTypes.size());
  11265. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  11266. forRedeclarationInCurContext());
  11267. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  11268. // A reduction-identifier may not be re-declared in the current scope for the
  11269. // same type or for a type that is compatible according to the base language
  11270. // rules.
  11271. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  11272. OMPDeclareReductionDecl *PrevDRD = nullptr;
  11273. bool InCompoundScope = true;
  11274. if (S != nullptr) {
  11275. // Find previous declaration with the same name not referenced in other
  11276. // declarations.
  11277. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  11278. InCompoundScope =
  11279. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  11280. LookupName(Lookup, S);
  11281. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  11282. /*AllowInlineNamespace=*/false);
  11283. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  11284. auto Filter = Lookup.makeFilter();
  11285. while (Filter.hasNext()) {
  11286. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  11287. if (InCompoundScope) {
  11288. auto I = UsedAsPrevious.find(PrevDecl);
  11289. if (I == UsedAsPrevious.end())
  11290. UsedAsPrevious[PrevDecl] = false;
  11291. if (auto *D = PrevDecl->getPrevDeclInScope())
  11292. UsedAsPrevious[D] = true;
  11293. }
  11294. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  11295. PrevDecl->getLocation();
  11296. }
  11297. Filter.done();
  11298. if (InCompoundScope) {
  11299. for (auto &PrevData : UsedAsPrevious) {
  11300. if (!PrevData.second) {
  11301. PrevDRD = PrevData.first;
  11302. break;
  11303. }
  11304. }
  11305. }
  11306. } else if (PrevDeclInScope != nullptr) {
  11307. auto *PrevDRDInScope = PrevDRD =
  11308. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  11309. do {
  11310. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  11311. PrevDRDInScope->getLocation();
  11312. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  11313. } while (PrevDRDInScope != nullptr);
  11314. }
  11315. for (auto &TyData : ReductionTypes) {
  11316. auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  11317. bool Invalid = false;
  11318. if (I != PreviousRedeclTypes.end()) {
  11319. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  11320. << TyData.first;
  11321. Diag(I->second, diag::note_previous_definition);
  11322. Invalid = true;
  11323. }
  11324. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  11325. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  11326. Name, TyData.first, PrevDRD);
  11327. DC->addDecl(DRD);
  11328. DRD->setAccess(AS);
  11329. Decls.push_back(DRD);
  11330. if (Invalid)
  11331. DRD->setInvalidDecl();
  11332. else
  11333. PrevDRD = DRD;
  11334. }
  11335. return DeclGroupPtrTy::make(
  11336. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  11337. }
  11338. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  11339. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11340. // Enter new function scope.
  11341. PushFunctionScope();
  11342. getCurFunction()->setHasBranchProtectedScope();
  11343. getCurFunction()->setHasOMPDeclareReductionCombiner();
  11344. if (S != nullptr)
  11345. PushDeclContext(S, DRD);
  11346. else
  11347. CurContext = DRD;
  11348. PushExpressionEvaluationContext(
  11349. ExpressionEvaluationContext::PotentiallyEvaluated);
  11350. QualType ReductionType = DRD->getType();
  11351. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  11352. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  11353. // uses semantics of argument handles by value, but it should be passed by
  11354. // reference. C lang does not support references, so pass all parameters as
  11355. // pointers.
  11356. // Create 'T omp_in;' variable.
  11357. auto *OmpInParm =
  11358. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  11359. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  11360. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  11361. // uses semantics of argument handles by value, but it should be passed by
  11362. // reference. C lang does not support references, so pass all parameters as
  11363. // pointers.
  11364. // Create 'T omp_out;' variable.
  11365. auto *OmpOutParm =
  11366. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  11367. if (S != nullptr) {
  11368. PushOnScopeChains(OmpInParm, S);
  11369. PushOnScopeChains(OmpOutParm, S);
  11370. } else {
  11371. DRD->addDecl(OmpInParm);
  11372. DRD->addDecl(OmpOutParm);
  11373. }
  11374. }
  11375. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  11376. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11377. DiscardCleanupsInEvaluationContext();
  11378. PopExpressionEvaluationContext();
  11379. PopDeclContext();
  11380. PopFunctionScopeInfo();
  11381. if (Combiner != nullptr)
  11382. DRD->setCombiner(Combiner);
  11383. else
  11384. DRD->setInvalidDecl();
  11385. }
  11386. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  11387. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11388. // Enter new function scope.
  11389. PushFunctionScope();
  11390. getCurFunction()->setHasBranchProtectedScope();
  11391. if (S != nullptr)
  11392. PushDeclContext(S, DRD);
  11393. else
  11394. CurContext = DRD;
  11395. PushExpressionEvaluationContext(
  11396. ExpressionEvaluationContext::PotentiallyEvaluated);
  11397. QualType ReductionType = DRD->getType();
  11398. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  11399. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  11400. // uses semantics of argument handles by value, but it should be passed by
  11401. // reference. C lang does not support references, so pass all parameters as
  11402. // pointers.
  11403. // Create 'T omp_priv;' variable.
  11404. auto *OmpPrivParm =
  11405. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  11406. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  11407. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  11408. // uses semantics of argument handles by value, but it should be passed by
  11409. // reference. C lang does not support references, so pass all parameters as
  11410. // pointers.
  11411. // Create 'T omp_orig;' variable.
  11412. auto *OmpOrigParm =
  11413. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  11414. if (S != nullptr) {
  11415. PushOnScopeChains(OmpPrivParm, S);
  11416. PushOnScopeChains(OmpOrigParm, S);
  11417. } else {
  11418. DRD->addDecl(OmpPrivParm);
  11419. DRD->addDecl(OmpOrigParm);
  11420. }
  11421. return OmpPrivParm;
  11422. }
  11423. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  11424. VarDecl *OmpPrivParm) {
  11425. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11426. DiscardCleanupsInEvaluationContext();
  11427. PopExpressionEvaluationContext();
  11428. PopDeclContext();
  11429. PopFunctionScopeInfo();
  11430. if (Initializer != nullptr) {
  11431. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  11432. } else if (OmpPrivParm->hasInit()) {
  11433. DRD->setInitializer(OmpPrivParm->getInit(),
  11434. OmpPrivParm->isDirectInit()
  11435. ? OMPDeclareReductionDecl::DirectInit
  11436. : OMPDeclareReductionDecl::CopyInit);
  11437. } else {
  11438. DRD->setInvalidDecl();
  11439. }
  11440. }
  11441. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  11442. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  11443. for (auto *D : DeclReductions.get()) {
  11444. if (IsValid) {
  11445. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  11446. if (S != nullptr)
  11447. PushOnScopeChains(DRD, S, /*AddToContext=*/false);
  11448. } else
  11449. D->setInvalidDecl();
  11450. }
  11451. return DeclReductions;
  11452. }
  11453. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  11454. SourceLocation StartLoc,
  11455. SourceLocation LParenLoc,
  11456. SourceLocation EndLoc) {
  11457. Expr *ValExpr = NumTeams;
  11458. Stmt *HelperValStmt = nullptr;
  11459. // OpenMP [teams Constrcut, Restrictions]
  11460. // The num_teams expression must evaluate to a positive integer value.
  11461. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  11462. /*StrictlyPositive=*/true))
  11463. return nullptr;
  11464. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11465. OpenMPDirectiveKind CaptureRegion =
  11466. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  11467. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11468. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11469. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11470. HelperValStmt = buildPreInits(Context, Captures);
  11471. }
  11472. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  11473. StartLoc, LParenLoc, EndLoc);
  11474. }
  11475. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  11476. SourceLocation StartLoc,
  11477. SourceLocation LParenLoc,
  11478. SourceLocation EndLoc) {
  11479. Expr *ValExpr = ThreadLimit;
  11480. Stmt *HelperValStmt = nullptr;
  11481. // OpenMP [teams Constrcut, Restrictions]
  11482. // The thread_limit expression must evaluate to a positive integer value.
  11483. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  11484. /*StrictlyPositive=*/true))
  11485. return nullptr;
  11486. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11487. OpenMPDirectiveKind CaptureRegion =
  11488. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  11489. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11490. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11491. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11492. HelperValStmt = buildPreInits(Context, Captures);
  11493. }
  11494. return new (Context) OMPThreadLimitClause(
  11495. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  11496. }
  11497. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  11498. SourceLocation StartLoc,
  11499. SourceLocation LParenLoc,
  11500. SourceLocation EndLoc) {
  11501. Expr *ValExpr = Priority;
  11502. // OpenMP [2.9.1, task Constrcut]
  11503. // The priority-value is a non-negative numerical scalar expression.
  11504. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  11505. /*StrictlyPositive=*/false))
  11506. return nullptr;
  11507. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11508. }
  11509. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  11510. SourceLocation StartLoc,
  11511. SourceLocation LParenLoc,
  11512. SourceLocation EndLoc) {
  11513. Expr *ValExpr = Grainsize;
  11514. // OpenMP [2.9.2, taskloop Constrcut]
  11515. // The parameter of the grainsize clause must be a positive integer
  11516. // expression.
  11517. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  11518. /*StrictlyPositive=*/true))
  11519. return nullptr;
  11520. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11521. }
  11522. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  11523. SourceLocation StartLoc,
  11524. SourceLocation LParenLoc,
  11525. SourceLocation EndLoc) {
  11526. Expr *ValExpr = NumTasks;
  11527. // OpenMP [2.9.2, taskloop Constrcut]
  11528. // The parameter of the num_tasks clause must be a positive integer
  11529. // expression.
  11530. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  11531. /*StrictlyPositive=*/true))
  11532. return nullptr;
  11533. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11534. }
  11535. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  11536. SourceLocation LParenLoc,
  11537. SourceLocation EndLoc) {
  11538. // OpenMP [2.13.2, critical construct, Description]
  11539. // ... where hint-expression is an integer constant expression that evaluates
  11540. // to a valid lock hint.
  11541. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  11542. if (HintExpr.isInvalid())
  11543. return nullptr;
  11544. return new (Context)
  11545. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  11546. }
  11547. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  11548. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  11549. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  11550. SourceLocation EndLoc) {
  11551. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  11552. std::string Values;
  11553. Values += "'";
  11554. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  11555. Values += "'";
  11556. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  11557. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  11558. return nullptr;
  11559. }
  11560. Expr *ValExpr = ChunkSize;
  11561. Stmt *HelperValStmt = nullptr;
  11562. if (ChunkSize) {
  11563. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  11564. !ChunkSize->isInstantiationDependent() &&
  11565. !ChunkSize->containsUnexpandedParameterPack()) {
  11566. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  11567. ExprResult Val =
  11568. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  11569. if (Val.isInvalid())
  11570. return nullptr;
  11571. ValExpr = Val.get();
  11572. // OpenMP [2.7.1, Restrictions]
  11573. // chunk_size must be a loop invariant integer expression with a positive
  11574. // value.
  11575. llvm::APSInt Result;
  11576. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  11577. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  11578. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  11579. << "dist_schedule" << ChunkSize->getSourceRange();
  11580. return nullptr;
  11581. }
  11582. } else if (getOpenMPCaptureRegionForClause(
  11583. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  11584. OMPD_unknown &&
  11585. !CurContext->isDependentContext()) {
  11586. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11587. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11588. HelperValStmt = buildPreInits(Context, Captures);
  11589. }
  11590. }
  11591. }
  11592. return new (Context)
  11593. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  11594. Kind, ValExpr, HelperValStmt);
  11595. }
  11596. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  11597. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  11598. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  11599. SourceLocation KindLoc, SourceLocation EndLoc) {
  11600. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  11601. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  11602. std::string Value;
  11603. SourceLocation Loc;
  11604. Value += "'";
  11605. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  11606. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11607. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  11608. Loc = MLoc;
  11609. } else {
  11610. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11611. OMPC_DEFAULTMAP_scalar);
  11612. Loc = KindLoc;
  11613. }
  11614. Value += "'";
  11615. Diag(Loc, diag::err_omp_unexpected_clause_value)
  11616. << Value << getOpenMPClauseName(OMPC_defaultmap);
  11617. return nullptr;
  11618. }
  11619. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  11620. return new (Context)
  11621. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  11622. }
  11623. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  11624. DeclContext *CurLexicalContext = getCurLexicalContext();
  11625. if (!CurLexicalContext->isFileContext() &&
  11626. !CurLexicalContext->isExternCContext() &&
  11627. !CurLexicalContext->isExternCXXContext() &&
  11628. !isa<CXXRecordDecl>(CurLexicalContext) &&
  11629. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  11630. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  11631. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  11632. Diag(Loc, diag::err_omp_region_not_file_context);
  11633. return false;
  11634. }
  11635. if (IsInOpenMPDeclareTargetContext) {
  11636. Diag(Loc, diag::err_omp_enclosed_declare_target);
  11637. return false;
  11638. }
  11639. IsInOpenMPDeclareTargetContext = true;
  11640. return true;
  11641. }
  11642. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  11643. assert(IsInOpenMPDeclareTargetContext &&
  11644. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  11645. IsInOpenMPDeclareTargetContext = false;
  11646. }
  11647. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  11648. CXXScopeSpec &ScopeSpec,
  11649. const DeclarationNameInfo &Id,
  11650. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  11651. NamedDeclSetType &SameDirectiveDecls) {
  11652. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  11653. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  11654. if (Lookup.isAmbiguous())
  11655. return;
  11656. Lookup.suppressDiagnostics();
  11657. if (!Lookup.isSingleResult()) {
  11658. if (TypoCorrection Corrected =
  11659. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  11660. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  11661. CTK_ErrorRecovery)) {
  11662. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  11663. << Id.getName());
  11664. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  11665. return;
  11666. }
  11667. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  11668. return;
  11669. }
  11670. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  11671. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  11672. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  11673. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  11674. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  11675. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  11676. ND->addAttr(A);
  11677. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11678. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  11679. checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
  11680. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  11681. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  11682. << Id.getName();
  11683. }
  11684. } else
  11685. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  11686. }
  11687. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  11688. Sema &SemaRef, Decl *D) {
  11689. if (!D)
  11690. return;
  11691. Decl *LD = nullptr;
  11692. if (isa<TagDecl>(D)) {
  11693. LD = cast<TagDecl>(D)->getDefinition();
  11694. } else if (isa<VarDecl>(D)) {
  11695. LD = cast<VarDecl>(D)->getDefinition();
  11696. // If this is an implicit variable that is legal and we do not need to do
  11697. // anything.
  11698. if (cast<VarDecl>(D)->isImplicit()) {
  11699. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11700. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11701. D->addAttr(A);
  11702. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11703. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11704. return;
  11705. }
  11706. } else if (isa<FunctionDecl>(D)) {
  11707. const FunctionDecl *FD = nullptr;
  11708. if (cast<FunctionDecl>(D)->hasBody(FD))
  11709. LD = const_cast<FunctionDecl *>(FD);
  11710. // If the definition is associated with the current declaration in the
  11711. // target region (it can be e.g. a lambda) that is legal and we do not need
  11712. // to do anything else.
  11713. if (LD == D) {
  11714. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11715. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11716. D->addAttr(A);
  11717. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11718. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11719. return;
  11720. }
  11721. }
  11722. if (!LD)
  11723. LD = D;
  11724. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11725. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  11726. // Outlined declaration is not declared target.
  11727. if (LD->isOutOfLine()) {
  11728. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11729. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11730. } else {
  11731. DeclContext *DC = LD->getDeclContext();
  11732. while (DC) {
  11733. if (isa<FunctionDecl>(DC) &&
  11734. cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
  11735. break;
  11736. DC = DC->getParent();
  11737. }
  11738. if (DC)
  11739. return;
  11740. // Is not declared in target context.
  11741. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11742. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11743. }
  11744. // Mark decl as declared target to prevent further diagnostic.
  11745. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11746. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11747. D->addAttr(A);
  11748. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11749. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11750. }
  11751. }
  11752. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  11753. Sema &SemaRef, DSAStackTy *Stack,
  11754. ValueDecl *VD) {
  11755. if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
  11756. return true;
  11757. if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
  11758. return false;
  11759. return true;
  11760. }
  11761. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
  11762. if (!D || D->isInvalidDecl())
  11763. return;
  11764. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  11765. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  11766. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  11767. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  11768. if (DSAStack->isThreadPrivate(VD)) {
  11769. Diag(SL, diag::err_omp_threadprivate_in_target);
  11770. ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  11771. return;
  11772. }
  11773. }
  11774. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  11775. // Problem if any with var declared with incomplete type will be reported
  11776. // as normal, so no need to check it here.
  11777. if ((E || !VD->getType()->isIncompleteType()) &&
  11778. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  11779. // Mark decl as declared target to prevent further diagnostic.
  11780. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
  11781. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11782. Context, OMPDeclareTargetDeclAttr::MT_To);
  11783. VD->addAttr(A);
  11784. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11785. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  11786. }
  11787. return;
  11788. }
  11789. }
  11790. if (!E) {
  11791. // Checking declaration inside declare target region.
  11792. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11793. (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
  11794. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11795. Context, OMPDeclareTargetDeclAttr::MT_To);
  11796. D->addAttr(A);
  11797. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11798. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11799. }
  11800. return;
  11801. }
  11802. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  11803. }
  11804. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  11805. SourceLocation StartLoc,
  11806. SourceLocation LParenLoc,
  11807. SourceLocation EndLoc) {
  11808. MappableVarListInfo MVLI(VarList);
  11809. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  11810. if (MVLI.ProcessedVarList.empty())
  11811. return nullptr;
  11812. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11813. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11814. MVLI.VarComponents);
  11815. }
  11816. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  11817. SourceLocation StartLoc,
  11818. SourceLocation LParenLoc,
  11819. SourceLocation EndLoc) {
  11820. MappableVarListInfo MVLI(VarList);
  11821. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  11822. if (MVLI.ProcessedVarList.empty())
  11823. return nullptr;
  11824. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11825. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11826. MVLI.VarComponents);
  11827. }
  11828. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  11829. SourceLocation StartLoc,
  11830. SourceLocation LParenLoc,
  11831. SourceLocation EndLoc) {
  11832. MappableVarListInfo MVLI(VarList);
  11833. SmallVector<Expr *, 8> PrivateCopies;
  11834. SmallVector<Expr *, 8> Inits;
  11835. for (auto &RefExpr : VarList) {
  11836. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  11837. SourceLocation ELoc;
  11838. SourceRange ERange;
  11839. Expr *SimpleRefExpr = RefExpr;
  11840. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11841. if (Res.second) {
  11842. // It will be analyzed later.
  11843. MVLI.ProcessedVarList.push_back(RefExpr);
  11844. PrivateCopies.push_back(nullptr);
  11845. Inits.push_back(nullptr);
  11846. }
  11847. ValueDecl *D = Res.first;
  11848. if (!D)
  11849. continue;
  11850. QualType Type = D->getType();
  11851. Type = Type.getNonReferenceType().getUnqualifiedType();
  11852. auto *VD = dyn_cast<VarDecl>(D);
  11853. // Item should be a pointer or reference to pointer.
  11854. if (!Type->isPointerType()) {
  11855. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  11856. << 0 << RefExpr->getSourceRange();
  11857. continue;
  11858. }
  11859. // Build the private variable and the expression that refers to it.
  11860. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  11861. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11862. if (VDPrivate->isInvalidDecl())
  11863. continue;
  11864. CurContext->addDecl(VDPrivate);
  11865. auto VDPrivateRefExpr = buildDeclRefExpr(
  11866. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11867. // Add temporary variable to initialize the private copy of the pointer.
  11868. auto *VDInit =
  11869. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  11870. auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11871. RefExpr->getExprLoc());
  11872. AddInitializerToDecl(VDPrivate,
  11873. DefaultLvalueConversion(VDInitRefExpr).get(),
  11874. /*DirectInit=*/false);
  11875. // If required, build a capture to implement the privatization initialized
  11876. // with the current list item value.
  11877. DeclRefExpr *Ref = nullptr;
  11878. if (!VD)
  11879. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11880. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  11881. PrivateCopies.push_back(VDPrivateRefExpr);
  11882. Inits.push_back(VDInitRefExpr);
  11883. // We need to add a data sharing attribute for this variable to make sure it
  11884. // is correctly captured. A variable that shows up in a use_device_ptr has
  11885. // similar properties of a first private variable.
  11886. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11887. // Create a mappable component for the list item. List items in this clause
  11888. // only need a component.
  11889. MVLI.VarBaseDeclarations.push_back(D);
  11890. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11891. MVLI.VarComponents.back().push_back(
  11892. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  11893. }
  11894. if (MVLI.ProcessedVarList.empty())
  11895. return nullptr;
  11896. return OMPUseDevicePtrClause::Create(
  11897. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11898. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11899. }
  11900. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  11901. SourceLocation StartLoc,
  11902. SourceLocation LParenLoc,
  11903. SourceLocation EndLoc) {
  11904. MappableVarListInfo MVLI(VarList);
  11905. for (auto &RefExpr : VarList) {
  11906. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  11907. SourceLocation ELoc;
  11908. SourceRange ERange;
  11909. Expr *SimpleRefExpr = RefExpr;
  11910. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11911. if (Res.second) {
  11912. // It will be analyzed later.
  11913. MVLI.ProcessedVarList.push_back(RefExpr);
  11914. }
  11915. ValueDecl *D = Res.first;
  11916. if (!D)
  11917. continue;
  11918. QualType Type = D->getType();
  11919. // item should be a pointer or array or reference to pointer or array
  11920. if (!Type.getNonReferenceType()->isPointerType() &&
  11921. !Type.getNonReferenceType()->isArrayType()) {
  11922. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  11923. << 0 << RefExpr->getSourceRange();
  11924. continue;
  11925. }
  11926. // Check if the declaration in the clause does not show up in any data
  11927. // sharing attribute.
  11928. auto DVar = DSAStack->getTopDSA(D, false);
  11929. if (isOpenMPPrivate(DVar.CKind)) {
  11930. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11931. << getOpenMPClauseName(DVar.CKind)
  11932. << getOpenMPClauseName(OMPC_is_device_ptr)
  11933. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11934. ReportOriginalDSA(*this, DSAStack, D, DVar);
  11935. continue;
  11936. }
  11937. Expr *ConflictExpr;
  11938. if (DSAStack->checkMappableExprComponentListsForDecl(
  11939. D, /*CurrentRegionOnly=*/true,
  11940. [&ConflictExpr](
  11941. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  11942. OpenMPClauseKind) -> bool {
  11943. ConflictExpr = R.front().getAssociatedExpression();
  11944. return true;
  11945. })) {
  11946. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  11947. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  11948. << ConflictExpr->getSourceRange();
  11949. continue;
  11950. }
  11951. // Store the components in the stack so that they can be used to check
  11952. // against other clauses later on.
  11953. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  11954. DSAStack->addMappableExpressionComponents(
  11955. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  11956. // Record the expression we've just processed.
  11957. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  11958. // Create a mappable component for the list item. List items in this clause
  11959. // only need a component. We use a null declaration to signal fields in
  11960. // 'this'.
  11961. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  11962. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  11963. "Unexpected device pointer expression!");
  11964. MVLI.VarBaseDeclarations.push_back(
  11965. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  11966. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11967. MVLI.VarComponents.back().push_back(MC);
  11968. }
  11969. if (MVLI.ProcessedVarList.empty())
  11970. return nullptr;
  11971. return OMPIsDevicePtrClause::Create(
  11972. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11973. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11974. }