SemaOpenMP.cpp 490 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413
  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. }
  898. if (isStackEmpty())
  899. // Not in OpenMP execution region and top scope was already checked.
  900. return DVar;
  901. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  902. // in a Construct, C/C++, predetermined, p.4]
  903. // Static data members are shared.
  904. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  905. // in a Construct, C/C++, predetermined, p.7]
  906. // Variables with static storage duration that are declared in a scope
  907. // inside the construct are shared.
  908. auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
  909. if (VD && VD->isStaticDataMember()) {
  910. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  911. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  912. return DVar;
  913. DVar.CKind = OMPC_shared;
  914. return DVar;
  915. }
  916. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  917. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  918. Type = SemaRef.getASTContext().getBaseElementType(Type);
  919. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  920. // in a Construct, C/C++, predetermined, p.6]
  921. // Variables with const qualified type having no mutable member are
  922. // shared.
  923. CXXRecordDecl *RD =
  924. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  925. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  926. if (auto *CTD = CTSD->getSpecializedTemplate())
  927. RD = CTD->getTemplatedDecl();
  928. if (IsConstant &&
  929. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
  930. RD->hasMutableFields())) {
  931. // Variables with const-qualified type having no mutable member may be
  932. // listed in a firstprivate clause, even if they are static data members.
  933. DSAVarData DVarTemp = hasDSA(
  934. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
  935. MatchesAlways, FromParent);
  936. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  937. return DVar;
  938. DVar.CKind = OMPC_shared;
  939. return DVar;
  940. }
  941. // Explicitly specified attributes and local variables with predetermined
  942. // attributes.
  943. auto I = Stack.back().first.rbegin();
  944. auto EndI = Stack.back().first.rend();
  945. if (FromParent && I != EndI)
  946. std::advance(I, 1);
  947. if (I->SharingMap.count(D)) {
  948. DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
  949. DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
  950. DVar.CKind = I->SharingMap[D].Attributes;
  951. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  952. DVar.DKind = I->Directive;
  953. }
  954. return DVar;
  955. }
  956. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  957. bool FromParent) {
  958. if (isStackEmpty()) {
  959. StackTy::reverse_iterator I;
  960. return getDSA(I, D);
  961. }
  962. D = getCanonicalDecl(D);
  963. auto StartI = Stack.back().first.rbegin();
  964. auto EndI = Stack.back().first.rend();
  965. if (FromParent && StartI != EndI)
  966. std::advance(StartI, 1);
  967. return getDSA(StartI, D);
  968. }
  969. DSAStackTy::DSAVarData
  970. DSAStackTy::hasDSA(ValueDecl *D,
  971. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  972. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  973. bool FromParent) {
  974. if (isStackEmpty())
  975. return {};
  976. D = getCanonicalDecl(D);
  977. auto I = Stack.back().first.rbegin();
  978. auto EndI = Stack.back().first.rend();
  979. if (FromParent && I != EndI)
  980. std::advance(I, 1);
  981. for (; I != EndI; std::advance(I, 1)) {
  982. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  983. continue;
  984. auto NewI = I;
  985. DSAVarData DVar = getDSA(NewI, D);
  986. if (I == NewI && CPred(DVar.CKind))
  987. return DVar;
  988. }
  989. return {};
  990. }
  991. DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  992. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  993. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  994. bool FromParent) {
  995. if (isStackEmpty())
  996. return {};
  997. D = getCanonicalDecl(D);
  998. auto StartI = Stack.back().first.rbegin();
  999. auto EndI = Stack.back().first.rend();
  1000. if (FromParent && StartI != EndI)
  1001. std::advance(StartI, 1);
  1002. if (StartI == EndI || !DPred(StartI->Directive))
  1003. return {};
  1004. auto NewI = StartI;
  1005. DSAVarData DVar = getDSA(NewI, D);
  1006. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1007. }
  1008. bool DSAStackTy::hasExplicitDSA(
  1009. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  1010. unsigned Level, bool NotLastprivate) {
  1011. if (CPred(ClauseKindMode))
  1012. return true;
  1013. if (isStackEmpty())
  1014. return false;
  1015. D = getCanonicalDecl(D);
  1016. auto StartI = Stack.back().first.begin();
  1017. auto EndI = Stack.back().first.end();
  1018. if (std::distance(StartI, EndI) <= (int)Level)
  1019. return false;
  1020. std::advance(StartI, Level);
  1021. return (StartI->SharingMap.count(D) > 0) &&
  1022. StartI->SharingMap[D].RefExpr.getPointer() &&
  1023. CPred(StartI->SharingMap[D].Attributes) &&
  1024. (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
  1025. }
  1026. bool DSAStackTy::hasExplicitDirective(
  1027. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  1028. unsigned Level) {
  1029. if (isStackEmpty())
  1030. return false;
  1031. auto StartI = Stack.back().first.begin();
  1032. auto EndI = Stack.back().first.end();
  1033. if (std::distance(StartI, EndI) <= (int)Level)
  1034. return false;
  1035. std::advance(StartI, Level);
  1036. return DPred(StartI->Directive);
  1037. }
  1038. bool DSAStackTy::hasDirective(
  1039. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1040. const DeclarationNameInfo &, SourceLocation)>
  1041. &DPred,
  1042. bool FromParent) {
  1043. // We look only in the enclosing region.
  1044. if (isStackEmpty())
  1045. return false;
  1046. auto StartI = std::next(Stack.back().first.rbegin());
  1047. auto EndI = Stack.back().first.rend();
  1048. if (FromParent && StartI != EndI)
  1049. StartI = std::next(StartI);
  1050. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1051. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1052. return true;
  1053. }
  1054. return false;
  1055. }
  1056. void Sema::InitDataSharingAttributesStack() {
  1057. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1058. }
  1059. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1060. void Sema::pushOpenMPFunctionRegion() {
  1061. DSAStack->pushFunction();
  1062. }
  1063. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1064. DSAStack->popFunction(OldFSI);
  1065. }
  1066. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
  1067. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1068. auto &Ctx = getASTContext();
  1069. bool IsByRef = true;
  1070. // Find the directive that is associated with the provided scope.
  1071. D = cast<ValueDecl>(D->getCanonicalDecl());
  1072. auto Ty = D->getType();
  1073. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1074. // This table summarizes how a given variable should be passed to the device
  1075. // given its type and the clauses where it appears. This table is based on
  1076. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1077. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1078. //
  1079. // =========================================================================
  1080. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1081. // | |(tofrom:scalar)| | pvt | | | |
  1082. // =========================================================================
  1083. // | scl | | | | - | | bycopy|
  1084. // | scl | | - | x | - | - | bycopy|
  1085. // | scl | | x | - | - | - | null |
  1086. // | scl | x | | | - | | byref |
  1087. // | scl | x | - | x | - | - | bycopy|
  1088. // | scl | x | x | - | - | - | null |
  1089. // | scl | | - | - | - | x | byref |
  1090. // | scl | x | - | - | - | x | byref |
  1091. //
  1092. // | agg | n.a. | | | - | | byref |
  1093. // | agg | n.a. | - | x | - | - | byref |
  1094. // | agg | n.a. | x | - | - | - | null |
  1095. // | agg | n.a. | - | - | - | x | byref |
  1096. // | agg | n.a. | - | - | - | x[] | byref |
  1097. //
  1098. // | ptr | n.a. | | | - | | bycopy|
  1099. // | ptr | n.a. | - | x | - | - | bycopy|
  1100. // | ptr | n.a. | x | - | - | - | null |
  1101. // | ptr | n.a. | - | - | - | x | byref |
  1102. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1103. // | ptr | n.a. | - | - | x | | bycopy|
  1104. // | ptr | n.a. | - | - | x | x | bycopy|
  1105. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1106. // =========================================================================
  1107. // Legend:
  1108. // scl - scalar
  1109. // ptr - pointer
  1110. // agg - aggregate
  1111. // x - applies
  1112. // - - invalid in this combination
  1113. // [] - mapped with an array section
  1114. // byref - should be mapped by reference
  1115. // byval - should be mapped by value
  1116. // null - initialize a local variable to null on the device
  1117. //
  1118. // Observations:
  1119. // - All scalar declarations that show up in a map clause have to be passed
  1120. // by reference, because they may have been mapped in the enclosing data
  1121. // environment.
  1122. // - If the scalar value does not fit the size of uintptr, it has to be
  1123. // passed by reference, regardless the result in the table above.
  1124. // - For pointers mapped by value that have either an implicit map or an
  1125. // array section, the runtime library may pass the NULL value to the
  1126. // device instead of the value passed to it by the compiler.
  1127. if (Ty->isReferenceType())
  1128. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1129. // Locate map clauses and see if the variable being captured is referred to
  1130. // in any of those clauses. Here we only care about variables, not fields,
  1131. // because fields are part of aggregates.
  1132. bool IsVariableUsedInMapClause = false;
  1133. bool IsVariableAssociatedWithSection = false;
  1134. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1135. D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1136. MapExprComponents,
  1137. OpenMPClauseKind WhereFoundClauseKind) {
  1138. // Only the map clause information influences how a variable is
  1139. // captured. E.g. is_device_ptr does not require changing the default
  1140. // behavior.
  1141. if (WhereFoundClauseKind != OMPC_map)
  1142. return false;
  1143. auto EI = MapExprComponents.rbegin();
  1144. auto EE = MapExprComponents.rend();
  1145. assert(EI != EE && "Invalid map expression!");
  1146. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1147. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1148. ++EI;
  1149. if (EI == EE)
  1150. return false;
  1151. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1152. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1153. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1154. IsVariableAssociatedWithSection = true;
  1155. // There is nothing more we need to know about this variable.
  1156. return true;
  1157. }
  1158. // Keep looking for more map info.
  1159. return false;
  1160. });
  1161. if (IsVariableUsedInMapClause) {
  1162. // If variable is identified in a map clause it is always captured by
  1163. // reference except if it is a pointer that is dereferenced somehow.
  1164. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1165. } else {
  1166. // By default, all the data that has a scalar type is mapped by copy.
  1167. IsByRef = !Ty->isScalarType() ||
  1168. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
  1169. }
  1170. }
  1171. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1172. IsByRef = !DSAStack->hasExplicitDSA(
  1173. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1174. Level, /*NotLastprivate=*/true);
  1175. }
  1176. // When passing data by copy, we need to make sure it fits the uintptr size
  1177. // and alignment, because the runtime library only deals with uintptr types.
  1178. // If it does not fit the uintptr size, we need to pass the data by reference
  1179. // instead.
  1180. if (!IsByRef &&
  1181. (Ctx.getTypeSizeInChars(Ty) >
  1182. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1183. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1184. IsByRef = true;
  1185. }
  1186. return IsByRef;
  1187. }
  1188. unsigned Sema::getOpenMPNestingLevel() const {
  1189. assert(getLangOpts().OpenMP);
  1190. return DSAStack->getNestingLevel();
  1191. }
  1192. VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  1193. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1194. D = getCanonicalDecl(D);
  1195. // If we are attempting to capture a global variable in a directive with
  1196. // 'target' we return true so that this global is also mapped to the device.
  1197. //
  1198. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  1199. // then it should not be captured. Therefore, an extra check has to be
  1200. // inserted here once support for 'declare target' is added.
  1201. //
  1202. auto *VD = dyn_cast<VarDecl>(D);
  1203. if (VD && !VD->hasLocalStorage()) {
  1204. if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1205. !DSAStack->isClauseParsingMode())
  1206. return VD;
  1207. if (DSAStack->hasDirective(
  1208. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1209. SourceLocation) -> bool {
  1210. return isOpenMPTargetExecutionDirective(K);
  1211. },
  1212. false))
  1213. return VD;
  1214. }
  1215. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1216. (!DSAStack->isClauseParsingMode() ||
  1217. DSAStack->getParentDirective() != OMPD_unknown)) {
  1218. auto &&Info = DSAStack->isLoopControlVariable(D);
  1219. if (Info.first ||
  1220. (VD && VD->hasLocalStorage() &&
  1221. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  1222. (VD && DSAStack->isForceVarCapturing()))
  1223. return VD ? VD : Info.second;
  1224. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1225. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1226. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1227. DVarPrivate = DSAStack->hasDSA(
  1228. D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  1229. DSAStack->isClauseParsingMode());
  1230. if (DVarPrivate.CKind != OMPC_unknown)
  1231. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1232. }
  1233. return nullptr;
  1234. }
  1235. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  1236. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1237. return DSAStack->hasExplicitDSA(
  1238. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
  1239. Level) ||
  1240. // Consider taskgroup reduction descriptor variable a private to avoid
  1241. // possible capture in the region.
  1242. (DSAStack->hasExplicitDirective(
  1243. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1244. Level) &&
  1245. DSAStack->isTaskgroupReductionRef(D, Level));
  1246. }
  1247. void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
  1248. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1249. D = getCanonicalDecl(D);
  1250. OpenMPClauseKind OMPC = OMPC_unknown;
  1251. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1252. const unsigned NewLevel = I - 1;
  1253. if (DSAStack->hasExplicitDSA(D,
  1254. [&OMPC](const OpenMPClauseKind K) {
  1255. if (isOpenMPPrivate(K)) {
  1256. OMPC = K;
  1257. return true;
  1258. }
  1259. return false;
  1260. },
  1261. NewLevel))
  1262. break;
  1263. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1264. D, NewLevel,
  1265. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1266. OpenMPClauseKind) { return true; })) {
  1267. OMPC = OMPC_map;
  1268. break;
  1269. }
  1270. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1271. NewLevel)) {
  1272. OMPC = OMPC_firstprivate;
  1273. break;
  1274. }
  1275. }
  1276. if (OMPC != OMPC_unknown)
  1277. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1278. }
  1279. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  1280. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1281. // Return true if the current level is no longer enclosed in a target region.
  1282. auto *VD = dyn_cast<VarDecl>(D);
  1283. return VD && !VD->hasLocalStorage() &&
  1284. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1285. Level);
  1286. }
  1287. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1288. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1289. const DeclarationNameInfo &DirName,
  1290. Scope *CurScope, SourceLocation Loc) {
  1291. DSAStack->push(DKind, DirName, CurScope, Loc);
  1292. PushExpressionEvaluationContext(
  1293. ExpressionEvaluationContext::PotentiallyEvaluated);
  1294. }
  1295. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1296. DSAStack->setClauseParsingMode(K);
  1297. }
  1298. void Sema::EndOpenMPClause() {
  1299. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1300. }
  1301. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1302. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1303. // A variable of class type (or array thereof) that appears in a lastprivate
  1304. // clause requires an accessible, unambiguous default constructor for the
  1305. // class type, unless the list item is also specified in a firstprivate
  1306. // clause.
  1307. if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1308. for (auto *C : D->clauses()) {
  1309. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1310. SmallVector<Expr *, 8> PrivateCopies;
  1311. for (auto *DE : Clause->varlists()) {
  1312. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1313. PrivateCopies.push_back(nullptr);
  1314. continue;
  1315. }
  1316. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1317. VarDecl *VD = cast<VarDecl>(DRE->getDecl());
  1318. QualType Type = VD->getType().getNonReferenceType();
  1319. auto DVar = DSAStack->getTopDSA(VD, false);
  1320. if (DVar.CKind == OMPC_lastprivate) {
  1321. // Generate helper private variable and initialize it with the
  1322. // default value. The address of the original variable is replaced
  1323. // by the address of the new private variable in CodeGen. This new
  1324. // variable is not added to IdResolver, so the code in the OpenMP
  1325. // region uses original variable for proper diagnostics.
  1326. auto *VDPrivate = buildVarDecl(
  1327. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1328. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  1329. ActOnUninitializedDecl(VDPrivate);
  1330. if (VDPrivate->isInvalidDecl())
  1331. continue;
  1332. PrivateCopies.push_back(buildDeclRefExpr(
  1333. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1334. } else {
  1335. // The variable is also a firstprivate, so initialization sequence
  1336. // for private copy is generated already.
  1337. PrivateCopies.push_back(nullptr);
  1338. }
  1339. }
  1340. // Set initializers to private copies if no errors were found.
  1341. if (PrivateCopies.size() == Clause->varlist_size())
  1342. Clause->setPrivateCopies(PrivateCopies);
  1343. }
  1344. }
  1345. }
  1346. DSAStack->pop();
  1347. DiscardCleanupsInEvaluationContext();
  1348. PopExpressionEvaluationContext();
  1349. }
  1350. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1351. Expr *NumIterations, Sema &SemaRef,
  1352. Scope *S, DSAStackTy *Stack);
  1353. namespace {
  1354. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  1355. private:
  1356. Sema &SemaRef;
  1357. public:
  1358. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1359. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1360. NamedDecl *ND = Candidate.getCorrectionDecl();
  1361. if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1362. return VD->hasGlobalStorage() &&
  1363. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1364. SemaRef.getCurScope());
  1365. }
  1366. return false;
  1367. }
  1368. };
  1369. class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
  1370. private:
  1371. Sema &SemaRef;
  1372. public:
  1373. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1374. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1375. NamedDecl *ND = Candidate.getCorrectionDecl();
  1376. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  1377. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1378. SemaRef.getCurScope());
  1379. }
  1380. return false;
  1381. }
  1382. };
  1383. } // namespace
  1384. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1385. CXXScopeSpec &ScopeSpec,
  1386. const DeclarationNameInfo &Id) {
  1387. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1388. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1389. if (Lookup.isAmbiguous())
  1390. return ExprError();
  1391. VarDecl *VD;
  1392. if (!Lookup.isSingleResult()) {
  1393. if (TypoCorrection Corrected = CorrectTypo(
  1394. Id, LookupOrdinaryName, CurScope, nullptr,
  1395. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1396. diagnoseTypo(Corrected,
  1397. PDiag(Lookup.empty()
  1398. ? diag::err_undeclared_var_use_suggest
  1399. : diag::err_omp_expected_var_arg_suggest)
  1400. << Id.getName());
  1401. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1402. } else {
  1403. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1404. : diag::err_omp_expected_var_arg)
  1405. << Id.getName();
  1406. return ExprError();
  1407. }
  1408. } else {
  1409. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1410. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1411. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1412. return ExprError();
  1413. }
  1414. }
  1415. Lookup.suppressDiagnostics();
  1416. // OpenMP [2.9.2, Syntax, C/C++]
  1417. // Variables must be file-scope, namespace-scope, or static block-scope.
  1418. if (!VD->hasGlobalStorage()) {
  1419. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1420. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1421. bool IsDecl =
  1422. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1423. Diag(VD->getLocation(),
  1424. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1425. << VD;
  1426. return ExprError();
  1427. }
  1428. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1429. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1430. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1431. // A threadprivate directive for file-scope variables must appear outside
  1432. // any definition or declaration.
  1433. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1434. !getCurLexicalContext()->isTranslationUnit()) {
  1435. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1436. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1437. bool IsDecl =
  1438. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1439. Diag(VD->getLocation(),
  1440. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1441. << VD;
  1442. return ExprError();
  1443. }
  1444. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1445. // A threadprivate directive for static class member variables must appear
  1446. // in the class definition, in the same scope in which the member
  1447. // variables are declared.
  1448. if (CanonicalVD->isStaticDataMember() &&
  1449. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1450. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1451. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1452. bool IsDecl =
  1453. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1454. Diag(VD->getLocation(),
  1455. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1456. << VD;
  1457. return ExprError();
  1458. }
  1459. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1460. // A threadprivate directive for namespace-scope variables must appear
  1461. // outside any definition or declaration other than the namespace
  1462. // definition itself.
  1463. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1464. (!getCurLexicalContext()->isFileContext() ||
  1465. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1466. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1467. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1468. bool IsDecl =
  1469. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1470. Diag(VD->getLocation(),
  1471. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1472. << VD;
  1473. return ExprError();
  1474. }
  1475. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1476. // A threadprivate directive for static block-scope variables must appear
  1477. // in the scope of the variable and not in a nested scope.
  1478. if (CanonicalVD->isStaticLocal() && CurScope &&
  1479. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1480. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1481. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1482. bool IsDecl =
  1483. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1484. Diag(VD->getLocation(),
  1485. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1486. << VD;
  1487. return ExprError();
  1488. }
  1489. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1490. // A threadprivate directive must lexically precede all references to any
  1491. // of the variables in its list.
  1492. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1493. Diag(Id.getLoc(), diag::err_omp_var_used)
  1494. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1495. return ExprError();
  1496. }
  1497. QualType ExprType = VD->getType().getNonReferenceType();
  1498. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1499. SourceLocation(), VD,
  1500. /*RefersToEnclosingVariableOrCapture=*/false,
  1501. Id.getLoc(), ExprType, VK_LValue);
  1502. }
  1503. Sema::DeclGroupPtrTy
  1504. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1505. ArrayRef<Expr *> VarList) {
  1506. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1507. CurContext->addDecl(D);
  1508. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1509. }
  1510. return nullptr;
  1511. }
  1512. namespace {
  1513. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1514. Sema &SemaRef;
  1515. public:
  1516. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1517. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1518. if (VD->hasLocalStorage()) {
  1519. SemaRef.Diag(E->getLocStart(),
  1520. diag::err_omp_local_var_in_threadprivate_init)
  1521. << E->getSourceRange();
  1522. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1523. << VD << VD->getSourceRange();
  1524. return true;
  1525. }
  1526. }
  1527. return false;
  1528. }
  1529. bool VisitStmt(const Stmt *S) {
  1530. for (auto Child : S->children()) {
  1531. if (Child && Visit(Child))
  1532. return true;
  1533. }
  1534. return false;
  1535. }
  1536. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1537. };
  1538. } // namespace
  1539. OMPThreadPrivateDecl *
  1540. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1541. SmallVector<Expr *, 8> Vars;
  1542. for (auto &RefExpr : VarList) {
  1543. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1544. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1545. SourceLocation ILoc = DE->getExprLoc();
  1546. // Mark variable as used.
  1547. VD->setReferenced();
  1548. VD->markUsed(Context);
  1549. QualType QType = VD->getType();
  1550. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1551. // It will be analyzed later.
  1552. Vars.push_back(DE);
  1553. continue;
  1554. }
  1555. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1556. // A threadprivate variable must not have an incomplete type.
  1557. if (RequireCompleteType(ILoc, VD->getType(),
  1558. diag::err_omp_threadprivate_incomplete_type)) {
  1559. continue;
  1560. }
  1561. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1562. // A threadprivate variable must not have a reference type.
  1563. if (VD->getType()->isReferenceType()) {
  1564. Diag(ILoc, diag::err_omp_ref_type_arg)
  1565. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1566. bool IsDecl =
  1567. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1568. Diag(VD->getLocation(),
  1569. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1570. << VD;
  1571. continue;
  1572. }
  1573. // Check if this is a TLS variable. If TLS is not being supported, produce
  1574. // the corresponding diagnostic.
  1575. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1576. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1577. getLangOpts().OpenMPUseTLS &&
  1578. getASTContext().getTargetInfo().isTLSSupported())) ||
  1579. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1580. !VD->isLocalVarDecl())) {
  1581. Diag(ILoc, diag::err_omp_var_thread_local)
  1582. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1583. bool IsDecl =
  1584. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1585. Diag(VD->getLocation(),
  1586. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1587. << VD;
  1588. continue;
  1589. }
  1590. // Check if initial value of threadprivate variable reference variable with
  1591. // local storage (it is not supported by runtime).
  1592. if (auto Init = VD->getAnyInitializer()) {
  1593. LocalVarRefChecker Checker(*this);
  1594. if (Checker.Visit(Init))
  1595. continue;
  1596. }
  1597. Vars.push_back(RefExpr);
  1598. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1599. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1600. Context, SourceRange(Loc, Loc)));
  1601. if (auto *ML = Context.getASTMutationListener())
  1602. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1603. }
  1604. OMPThreadPrivateDecl *D = nullptr;
  1605. if (!Vars.empty()) {
  1606. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1607. Vars);
  1608. D->setAccess(AS_public);
  1609. }
  1610. return D;
  1611. }
  1612. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1613. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1614. bool IsLoopIterVar = false) {
  1615. if (DVar.RefExpr) {
  1616. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1617. << getOpenMPClauseName(DVar.CKind);
  1618. return;
  1619. }
  1620. enum {
  1621. PDSA_StaticMemberShared,
  1622. PDSA_StaticLocalVarShared,
  1623. PDSA_LoopIterVarPrivate,
  1624. PDSA_LoopIterVarLinear,
  1625. PDSA_LoopIterVarLastprivate,
  1626. PDSA_ConstVarShared,
  1627. PDSA_GlobalVarShared,
  1628. PDSA_TaskVarFirstprivate,
  1629. PDSA_LocalVarPrivate,
  1630. PDSA_Implicit
  1631. } Reason = PDSA_Implicit;
  1632. bool ReportHint = false;
  1633. auto ReportLoc = D->getLocation();
  1634. auto *VD = dyn_cast<VarDecl>(D);
  1635. if (IsLoopIterVar) {
  1636. if (DVar.CKind == OMPC_private)
  1637. Reason = PDSA_LoopIterVarPrivate;
  1638. else if (DVar.CKind == OMPC_lastprivate)
  1639. Reason = PDSA_LoopIterVarLastprivate;
  1640. else
  1641. Reason = PDSA_LoopIterVarLinear;
  1642. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  1643. DVar.CKind == OMPC_firstprivate) {
  1644. Reason = PDSA_TaskVarFirstprivate;
  1645. ReportLoc = DVar.ImplicitDSALoc;
  1646. } else if (VD && VD->isStaticLocal())
  1647. Reason = PDSA_StaticLocalVarShared;
  1648. else if (VD && VD->isStaticDataMember())
  1649. Reason = PDSA_StaticMemberShared;
  1650. else if (VD && VD->isFileVarDecl())
  1651. Reason = PDSA_GlobalVarShared;
  1652. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1653. Reason = PDSA_ConstVarShared;
  1654. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1655. ReportHint = true;
  1656. Reason = PDSA_LocalVarPrivate;
  1657. }
  1658. if (Reason != PDSA_Implicit) {
  1659. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1660. << Reason << ReportHint
  1661. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1662. } else if (DVar.ImplicitDSALoc.isValid()) {
  1663. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1664. << getOpenMPClauseName(DVar.CKind);
  1665. }
  1666. }
  1667. namespace {
  1668. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1669. DSAStackTy *Stack;
  1670. Sema &SemaRef;
  1671. bool ErrorFound;
  1672. CapturedStmt *CS;
  1673. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1674. llvm::SmallVector<Expr *, 8> ImplicitMap;
  1675. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1676. llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
  1677. public:
  1678. void VisitDeclRefExpr(DeclRefExpr *E) {
  1679. if (E->isTypeDependent() || E->isValueDependent() ||
  1680. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1681. return;
  1682. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1683. VD = VD->getCanonicalDecl();
  1684. // Skip internally declared variables.
  1685. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  1686. return;
  1687. auto DVar = Stack->getTopDSA(VD, false);
  1688. // Check if the variable has explicit DSA set and stop analysis if it so.
  1689. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  1690. return;
  1691. // Skip internally declared static variables.
  1692. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
  1693. return;
  1694. auto ELoc = E->getExprLoc();
  1695. auto DKind = Stack->getCurrentDirective();
  1696. // The default(none) clause requires that each variable that is referenced
  1697. // in the construct, and does not have a predetermined data-sharing
  1698. // attribute, must have its data-sharing attribute explicitly determined
  1699. // by being listed in a data-sharing attribute clause.
  1700. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1701. isParallelOrTaskRegion(DKind) &&
  1702. VarsWithInheritedDSA.count(VD) == 0) {
  1703. VarsWithInheritedDSA[VD] = E;
  1704. return;
  1705. }
  1706. if (isOpenMPTargetExecutionDirective(DKind) &&
  1707. !Stack->isLoopControlVariable(VD).first) {
  1708. if (!Stack->checkMappableExprComponentListsForDecl(
  1709. VD, /*CurrentRegionOnly=*/true,
  1710. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1711. StackComponents,
  1712. OpenMPClauseKind) {
  1713. // Variable is used if it has been marked as an array, array
  1714. // section or the variable iself.
  1715. return StackComponents.size() == 1 ||
  1716. std::all_of(
  1717. std::next(StackComponents.rbegin()),
  1718. StackComponents.rend(),
  1719. [](const OMPClauseMappableExprCommon::
  1720. MappableComponent &MC) {
  1721. return MC.getAssociatedDeclaration() ==
  1722. nullptr &&
  1723. (isa<OMPArraySectionExpr>(
  1724. MC.getAssociatedExpression()) ||
  1725. isa<ArraySubscriptExpr>(
  1726. MC.getAssociatedExpression()));
  1727. });
  1728. })) {
  1729. bool IsFirstprivate = false;
  1730. // By default lambdas are captured as firstprivates.
  1731. if (const auto *RD =
  1732. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  1733. IsFirstprivate = RD->isLambda();
  1734. IsFirstprivate =
  1735. IsFirstprivate ||
  1736. (VD->getType().getNonReferenceType()->isScalarType() &&
  1737. Stack->getDefaultDMA() != DMA_tofrom_scalar);
  1738. if (IsFirstprivate)
  1739. ImplicitFirstprivate.emplace_back(E);
  1740. else
  1741. ImplicitMap.emplace_back(E);
  1742. return;
  1743. }
  1744. }
  1745. // OpenMP [2.9.3.6, Restrictions, p.2]
  1746. // A list item that appears in a reduction clause of the innermost
  1747. // enclosing worksharing or parallel construct may not be accessed in an
  1748. // explicit task.
  1749. DVar = Stack->hasInnermostDSA(
  1750. VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1751. [](OpenMPDirectiveKind K) -> bool {
  1752. return isOpenMPParallelDirective(K) ||
  1753. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1754. },
  1755. /*FromParent=*/true);
  1756. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1757. ErrorFound = true;
  1758. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1759. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1760. return;
  1761. }
  1762. // Define implicit data-sharing attributes for task.
  1763. DVar = Stack->getImplicitDSA(VD, false);
  1764. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1765. !Stack->isLoopControlVariable(VD).first)
  1766. ImplicitFirstprivate.push_back(E);
  1767. }
  1768. }
  1769. void VisitMemberExpr(MemberExpr *E) {
  1770. if (E->isTypeDependent() || E->isValueDependent() ||
  1771. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  1772. return;
  1773. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  1774. if (!FD)
  1775. return;
  1776. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  1777. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1778. auto DVar = Stack->getTopDSA(FD, false);
  1779. // Check if the variable has explicit DSA set and stop analysis if it
  1780. // so.
  1781. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  1782. return;
  1783. if (isOpenMPTargetExecutionDirective(DKind) &&
  1784. !Stack->isLoopControlVariable(FD).first &&
  1785. !Stack->checkMappableExprComponentListsForDecl(
  1786. FD, /*CurrentRegionOnly=*/true,
  1787. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  1788. StackComponents,
  1789. OpenMPClauseKind) {
  1790. return isa<CXXThisExpr>(
  1791. cast<MemberExpr>(
  1792. StackComponents.back().getAssociatedExpression())
  1793. ->getBase()
  1794. ->IgnoreParens());
  1795. })) {
  1796. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  1797. // A bit-field cannot appear in a map clause.
  1798. //
  1799. if (FD->isBitField()) {
  1800. SemaRef.Diag(E->getMemberLoc(),
  1801. diag::err_omp_bit_fields_forbidden_in_clause)
  1802. << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
  1803. return;
  1804. }
  1805. ImplicitMap.emplace_back(E);
  1806. return;
  1807. }
  1808. auto ELoc = E->getExprLoc();
  1809. // OpenMP [2.9.3.6, Restrictions, p.2]
  1810. // A list item that appears in a reduction clause of the innermost
  1811. // enclosing worksharing or parallel construct may not be accessed in
  1812. // an explicit task.
  1813. DVar = Stack->hasInnermostDSA(
  1814. FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  1815. [](OpenMPDirectiveKind K) -> bool {
  1816. return isOpenMPParallelDirective(K) ||
  1817. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  1818. },
  1819. /*FromParent=*/true);
  1820. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  1821. ErrorFound = true;
  1822. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1823. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1824. return;
  1825. }
  1826. // Define implicit data-sharing attributes for task.
  1827. DVar = Stack->getImplicitDSA(FD, false);
  1828. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  1829. !Stack->isLoopControlVariable(FD).first)
  1830. ImplicitFirstprivate.push_back(E);
  1831. return;
  1832. }
  1833. if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
  1834. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  1835. CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
  1836. auto *VD = cast<ValueDecl>(
  1837. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  1838. if (!Stack->checkMappableExprComponentListsForDecl(
  1839. VD, /*CurrentRegionOnly=*/true,
  1840. [&CurComponents](
  1841. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1842. StackComponents,
  1843. OpenMPClauseKind) {
  1844. auto CCI = CurComponents.rbegin();
  1845. auto CCE = CurComponents.rend();
  1846. for (const auto &SC : llvm::reverse(StackComponents)) {
  1847. // Do both expressions have the same kind?
  1848. if (CCI->getAssociatedExpression()->getStmtClass() !=
  1849. SC.getAssociatedExpression()->getStmtClass())
  1850. if (!(isa<OMPArraySectionExpr>(
  1851. SC.getAssociatedExpression()) &&
  1852. isa<ArraySubscriptExpr>(
  1853. CCI->getAssociatedExpression())))
  1854. return false;
  1855. Decl *CCD = CCI->getAssociatedDeclaration();
  1856. Decl *SCD = SC.getAssociatedDeclaration();
  1857. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  1858. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  1859. if (SCD != CCD)
  1860. return false;
  1861. std::advance(CCI, 1);
  1862. if (CCI == CCE)
  1863. break;
  1864. }
  1865. return true;
  1866. })) {
  1867. Visit(E->getBase());
  1868. }
  1869. } else
  1870. Visit(E->getBase());
  1871. }
  1872. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1873. for (auto *C : S->clauses()) {
  1874. // Skip analysis of arguments of implicitly defined firstprivate clause
  1875. // for task|target directives.
  1876. // Skip analysis of arguments of implicitly defined map clause for target
  1877. // directives.
  1878. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  1879. C->isImplicit())) {
  1880. for (auto *CC : C->children()) {
  1881. if (CC)
  1882. Visit(CC);
  1883. }
  1884. }
  1885. }
  1886. }
  1887. void VisitStmt(Stmt *S) {
  1888. for (auto *C : S->children()) {
  1889. if (C && !isa<OMPExecutableDirective>(C))
  1890. Visit(C);
  1891. }
  1892. }
  1893. bool isErrorFound() { return ErrorFound; }
  1894. ArrayRef<Expr *> getImplicitFirstprivate() const {
  1895. return ImplicitFirstprivate;
  1896. }
  1897. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  1898. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1899. return VarsWithInheritedDSA;
  1900. }
  1901. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1902. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1903. };
  1904. } // namespace
  1905. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1906. switch (DKind) {
  1907. case OMPD_parallel:
  1908. case OMPD_parallel_for:
  1909. case OMPD_parallel_for_simd:
  1910. case OMPD_parallel_sections:
  1911. case OMPD_teams:
  1912. case OMPD_teams_distribute: {
  1913. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1914. QualType KmpInt32PtrTy =
  1915. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1916. Sema::CapturedParamNameType Params[] = {
  1917. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1918. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1919. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1920. };
  1921. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1922. Params);
  1923. break;
  1924. }
  1925. case OMPD_target_teams:
  1926. case OMPD_target_parallel: {
  1927. Sema::CapturedParamNameType ParamsTarget[] = {
  1928. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1929. };
  1930. // Start a captured region for 'target' with no implicit parameters.
  1931. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1932. ParamsTarget);
  1933. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1934. QualType KmpInt32PtrTy =
  1935. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1936. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  1937. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1938. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1939. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1940. };
  1941. // Start a captured region for 'teams' or 'parallel'. Both regions have
  1942. // the same implicit parameters.
  1943. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1944. ParamsTeamsOrParallel);
  1945. break;
  1946. }
  1947. case OMPD_simd:
  1948. case OMPD_for:
  1949. case OMPD_for_simd:
  1950. case OMPD_sections:
  1951. case OMPD_section:
  1952. case OMPD_single:
  1953. case OMPD_master:
  1954. case OMPD_critical:
  1955. case OMPD_taskgroup:
  1956. case OMPD_distribute:
  1957. case OMPD_ordered:
  1958. case OMPD_atomic:
  1959. case OMPD_target_data:
  1960. case OMPD_target:
  1961. case OMPD_target_parallel_for:
  1962. case OMPD_target_parallel_for_simd:
  1963. case OMPD_target_simd: {
  1964. Sema::CapturedParamNameType Params[] = {
  1965. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1966. };
  1967. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1968. Params);
  1969. break;
  1970. }
  1971. case OMPD_task: {
  1972. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1973. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1974. FunctionProtoType::ExtProtoInfo EPI;
  1975. EPI.Variadic = true;
  1976. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1977. Sema::CapturedParamNameType Params[] = {
  1978. std::make_pair(".global_tid.", KmpInt32Ty),
  1979. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  1980. std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
  1981. std::make_pair(".copy_fn.",
  1982. Context.getPointerType(CopyFnType).withConst()),
  1983. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  1984. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1985. };
  1986. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1987. Params);
  1988. // Mark this captured region as inlined, because we don't use outlined
  1989. // function directly.
  1990. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1991. AlwaysInlineAttr::CreateImplicit(
  1992. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1993. break;
  1994. }
  1995. case OMPD_taskloop:
  1996. case OMPD_taskloop_simd: {
  1997. QualType KmpInt32Ty =
  1998. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  1999. QualType KmpUInt64Ty =
  2000. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  2001. QualType KmpInt64Ty =
  2002. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  2003. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  2004. FunctionProtoType::ExtProtoInfo EPI;
  2005. EPI.Variadic = true;
  2006. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2007. Sema::CapturedParamNameType Params[] = {
  2008. std::make_pair(".global_tid.", KmpInt32Ty),
  2009. std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
  2010. std::make_pair(".privates.",
  2011. Context.VoidPtrTy.withConst().withRestrict()),
  2012. std::make_pair(
  2013. ".copy_fn.",
  2014. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2015. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2016. std::make_pair(".lb.", KmpUInt64Ty),
  2017. std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
  2018. std::make_pair(".liter.", KmpInt32Ty),
  2019. std::make_pair(".reductions.",
  2020. Context.VoidPtrTy.withConst().withRestrict()),
  2021. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2022. };
  2023. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2024. Params);
  2025. // Mark this captured region as inlined, because we don't use outlined
  2026. // function directly.
  2027. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2028. AlwaysInlineAttr::CreateImplicit(
  2029. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  2030. break;
  2031. }
  2032. case OMPD_distribute_parallel_for_simd:
  2033. case OMPD_distribute_simd:
  2034. case OMPD_distribute_parallel_for:
  2035. case OMPD_teams_distribute_simd:
  2036. case OMPD_teams_distribute_parallel_for_simd:
  2037. case OMPD_teams_distribute_parallel_for:
  2038. case OMPD_target_teams_distribute:
  2039. case OMPD_target_teams_distribute_parallel_for:
  2040. case OMPD_target_teams_distribute_parallel_for_simd:
  2041. case OMPD_target_teams_distribute_simd: {
  2042. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  2043. QualType KmpInt32PtrTy =
  2044. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2045. Sema::CapturedParamNameType Params[] = {
  2046. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2047. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2048. std::make_pair(".previous.lb.", Context.getSizeType()),
  2049. std::make_pair(".previous.ub.", Context.getSizeType()),
  2050. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2051. };
  2052. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2053. Params);
  2054. break;
  2055. }
  2056. case OMPD_threadprivate:
  2057. case OMPD_taskyield:
  2058. case OMPD_barrier:
  2059. case OMPD_taskwait:
  2060. case OMPD_cancellation_point:
  2061. case OMPD_cancel:
  2062. case OMPD_flush:
  2063. case OMPD_target_enter_data:
  2064. case OMPD_target_exit_data:
  2065. case OMPD_declare_reduction:
  2066. case OMPD_declare_simd:
  2067. case OMPD_declare_target:
  2068. case OMPD_end_declare_target:
  2069. case OMPD_target_update:
  2070. llvm_unreachable("OpenMP Directive is not allowed");
  2071. case OMPD_unknown:
  2072. llvm_unreachable("Unknown OpenMP directive");
  2073. }
  2074. }
  2075. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2076. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2077. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2078. return CaptureRegions.size();
  2079. }
  2080. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2081. Expr *CaptureExpr, bool WithInit,
  2082. bool AsExpression) {
  2083. assert(CaptureExpr);
  2084. ASTContext &C = S.getASTContext();
  2085. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2086. QualType Ty = Init->getType();
  2087. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2088. if (S.getLangOpts().CPlusPlus)
  2089. Ty = C.getLValueReferenceType(Ty);
  2090. else {
  2091. Ty = C.getPointerType(Ty);
  2092. ExprResult Res =
  2093. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2094. if (!Res.isUsable())
  2095. return nullptr;
  2096. Init = Res.get();
  2097. }
  2098. WithInit = true;
  2099. }
  2100. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2101. CaptureExpr->getLocStart());
  2102. if (!WithInit)
  2103. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
  2104. S.CurContext->addHiddenDecl(CED);
  2105. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2106. return CED;
  2107. }
  2108. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2109. bool WithInit) {
  2110. OMPCapturedExprDecl *CD;
  2111. if (auto *VD = S.IsOpenMPCapturedDecl(D))
  2112. CD = cast<OMPCapturedExprDecl>(VD);
  2113. else
  2114. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2115. /*AsExpression=*/false);
  2116. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2117. CaptureExpr->getExprLoc());
  2118. }
  2119. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2120. if (!Ref) {
  2121. auto *CD =
  2122. buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
  2123. CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
  2124. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2125. CaptureExpr->getExprLoc());
  2126. }
  2127. ExprResult Res = Ref;
  2128. if (!S.getLangOpts().CPlusPlus &&
  2129. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2130. Ref->getType()->isPointerType())
  2131. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2132. if (!Res.isUsable())
  2133. return ExprError();
  2134. return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
  2135. }
  2136. namespace {
  2137. // OpenMP directives parsed in this section are represented as a
  2138. // CapturedStatement with an associated statement. If a syntax error
  2139. // is detected during the parsing of the associated statement, the
  2140. // compiler must abort processing and close the CapturedStatement.
  2141. //
  2142. // Combined directives such as 'target parallel' have more than one
  2143. // nested CapturedStatements. This RAII ensures that we unwind out
  2144. // of all the nested CapturedStatements when an error is found.
  2145. class CaptureRegionUnwinderRAII {
  2146. private:
  2147. Sema &S;
  2148. bool &ErrorFound;
  2149. OpenMPDirectiveKind DKind;
  2150. public:
  2151. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2152. OpenMPDirectiveKind DKind)
  2153. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2154. ~CaptureRegionUnwinderRAII() {
  2155. if (ErrorFound) {
  2156. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2157. while (--ThisCaptureLevel >= 0)
  2158. S.ActOnCapturedRegionError();
  2159. }
  2160. }
  2161. };
  2162. } // namespace
  2163. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2164. ArrayRef<OMPClause *> Clauses) {
  2165. bool ErrorFound = false;
  2166. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2167. *this, ErrorFound, DSAStack->getCurrentDirective());
  2168. if (!S.isUsable()) {
  2169. ErrorFound = true;
  2170. return StmtError();
  2171. }
  2172. OMPOrderedClause *OC = nullptr;
  2173. OMPScheduleClause *SC = nullptr;
  2174. SmallVector<OMPLinearClause *, 4> LCs;
  2175. SmallVector<OMPClauseWithPreInit *, 8> PICs;
  2176. // This is required for proper codegen.
  2177. for (auto *Clause : Clauses) {
  2178. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2179. Clause->getClauseKind() == OMPC_in_reduction) {
  2180. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2181. // with the corresponding in_reduction items.
  2182. auto *IRC = cast<OMPInReductionClause>(Clause);
  2183. for (auto *E : IRC->taskgroup_descriptors())
  2184. if (E)
  2185. MarkDeclarationsReferencedInExpr(E);
  2186. }
  2187. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2188. Clause->getClauseKind() == OMPC_copyprivate ||
  2189. (getLangOpts().OpenMPUseTLS &&
  2190. getASTContext().getTargetInfo().isTLSSupported() &&
  2191. Clause->getClauseKind() == OMPC_copyin)) {
  2192. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2193. // Mark all variables in private list clauses as used in inner region.
  2194. for (auto *VarRef : Clause->children()) {
  2195. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2196. MarkDeclarationsReferencedInExpr(E);
  2197. }
  2198. }
  2199. DSAStack->setForceVarCapturing(/*V=*/false);
  2200. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  2201. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2202. PICs.push_back(C);
  2203. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2204. if (auto *E = C->getPostUpdateExpr())
  2205. MarkDeclarationsReferencedInExpr(E);
  2206. }
  2207. }
  2208. if (Clause->getClauseKind() == OMPC_schedule)
  2209. SC = cast<OMPScheduleClause>(Clause);
  2210. else if (Clause->getClauseKind() == OMPC_ordered)
  2211. OC = cast<OMPOrderedClause>(Clause);
  2212. else if (Clause->getClauseKind() == OMPC_linear)
  2213. LCs.push_back(cast<OMPLinearClause>(Clause));
  2214. }
  2215. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2216. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2217. // specified.
  2218. if (SC &&
  2219. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2220. SC->getSecondScheduleModifier() ==
  2221. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2222. OC) {
  2223. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2224. ? SC->getFirstScheduleModifierLoc()
  2225. : SC->getSecondScheduleModifierLoc(),
  2226. diag::err_omp_schedule_nonmonotonic_ordered)
  2227. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2228. ErrorFound = true;
  2229. }
  2230. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2231. for (auto *C : LCs) {
  2232. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  2233. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  2234. }
  2235. ErrorFound = true;
  2236. }
  2237. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2238. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2239. OC->getNumForLoops()) {
  2240. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  2241. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2242. ErrorFound = true;
  2243. }
  2244. if (ErrorFound) {
  2245. return StmtError();
  2246. }
  2247. StmtResult SR = S;
  2248. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2249. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2250. for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2251. // Mark all variables in private list clauses as used in inner region.
  2252. // Required for proper codegen of combined directives.
  2253. // TODO: add processing for other clauses.
  2254. if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  2255. for (auto *C : PICs) {
  2256. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2257. // Find the particular capture region for the clause if the
  2258. // directive is a combined one with multiple capture regions.
  2259. // If the directive is not a combined one, the capture region
  2260. // associated with the clause is OMPD_unknown and is generated
  2261. // only once.
  2262. if (CaptureRegion == ThisCaptureRegion ||
  2263. CaptureRegion == OMPD_unknown) {
  2264. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2265. for (auto *D : DS->decls())
  2266. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2267. }
  2268. }
  2269. }
  2270. }
  2271. SR = ActOnCapturedRegionEnd(SR.get());
  2272. }
  2273. return SR;
  2274. }
  2275. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2276. OpenMPDirectiveKind CancelRegion,
  2277. SourceLocation StartLoc) {
  2278. // CancelRegion is only needed for cancel and cancellation_point.
  2279. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2280. return false;
  2281. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2282. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2283. return false;
  2284. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2285. << getOpenMPDirectiveName(CancelRegion);
  2286. return true;
  2287. }
  2288. static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  2289. OpenMPDirectiveKind CurrentRegion,
  2290. const DeclarationNameInfo &CurrentName,
  2291. OpenMPDirectiveKind CancelRegion,
  2292. SourceLocation StartLoc) {
  2293. if (Stack->getCurScope()) {
  2294. auto ParentRegion = Stack->getParentDirective();
  2295. auto OffendingRegion = ParentRegion;
  2296. bool NestingProhibited = false;
  2297. bool CloseNesting = true;
  2298. bool OrphanSeen = false;
  2299. enum {
  2300. NoRecommend,
  2301. ShouldBeInParallelRegion,
  2302. ShouldBeInOrderedRegion,
  2303. ShouldBeInTargetRegion,
  2304. ShouldBeInTeamsRegion
  2305. } Recommend = NoRecommend;
  2306. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2307. // OpenMP [2.16, Nesting of Regions]
  2308. // OpenMP constructs may not be nested inside a simd region.
  2309. // OpenMP [2.8.1,simd Construct, Restrictions]
  2310. // An ordered construct with the simd clause is the only OpenMP
  2311. // construct that can appear in the simd region.
  2312. // Allowing a SIMD construct nested in another SIMD construct is an
  2313. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2314. // message.
  2315. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2316. ? diag::err_omp_prohibited_region_simd
  2317. : diag::warn_omp_nesting_simd);
  2318. return CurrentRegion != OMPD_simd;
  2319. }
  2320. if (ParentRegion == OMPD_atomic) {
  2321. // OpenMP [2.16, Nesting of Regions]
  2322. // OpenMP constructs may not be nested inside an atomic region.
  2323. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2324. return true;
  2325. }
  2326. if (CurrentRegion == OMPD_section) {
  2327. // OpenMP [2.7.2, sections Construct, Restrictions]
  2328. // Orphaned section directives are prohibited. That is, the section
  2329. // directives must appear within the sections construct and must not be
  2330. // encountered elsewhere in the sections region.
  2331. if (ParentRegion != OMPD_sections &&
  2332. ParentRegion != OMPD_parallel_sections) {
  2333. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2334. << (ParentRegion != OMPD_unknown)
  2335. << getOpenMPDirectiveName(ParentRegion);
  2336. return true;
  2337. }
  2338. return false;
  2339. }
  2340. // Allow some constructs (except teams) to be orphaned (they could be
  2341. // used in functions, called from OpenMP regions with the required
  2342. // preconditions).
  2343. if (ParentRegion == OMPD_unknown &&
  2344. !isOpenMPNestingTeamsDirective(CurrentRegion))
  2345. return false;
  2346. if (CurrentRegion == OMPD_cancellation_point ||
  2347. CurrentRegion == OMPD_cancel) {
  2348. // OpenMP [2.16, Nesting of Regions]
  2349. // A cancellation point construct for which construct-type-clause is
  2350. // taskgroup must be nested inside a task construct. A cancellation
  2351. // point construct for which construct-type-clause is not taskgroup must
  2352. // be closely nested inside an OpenMP construct that matches the type
  2353. // specified in construct-type-clause.
  2354. // A cancel construct for which construct-type-clause is taskgroup must be
  2355. // nested inside a task construct. A cancel construct for which
  2356. // construct-type-clause is not taskgroup must be closely nested inside an
  2357. // OpenMP construct that matches the type specified in
  2358. // construct-type-clause.
  2359. NestingProhibited =
  2360. !((CancelRegion == OMPD_parallel &&
  2361. (ParentRegion == OMPD_parallel ||
  2362. ParentRegion == OMPD_target_parallel)) ||
  2363. (CancelRegion == OMPD_for &&
  2364. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2365. ParentRegion == OMPD_target_parallel_for)) ||
  2366. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2367. (CancelRegion == OMPD_sections &&
  2368. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2369. ParentRegion == OMPD_parallel_sections)));
  2370. } else if (CurrentRegion == OMPD_master) {
  2371. // OpenMP [2.16, Nesting of Regions]
  2372. // A master region may not be closely nested inside a worksharing,
  2373. // atomic, or explicit task region.
  2374. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2375. isOpenMPTaskingDirective(ParentRegion);
  2376. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2377. // OpenMP [2.16, Nesting of Regions]
  2378. // A critical region may not be nested (closely or otherwise) inside a
  2379. // critical region with the same name. Note that this restriction is not
  2380. // sufficient to prevent deadlock.
  2381. SourceLocation PreviousCriticalLoc;
  2382. bool DeadLock = Stack->hasDirective(
  2383. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2384. const DeclarationNameInfo &DNI,
  2385. SourceLocation Loc) -> bool {
  2386. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2387. PreviousCriticalLoc = Loc;
  2388. return true;
  2389. } else
  2390. return false;
  2391. },
  2392. false /* skip top directive */);
  2393. if (DeadLock) {
  2394. SemaRef.Diag(StartLoc,
  2395. diag::err_omp_prohibited_region_critical_same_name)
  2396. << CurrentName.getName();
  2397. if (PreviousCriticalLoc.isValid())
  2398. SemaRef.Diag(PreviousCriticalLoc,
  2399. diag::note_omp_previous_critical_region);
  2400. return true;
  2401. }
  2402. } else if (CurrentRegion == OMPD_barrier) {
  2403. // OpenMP [2.16, Nesting of Regions]
  2404. // A barrier region may not be closely nested inside a worksharing,
  2405. // explicit task, critical, ordered, atomic, or master region.
  2406. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2407. isOpenMPTaskingDirective(ParentRegion) ||
  2408. ParentRegion == OMPD_master ||
  2409. ParentRegion == OMPD_critical ||
  2410. ParentRegion == OMPD_ordered;
  2411. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2412. !isOpenMPParallelDirective(CurrentRegion) &&
  2413. !isOpenMPTeamsDirective(CurrentRegion)) {
  2414. // OpenMP [2.16, Nesting of Regions]
  2415. // A worksharing region may not be closely nested inside a worksharing,
  2416. // explicit task, critical, ordered, atomic, or master region.
  2417. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2418. isOpenMPTaskingDirective(ParentRegion) ||
  2419. ParentRegion == OMPD_master ||
  2420. ParentRegion == OMPD_critical ||
  2421. ParentRegion == OMPD_ordered;
  2422. Recommend = ShouldBeInParallelRegion;
  2423. } else if (CurrentRegion == OMPD_ordered) {
  2424. // OpenMP [2.16, Nesting of Regions]
  2425. // An ordered region may not be closely nested inside a critical,
  2426. // atomic, or explicit task region.
  2427. // An ordered region must be closely nested inside a loop region (or
  2428. // parallel loop region) with an ordered clause.
  2429. // OpenMP [2.8.1,simd Construct, Restrictions]
  2430. // An ordered construct with the simd clause is the only OpenMP construct
  2431. // that can appear in the simd region.
  2432. NestingProhibited = ParentRegion == OMPD_critical ||
  2433. isOpenMPTaskingDirective(ParentRegion) ||
  2434. !(isOpenMPSimdDirective(ParentRegion) ||
  2435. Stack->isParentOrderedRegion());
  2436. Recommend = ShouldBeInOrderedRegion;
  2437. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  2438. // OpenMP [2.16, Nesting of Regions]
  2439. // If specified, a teams construct must be contained within a target
  2440. // construct.
  2441. NestingProhibited = ParentRegion != OMPD_target;
  2442. OrphanSeen = ParentRegion == OMPD_unknown;
  2443. Recommend = ShouldBeInTargetRegion;
  2444. Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
  2445. }
  2446. if (!NestingProhibited &&
  2447. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  2448. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  2449. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  2450. // OpenMP [2.16, Nesting of Regions]
  2451. // distribute, parallel, parallel sections, parallel workshare, and the
  2452. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2453. // constructs that can be closely nested in the teams region.
  2454. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2455. !isOpenMPDistributeDirective(CurrentRegion);
  2456. Recommend = ShouldBeInParallelRegion;
  2457. }
  2458. if (!NestingProhibited &&
  2459. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  2460. // OpenMP 4.5 [2.17 Nesting of Regions]
  2461. // The region associated with the distribute construct must be strictly
  2462. // nested inside a teams region
  2463. NestingProhibited =
  2464. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  2465. Recommend = ShouldBeInTeamsRegion;
  2466. }
  2467. if (!NestingProhibited &&
  2468. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2469. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2470. // OpenMP 4.5 [2.17 Nesting of Regions]
  2471. // If a target, target update, target data, target enter data, or
  2472. // target exit data construct is encountered during execution of a
  2473. // target region, the behavior is unspecified.
  2474. NestingProhibited = Stack->hasDirective(
  2475. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2476. SourceLocation) -> bool {
  2477. if (isOpenMPTargetExecutionDirective(K)) {
  2478. OffendingRegion = K;
  2479. return true;
  2480. } else
  2481. return false;
  2482. },
  2483. false /* don't skip top directive */);
  2484. CloseNesting = false;
  2485. }
  2486. if (NestingProhibited) {
  2487. if (OrphanSeen) {
  2488. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  2489. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  2490. } else {
  2491. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2492. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2493. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2494. }
  2495. return true;
  2496. }
  2497. }
  2498. return false;
  2499. }
  2500. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2501. ArrayRef<OMPClause *> Clauses,
  2502. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2503. bool ErrorFound = false;
  2504. unsigned NamedModifiersNumber = 0;
  2505. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2506. OMPD_unknown + 1);
  2507. SmallVector<SourceLocation, 4> NameModifierLoc;
  2508. for (const auto *C : Clauses) {
  2509. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2510. // At most one if clause without a directive-name-modifier can appear on
  2511. // the directive.
  2512. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2513. if (FoundNameModifiers[CurNM]) {
  2514. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2515. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2516. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2517. ErrorFound = true;
  2518. } else if (CurNM != OMPD_unknown) {
  2519. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2520. ++NamedModifiersNumber;
  2521. }
  2522. FoundNameModifiers[CurNM] = IC;
  2523. if (CurNM == OMPD_unknown)
  2524. continue;
  2525. // Check if the specified name modifier is allowed for the current
  2526. // directive.
  2527. // At most one if clause with the particular directive-name-modifier can
  2528. // appear on the directive.
  2529. bool MatchFound = false;
  2530. for (auto NM : AllowedNameModifiers) {
  2531. if (CurNM == NM) {
  2532. MatchFound = true;
  2533. break;
  2534. }
  2535. }
  2536. if (!MatchFound) {
  2537. S.Diag(IC->getNameModifierLoc(),
  2538. diag::err_omp_wrong_if_directive_name_modifier)
  2539. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2540. ErrorFound = true;
  2541. }
  2542. }
  2543. }
  2544. // If any if clause on the directive includes a directive-name-modifier then
  2545. // all if clauses on the directive must include a directive-name-modifier.
  2546. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2547. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2548. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2549. diag::err_omp_no_more_if_clause);
  2550. } else {
  2551. std::string Values;
  2552. std::string Sep(", ");
  2553. unsigned AllowedCnt = 0;
  2554. unsigned TotalAllowedNum =
  2555. AllowedNameModifiers.size() - NamedModifiersNumber;
  2556. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2557. ++Cnt) {
  2558. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2559. if (!FoundNameModifiers[NM]) {
  2560. Values += "'";
  2561. Values += getOpenMPDirectiveName(NM);
  2562. Values += "'";
  2563. if (AllowedCnt + 2 == TotalAllowedNum)
  2564. Values += " or ";
  2565. else if (AllowedCnt + 1 != TotalAllowedNum)
  2566. Values += Sep;
  2567. ++AllowedCnt;
  2568. }
  2569. }
  2570. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2571. diag::err_omp_unnamed_if_clause)
  2572. << (TotalAllowedNum > 1) << Values;
  2573. }
  2574. for (auto Loc : NameModifierLoc) {
  2575. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2576. }
  2577. ErrorFound = true;
  2578. }
  2579. return ErrorFound;
  2580. }
  2581. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2582. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2583. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2584. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2585. StmtResult Res = StmtError();
  2586. // First check CancelRegion which is then used in checkNestingOfRegions.
  2587. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  2588. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2589. StartLoc))
  2590. return StmtError();
  2591. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2592. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2593. bool ErrorFound = false;
  2594. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2595. if (AStmt && !CurContext->isDependentContext()) {
  2596. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2597. // Check default data sharing attributes for referenced variables.
  2598. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2599. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  2600. Stmt *S = AStmt;
  2601. while (--ThisCaptureLevel >= 0)
  2602. S = cast<CapturedStmt>(S)->getCapturedStmt();
  2603. DSAChecker.Visit(S);
  2604. if (DSAChecker.isErrorFound())
  2605. return StmtError();
  2606. // Generate list of implicitly defined firstprivate variables.
  2607. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2608. SmallVector<Expr *, 4> ImplicitFirstprivates(
  2609. DSAChecker.getImplicitFirstprivate().begin(),
  2610. DSAChecker.getImplicitFirstprivate().end());
  2611. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  2612. DSAChecker.getImplicitMap().end());
  2613. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  2614. for (auto *C : Clauses) {
  2615. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  2616. for (auto *E : IRC->taskgroup_descriptors())
  2617. if (E)
  2618. ImplicitFirstprivates.emplace_back(E);
  2619. }
  2620. }
  2621. if (!ImplicitFirstprivates.empty()) {
  2622. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2623. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  2624. SourceLocation())) {
  2625. ClausesWithImplicit.push_back(Implicit);
  2626. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2627. ImplicitFirstprivates.size();
  2628. } else
  2629. ErrorFound = true;
  2630. }
  2631. if (!ImplicitMaps.empty()) {
  2632. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  2633. OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
  2634. SourceLocation(), SourceLocation(), ImplicitMaps,
  2635. SourceLocation(), SourceLocation(), SourceLocation())) {
  2636. ClausesWithImplicit.emplace_back(Implicit);
  2637. ErrorFound |=
  2638. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  2639. } else
  2640. ErrorFound = true;
  2641. }
  2642. }
  2643. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2644. switch (Kind) {
  2645. case OMPD_parallel:
  2646. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2647. EndLoc);
  2648. AllowedNameModifiers.push_back(OMPD_parallel);
  2649. break;
  2650. case OMPD_simd:
  2651. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2652. VarsWithInheritedDSA);
  2653. break;
  2654. case OMPD_for:
  2655. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2656. VarsWithInheritedDSA);
  2657. break;
  2658. case OMPD_for_simd:
  2659. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2660. EndLoc, VarsWithInheritedDSA);
  2661. break;
  2662. case OMPD_sections:
  2663. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2664. EndLoc);
  2665. break;
  2666. case OMPD_section:
  2667. assert(ClausesWithImplicit.empty() &&
  2668. "No clauses are allowed for 'omp section' directive");
  2669. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2670. break;
  2671. case OMPD_single:
  2672. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2673. EndLoc);
  2674. break;
  2675. case OMPD_master:
  2676. assert(ClausesWithImplicit.empty() &&
  2677. "No clauses are allowed for 'omp master' directive");
  2678. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2679. break;
  2680. case OMPD_critical:
  2681. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2682. StartLoc, EndLoc);
  2683. break;
  2684. case OMPD_parallel_for:
  2685. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2686. EndLoc, VarsWithInheritedDSA);
  2687. AllowedNameModifiers.push_back(OMPD_parallel);
  2688. break;
  2689. case OMPD_parallel_for_simd:
  2690. Res = ActOnOpenMPParallelForSimdDirective(
  2691. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2692. AllowedNameModifiers.push_back(OMPD_parallel);
  2693. break;
  2694. case OMPD_parallel_sections:
  2695. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2696. StartLoc, EndLoc);
  2697. AllowedNameModifiers.push_back(OMPD_parallel);
  2698. break;
  2699. case OMPD_task:
  2700. Res =
  2701. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2702. AllowedNameModifiers.push_back(OMPD_task);
  2703. break;
  2704. case OMPD_taskyield:
  2705. assert(ClausesWithImplicit.empty() &&
  2706. "No clauses are allowed for 'omp taskyield' directive");
  2707. assert(AStmt == nullptr &&
  2708. "No associated statement allowed for 'omp taskyield' directive");
  2709. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2710. break;
  2711. case OMPD_barrier:
  2712. assert(ClausesWithImplicit.empty() &&
  2713. "No clauses are allowed for 'omp barrier' directive");
  2714. assert(AStmt == nullptr &&
  2715. "No associated statement allowed for 'omp barrier' directive");
  2716. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2717. break;
  2718. case OMPD_taskwait:
  2719. assert(ClausesWithImplicit.empty() &&
  2720. "No clauses are allowed for 'omp taskwait' directive");
  2721. assert(AStmt == nullptr &&
  2722. "No associated statement allowed for 'omp taskwait' directive");
  2723. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2724. break;
  2725. case OMPD_taskgroup:
  2726. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  2727. EndLoc);
  2728. break;
  2729. case OMPD_flush:
  2730. assert(AStmt == nullptr &&
  2731. "No associated statement allowed for 'omp flush' directive");
  2732. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2733. break;
  2734. case OMPD_ordered:
  2735. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2736. EndLoc);
  2737. break;
  2738. case OMPD_atomic:
  2739. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2740. EndLoc);
  2741. break;
  2742. case OMPD_teams:
  2743. Res =
  2744. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2745. break;
  2746. case OMPD_target:
  2747. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2748. EndLoc);
  2749. AllowedNameModifiers.push_back(OMPD_target);
  2750. break;
  2751. case OMPD_target_parallel:
  2752. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2753. StartLoc, EndLoc);
  2754. AllowedNameModifiers.push_back(OMPD_target);
  2755. AllowedNameModifiers.push_back(OMPD_parallel);
  2756. break;
  2757. case OMPD_target_parallel_for:
  2758. Res = ActOnOpenMPTargetParallelForDirective(
  2759. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2760. AllowedNameModifiers.push_back(OMPD_target);
  2761. AllowedNameModifiers.push_back(OMPD_parallel);
  2762. break;
  2763. case OMPD_cancellation_point:
  2764. assert(ClausesWithImplicit.empty() &&
  2765. "No clauses are allowed for 'omp cancellation point' directive");
  2766. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2767. "cancellation point' directive");
  2768. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2769. break;
  2770. case OMPD_cancel:
  2771. assert(AStmt == nullptr &&
  2772. "No associated statement allowed for 'omp cancel' directive");
  2773. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2774. CancelRegion);
  2775. AllowedNameModifiers.push_back(OMPD_cancel);
  2776. break;
  2777. case OMPD_target_data:
  2778. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2779. EndLoc);
  2780. AllowedNameModifiers.push_back(OMPD_target_data);
  2781. break;
  2782. case OMPD_target_enter_data:
  2783. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2784. EndLoc);
  2785. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2786. break;
  2787. case OMPD_target_exit_data:
  2788. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2789. EndLoc);
  2790. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2791. break;
  2792. case OMPD_taskloop:
  2793. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2794. EndLoc, VarsWithInheritedDSA);
  2795. AllowedNameModifiers.push_back(OMPD_taskloop);
  2796. break;
  2797. case OMPD_taskloop_simd:
  2798. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2799. EndLoc, VarsWithInheritedDSA);
  2800. AllowedNameModifiers.push_back(OMPD_taskloop);
  2801. break;
  2802. case OMPD_distribute:
  2803. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2804. EndLoc, VarsWithInheritedDSA);
  2805. break;
  2806. case OMPD_target_update:
  2807. assert(!AStmt && "Statement is not allowed for target update");
  2808. Res =
  2809. ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2810. AllowedNameModifiers.push_back(OMPD_target_update);
  2811. break;
  2812. case OMPD_distribute_parallel_for:
  2813. Res = ActOnOpenMPDistributeParallelForDirective(
  2814. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2815. AllowedNameModifiers.push_back(OMPD_parallel);
  2816. break;
  2817. case OMPD_distribute_parallel_for_simd:
  2818. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  2819. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2820. AllowedNameModifiers.push_back(OMPD_parallel);
  2821. break;
  2822. case OMPD_distribute_simd:
  2823. Res = ActOnOpenMPDistributeSimdDirective(
  2824. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2825. break;
  2826. case OMPD_target_parallel_for_simd:
  2827. Res = ActOnOpenMPTargetParallelForSimdDirective(
  2828. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2829. AllowedNameModifiers.push_back(OMPD_target);
  2830. AllowedNameModifiers.push_back(OMPD_parallel);
  2831. break;
  2832. case OMPD_target_simd:
  2833. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2834. EndLoc, VarsWithInheritedDSA);
  2835. AllowedNameModifiers.push_back(OMPD_target);
  2836. break;
  2837. case OMPD_teams_distribute:
  2838. Res = ActOnOpenMPTeamsDistributeDirective(
  2839. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2840. break;
  2841. case OMPD_teams_distribute_simd:
  2842. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  2843. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2844. break;
  2845. case OMPD_teams_distribute_parallel_for_simd:
  2846. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  2847. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2848. AllowedNameModifiers.push_back(OMPD_parallel);
  2849. break;
  2850. case OMPD_teams_distribute_parallel_for:
  2851. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  2852. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2853. AllowedNameModifiers.push_back(OMPD_parallel);
  2854. break;
  2855. case OMPD_target_teams:
  2856. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2857. EndLoc);
  2858. AllowedNameModifiers.push_back(OMPD_target);
  2859. break;
  2860. case OMPD_target_teams_distribute:
  2861. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  2862. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2863. AllowedNameModifiers.push_back(OMPD_target);
  2864. break;
  2865. case OMPD_target_teams_distribute_parallel_for:
  2866. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  2867. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2868. AllowedNameModifiers.push_back(OMPD_target);
  2869. AllowedNameModifiers.push_back(OMPD_parallel);
  2870. break;
  2871. case OMPD_target_teams_distribute_parallel_for_simd:
  2872. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  2873. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2874. AllowedNameModifiers.push_back(OMPD_target);
  2875. AllowedNameModifiers.push_back(OMPD_parallel);
  2876. break;
  2877. case OMPD_target_teams_distribute_simd:
  2878. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  2879. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2880. AllowedNameModifiers.push_back(OMPD_target);
  2881. break;
  2882. case OMPD_declare_target:
  2883. case OMPD_end_declare_target:
  2884. case OMPD_threadprivate:
  2885. case OMPD_declare_reduction:
  2886. case OMPD_declare_simd:
  2887. llvm_unreachable("OpenMP Directive is not allowed");
  2888. case OMPD_unknown:
  2889. llvm_unreachable("Unknown OpenMP directive");
  2890. }
  2891. for (auto P : VarsWithInheritedDSA) {
  2892. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2893. << P.first << P.second->getSourceRange();
  2894. }
  2895. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2896. if (!AllowedNameModifiers.empty())
  2897. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2898. ErrorFound;
  2899. if (ErrorFound)
  2900. return StmtError();
  2901. return Res;
  2902. }
  2903. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  2904. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  2905. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  2906. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  2907. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  2908. assert(Aligneds.size() == Alignments.size());
  2909. assert(Linears.size() == LinModifiers.size());
  2910. assert(Linears.size() == Steps.size());
  2911. if (!DG || DG.get().isNull())
  2912. return DeclGroupPtrTy();
  2913. if (!DG.get().isSingleDecl()) {
  2914. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  2915. return DG;
  2916. }
  2917. auto *ADecl = DG.get().getSingleDecl();
  2918. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  2919. ADecl = FTD->getTemplatedDecl();
  2920. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  2921. if (!FD) {
  2922. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  2923. return DeclGroupPtrTy();
  2924. }
  2925. // OpenMP [2.8.2, declare simd construct, Description]
  2926. // The parameter of the simdlen clause must be a constant positive integer
  2927. // expression.
  2928. ExprResult SL;
  2929. if (Simdlen)
  2930. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  2931. // OpenMP [2.8.2, declare simd construct, Description]
  2932. // The special this pointer can be used as if was one of the arguments to the
  2933. // function in any of the linear, aligned, or uniform clauses.
  2934. // The uniform clause declares one or more arguments to have an invariant
  2935. // value for all concurrent invocations of the function in the execution of a
  2936. // single SIMD loop.
  2937. llvm::DenseMap<Decl *, Expr *> UniformedArgs;
  2938. Expr *UniformedLinearThis = nullptr;
  2939. for (auto *E : Uniforms) {
  2940. E = E->IgnoreParenImpCasts();
  2941. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  2942. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  2943. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  2944. FD->getParamDecl(PVD->getFunctionScopeIndex())
  2945. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  2946. UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
  2947. continue;
  2948. }
  2949. if (isa<CXXThisExpr>(E)) {
  2950. UniformedLinearThis = E;
  2951. continue;
  2952. }
  2953. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  2954. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  2955. }
  2956. // OpenMP [2.8.2, declare simd construct, Description]
  2957. // The aligned clause declares that the object to which each list item points
  2958. // is aligned to the number of bytes expressed in the optional parameter of
  2959. // the aligned clause.
  2960. // The special this pointer can be used as if was one of the arguments to the
  2961. // function in any of the linear, aligned, or uniform clauses.
  2962. // The type of list items appearing in the aligned clause must be array,
  2963. // pointer, reference to array, or reference to pointer.
  2964. llvm::DenseMap<Decl *, Expr *> AlignedArgs;
  2965. Expr *AlignedThis = nullptr;
  2966. for (auto *E : Aligneds) {
  2967. E = E->IgnoreParenImpCasts();
  2968. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  2969. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  2970. auto *CanonPVD = PVD->getCanonicalDecl();
  2971. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  2972. FD->getParamDecl(PVD->getFunctionScopeIndex())
  2973. ->getCanonicalDecl() == CanonPVD) {
  2974. // OpenMP [2.8.1, simd construct, Restrictions]
  2975. // A list-item cannot appear in more than one aligned clause.
  2976. if (AlignedArgs.count(CanonPVD) > 0) {
  2977. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  2978. << 1 << E->getSourceRange();
  2979. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  2980. diag::note_omp_explicit_dsa)
  2981. << getOpenMPClauseName(OMPC_aligned);
  2982. continue;
  2983. }
  2984. AlignedArgs[CanonPVD] = E;
  2985. QualType QTy = PVD->getType()
  2986. .getNonReferenceType()
  2987. .getUnqualifiedType()
  2988. .getCanonicalType();
  2989. const Type *Ty = QTy.getTypePtrOrNull();
  2990. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  2991. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  2992. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  2993. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  2994. }
  2995. continue;
  2996. }
  2997. }
  2998. if (isa<CXXThisExpr>(E)) {
  2999. if (AlignedThis) {
  3000. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3001. << 2 << E->getSourceRange();
  3002. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3003. << getOpenMPClauseName(OMPC_aligned);
  3004. }
  3005. AlignedThis = 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. // The optional parameter of the aligned clause, alignment, must be a constant
  3012. // positive integer expression. If no optional parameter is specified,
  3013. // implementation-defined default alignments for SIMD instructions on the
  3014. // target platforms are assumed.
  3015. SmallVector<Expr *, 4> NewAligns;
  3016. for (auto *E : Alignments) {
  3017. ExprResult Align;
  3018. if (E)
  3019. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3020. NewAligns.push_back(Align.get());
  3021. }
  3022. // OpenMP [2.8.2, declare simd construct, Description]
  3023. // The linear clause declares one or more list items to be private to a SIMD
  3024. // lane and to have a linear relationship with respect to the iteration space
  3025. // of a loop.
  3026. // The special this pointer can be used as if was one of the arguments to the
  3027. // function in any of the linear, aligned, or uniform clauses.
  3028. // When a linear-step expression is specified in a linear clause it must be
  3029. // either a constant integer expression or an integer-typed parameter that is
  3030. // specified in a uniform clause on the directive.
  3031. llvm::DenseMap<Decl *, Expr *> LinearArgs;
  3032. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3033. auto MI = LinModifiers.begin();
  3034. for (auto *E : Linears) {
  3035. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3036. ++MI;
  3037. E = E->IgnoreParenImpCasts();
  3038. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  3039. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3040. auto *CanonPVD = PVD->getCanonicalDecl();
  3041. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3042. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3043. ->getCanonicalDecl() == CanonPVD) {
  3044. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3045. // A list-item cannot appear in more than one linear clause.
  3046. if (LinearArgs.count(CanonPVD) > 0) {
  3047. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3048. << getOpenMPClauseName(OMPC_linear)
  3049. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3050. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3051. diag::note_omp_explicit_dsa)
  3052. << getOpenMPClauseName(OMPC_linear);
  3053. continue;
  3054. }
  3055. // Each argument can appear in at most one uniform or linear clause.
  3056. if (UniformedArgs.count(CanonPVD) > 0) {
  3057. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3058. << getOpenMPClauseName(OMPC_linear)
  3059. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3060. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3061. diag::note_omp_explicit_dsa)
  3062. << getOpenMPClauseName(OMPC_uniform);
  3063. continue;
  3064. }
  3065. LinearArgs[CanonPVD] = E;
  3066. if (E->isValueDependent() || E->isTypeDependent() ||
  3067. E->isInstantiationDependent() ||
  3068. E->containsUnexpandedParameterPack())
  3069. continue;
  3070. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3071. PVD->getOriginalType());
  3072. continue;
  3073. }
  3074. }
  3075. if (isa<CXXThisExpr>(E)) {
  3076. if (UniformedLinearThis) {
  3077. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3078. << getOpenMPClauseName(OMPC_linear)
  3079. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3080. << E->getSourceRange();
  3081. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3082. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3083. : OMPC_linear);
  3084. continue;
  3085. }
  3086. UniformedLinearThis = E;
  3087. if (E->isValueDependent() || E->isTypeDependent() ||
  3088. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3089. continue;
  3090. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3091. E->getType());
  3092. continue;
  3093. }
  3094. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3095. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3096. }
  3097. Expr *Step = nullptr;
  3098. Expr *NewStep = nullptr;
  3099. SmallVector<Expr *, 4> NewSteps;
  3100. for (auto *E : Steps) {
  3101. // Skip the same step expression, it was checked already.
  3102. if (Step == E || !E) {
  3103. NewSteps.push_back(E ? NewStep : nullptr);
  3104. continue;
  3105. }
  3106. Step = E;
  3107. if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3108. if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3109. auto *CanonPVD = PVD->getCanonicalDecl();
  3110. if (UniformedArgs.count(CanonPVD) == 0) {
  3111. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3112. << Step->getSourceRange();
  3113. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3114. E->isInstantiationDependent() ||
  3115. E->containsUnexpandedParameterPack() ||
  3116. CanonPVD->getType()->hasIntegerRepresentation())
  3117. NewSteps.push_back(Step);
  3118. else {
  3119. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3120. << Step->getSourceRange();
  3121. }
  3122. continue;
  3123. }
  3124. NewStep = Step;
  3125. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3126. !Step->isInstantiationDependent() &&
  3127. !Step->containsUnexpandedParameterPack()) {
  3128. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3129. .get();
  3130. if (NewStep)
  3131. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3132. }
  3133. NewSteps.push_back(NewStep);
  3134. }
  3135. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3136. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3137. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3138. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3139. const_cast<Expr **>(Linears.data()), Linears.size(),
  3140. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3141. NewSteps.data(), NewSteps.size(), SR);
  3142. ADecl->addAttr(NewAttr);
  3143. return ConvertDeclToDeclGroup(ADecl);
  3144. }
  3145. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3146. Stmt *AStmt,
  3147. SourceLocation StartLoc,
  3148. SourceLocation EndLoc) {
  3149. if (!AStmt)
  3150. return StmtError();
  3151. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  3152. // 1.2.2 OpenMP Language Terminology
  3153. // Structured block - An executable statement with a single entry at the
  3154. // top and a single exit at the bottom.
  3155. // The point of exit cannot be a branch out of the structured block.
  3156. // longjmp() and throw() must not violate the entry/exit criteria.
  3157. CS->getCapturedDecl()->setNothrow();
  3158. getCurFunction()->setHasBranchProtectedScope();
  3159. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3160. DSAStack->isCancelRegion());
  3161. }
  3162. namespace {
  3163. /// \brief Helper class for checking canonical form of the OpenMP loops and
  3164. /// extracting iteration space of each loop in the loop nest, that will be used
  3165. /// for IR generation.
  3166. class OpenMPIterationSpaceChecker {
  3167. /// \brief Reference to Sema.
  3168. Sema &SemaRef;
  3169. /// \brief A location for diagnostics (when there is no some better location).
  3170. SourceLocation DefaultLoc;
  3171. /// \brief A location for diagnostics (when increment is not compatible).
  3172. SourceLocation ConditionLoc;
  3173. /// \brief A source location for referring to loop init later.
  3174. SourceRange InitSrcRange;
  3175. /// \brief A source location for referring to condition later.
  3176. SourceRange ConditionSrcRange;
  3177. /// \brief A source location for referring to increment later.
  3178. SourceRange IncrementSrcRange;
  3179. /// \brief Loop variable.
  3180. ValueDecl *LCDecl = nullptr;
  3181. /// \brief Reference to loop variable.
  3182. Expr *LCRef = nullptr;
  3183. /// \brief Lower bound (initializer for the var).
  3184. Expr *LB = nullptr;
  3185. /// \brief Upper bound.
  3186. Expr *UB = nullptr;
  3187. /// \brief Loop step (increment).
  3188. Expr *Step = nullptr;
  3189. /// \brief This flag is true when condition is one of:
  3190. /// Var < UB
  3191. /// Var <= UB
  3192. /// UB > Var
  3193. /// UB >= Var
  3194. bool TestIsLessOp = false;
  3195. /// \brief This flag is true when condition is strict ( < or > ).
  3196. bool TestIsStrictOp = false;
  3197. /// \brief This flag is true when step is subtracted on each iteration.
  3198. bool SubtractStep = false;
  3199. public:
  3200. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3201. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3202. /// \brief Check init-expr for canonical loop form and save loop counter
  3203. /// variable - #Var and its initialization value - #LB.
  3204. bool CheckInit(Stmt *S, bool EmitDiags = true);
  3205. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  3206. /// for less/greater and for strict/non-strict comparison.
  3207. bool CheckCond(Expr *S);
  3208. /// \brief Check incr-expr for canonical loop form and return true if it
  3209. /// does not conform, otherwise save loop step (#Step).
  3210. bool CheckInc(Expr *S);
  3211. /// \brief Return the loop counter variable.
  3212. ValueDecl *GetLoopDecl() const { return LCDecl; }
  3213. /// \brief Return the reference expression to loop counter variable.
  3214. Expr *GetLoopDeclRefExpr() const { return LCRef; }
  3215. /// \brief Source range of the loop init.
  3216. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  3217. /// \brief Source range of the loop condition.
  3218. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  3219. /// \brief Source range of the loop increment.
  3220. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  3221. /// \brief True if the step should be subtracted.
  3222. bool ShouldSubtractStep() const { return SubtractStep; }
  3223. /// \brief Build the expression to calculate the number of iterations.
  3224. Expr *
  3225. BuildNumIterations(Scope *S, const bool LimitedType,
  3226. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3227. /// \brief Build the precondition expression for the loops.
  3228. Expr *BuildPreCond(Scope *S, Expr *Cond,
  3229. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
  3230. /// \brief Build reference expression to the counter be used for codegen.
  3231. DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
  3232. DSAStackTy &DSA) const;
  3233. /// \brief Build reference expression to the private counter be used for
  3234. /// codegen.
  3235. Expr *BuildPrivateCounterVar() const;
  3236. /// \brief Build initialization of the counter be used for codegen.
  3237. Expr *BuildCounterInit() const;
  3238. /// \brief Build step of the counter be used for codegen.
  3239. Expr *BuildCounterStep() const;
  3240. /// \brief Return true if any expression is dependent.
  3241. bool Dependent() const;
  3242. private:
  3243. /// \brief Check the right-hand side of an assignment in the increment
  3244. /// expression.
  3245. bool CheckIncRHS(Expr *RHS);
  3246. /// \brief Helper to set loop counter variable and its initializer.
  3247. bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3248. /// \brief Helper to set upper bound.
  3249. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  3250. SourceLocation SL);
  3251. /// \brief Helper to set loop increment.
  3252. bool SetStep(Expr *NewStep, bool Subtract);
  3253. };
  3254. bool OpenMPIterationSpaceChecker::Dependent() const {
  3255. if (!LCDecl) {
  3256. assert(!LB && !UB && !Step);
  3257. return false;
  3258. }
  3259. return LCDecl->getType()->isDependentType() ||
  3260. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3261. (Step && Step->isValueDependent());
  3262. }
  3263. bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
  3264. Expr *NewLCRefExpr,
  3265. Expr *NewLB) {
  3266. // State consistency checking to ensure correct usage.
  3267. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3268. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3269. if (!NewLCDecl || !NewLB)
  3270. return true;
  3271. LCDecl = getCanonicalDecl(NewLCDecl);
  3272. LCRef = NewLCRefExpr;
  3273. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3274. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3275. if ((Ctor->isCopyOrMoveConstructor() ||
  3276. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3277. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3278. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3279. LB = NewLB;
  3280. return false;
  3281. }
  3282. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3283. SourceRange SR, SourceLocation SL) {
  3284. // State consistency checking to ensure correct usage.
  3285. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3286. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3287. if (!NewUB)
  3288. return true;
  3289. UB = NewUB;
  3290. TestIsLessOp = LessOp;
  3291. TestIsStrictOp = StrictOp;
  3292. ConditionSrcRange = SR;
  3293. ConditionLoc = SL;
  3294. return false;
  3295. }
  3296. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  3297. // State consistency checking to ensure correct usage.
  3298. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3299. if (!NewStep)
  3300. return true;
  3301. if (!NewStep->isValueDependent()) {
  3302. // Check that the step is integer expression.
  3303. SourceLocation StepLoc = NewStep->getLocStart();
  3304. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3305. StepLoc, getExprAsWritten(NewStep));
  3306. if (Val.isInvalid())
  3307. return true;
  3308. NewStep = Val.get();
  3309. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3310. // If test-expr is of form var relational-op b and relational-op is < or
  3311. // <= then incr-expr must cause var to increase on each iteration of the
  3312. // loop. If test-expr is of form var relational-op b and relational-op is
  3313. // > or >= then incr-expr must cause var to decrease on each iteration of
  3314. // the loop.
  3315. // If test-expr is of form b relational-op var and relational-op is < or
  3316. // <= then incr-expr must cause var to decrease on each iteration of the
  3317. // loop. If test-expr is of form b relational-op var and relational-op is
  3318. // > or >= then incr-expr must cause var to increase on each iteration of
  3319. // the loop.
  3320. llvm::APSInt Result;
  3321. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3322. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3323. bool IsConstNeg =
  3324. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3325. bool IsConstPos =
  3326. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3327. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3328. if (UB && (IsConstZero ||
  3329. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3330. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3331. SemaRef.Diag(NewStep->getExprLoc(),
  3332. diag::err_omp_loop_incr_not_compatible)
  3333. << LCDecl << TestIsLessOp << NewStep->getSourceRange();
  3334. SemaRef.Diag(ConditionLoc,
  3335. diag::note_omp_loop_cond_requres_compatible_incr)
  3336. << TestIsLessOp << ConditionSrcRange;
  3337. return true;
  3338. }
  3339. if (TestIsLessOp == Subtract) {
  3340. NewStep =
  3341. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3342. .get();
  3343. Subtract = !Subtract;
  3344. }
  3345. }
  3346. Step = NewStep;
  3347. SubtractStep = Subtract;
  3348. return false;
  3349. }
  3350. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  3351. // Check init-expr for canonical loop form and save loop counter
  3352. // variable - #Var and its initialization value - #LB.
  3353. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3354. // var = lb
  3355. // integer-type var = lb
  3356. // random-access-iterator-type var = lb
  3357. // pointer-type var = lb
  3358. //
  3359. if (!S) {
  3360. if (EmitDiags) {
  3361. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3362. }
  3363. return true;
  3364. }
  3365. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3366. if (!ExprTemp->cleanupsHaveSideEffects())
  3367. S = ExprTemp->getSubExpr();
  3368. InitSrcRange = S->getSourceRange();
  3369. if (Expr *E = dyn_cast<Expr>(S))
  3370. S = E->IgnoreParens();
  3371. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3372. if (BO->getOpcode() == BO_Assign) {
  3373. auto *LHS = BO->getLHS()->IgnoreParens();
  3374. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3375. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3376. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3377. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3378. return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  3379. }
  3380. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3381. if (ME->isArrow() &&
  3382. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3383. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3384. }
  3385. }
  3386. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  3387. if (DS->isSingleDecl()) {
  3388. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3389. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3390. // Accept non-canonical init form here but emit ext. warning.
  3391. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3392. SemaRef.Diag(S->getLocStart(),
  3393. diag::ext_omp_loop_not_canonical_init)
  3394. << S->getSourceRange();
  3395. return SetLCDeclAndLB(Var, nullptr, Var->getInit());
  3396. }
  3397. }
  3398. }
  3399. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3400. if (CE->getOperator() == OO_Equal) {
  3401. auto *LHS = CE->getArg(0);
  3402. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  3403. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  3404. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  3405. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3406. return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  3407. }
  3408. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  3409. if (ME->isArrow() &&
  3410. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3411. return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  3412. }
  3413. }
  3414. }
  3415. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3416. return false;
  3417. if (EmitDiags) {
  3418. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3419. << S->getSourceRange();
  3420. }
  3421. return true;
  3422. }
  3423. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3424. /// variable (which may be the loop variable) if possible.
  3425. static const ValueDecl *GetInitLCDecl(Expr *E) {
  3426. if (!E)
  3427. return nullptr;
  3428. E = getExprAsWritten(E);
  3429. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3430. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3431. if ((Ctor->isCopyOrMoveConstructor() ||
  3432. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3433. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3434. E = CE->getArg(0)->IgnoreParenImpCasts();
  3435. if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  3436. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  3437. return getCanonicalDecl(VD);
  3438. }
  3439. if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
  3440. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  3441. return getCanonicalDecl(ME->getMemberDecl());
  3442. return nullptr;
  3443. }
  3444. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  3445. // Check test-expr for canonical form, save upper-bound UB, flags for
  3446. // less/greater and for strict/non-strict comparison.
  3447. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3448. // var relational-op b
  3449. // b relational-op var
  3450. //
  3451. if (!S) {
  3452. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  3453. return true;
  3454. }
  3455. S = getExprAsWritten(S);
  3456. SourceLocation CondLoc = S->getLocStart();
  3457. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3458. if (BO->isRelationalOp()) {
  3459. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3460. return SetUB(BO->getRHS(),
  3461. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3462. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3463. BO->getSourceRange(), BO->getOperatorLoc());
  3464. if (GetInitLCDecl(BO->getRHS()) == LCDecl)
  3465. return SetUB(BO->getLHS(),
  3466. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3467. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3468. BO->getSourceRange(), BO->getOperatorLoc());
  3469. }
  3470. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3471. if (CE->getNumArgs() == 2) {
  3472. auto Op = CE->getOperator();
  3473. switch (Op) {
  3474. case OO_Greater:
  3475. case OO_GreaterEqual:
  3476. case OO_Less:
  3477. case OO_LessEqual:
  3478. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3479. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3480. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3481. CE->getOperatorLoc());
  3482. if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3483. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3484. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3485. CE->getOperatorLoc());
  3486. break;
  3487. default:
  3488. break;
  3489. }
  3490. }
  3491. }
  3492. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3493. return false;
  3494. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3495. << S->getSourceRange() << LCDecl;
  3496. return true;
  3497. }
  3498. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  3499. // RHS of canonical loop form increment can be:
  3500. // var + incr
  3501. // incr + var
  3502. // var - incr
  3503. //
  3504. RHS = RHS->IgnoreParenImpCasts();
  3505. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  3506. if (BO->isAdditiveOp()) {
  3507. bool IsAdd = BO->getOpcode() == BO_Add;
  3508. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3509. return SetStep(BO->getRHS(), !IsAdd);
  3510. if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
  3511. return SetStep(BO->getLHS(), false);
  3512. }
  3513. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3514. bool IsAdd = CE->getOperator() == OO_Plus;
  3515. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3516. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3517. return SetStep(CE->getArg(1), !IsAdd);
  3518. if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
  3519. return SetStep(CE->getArg(0), false);
  3520. }
  3521. }
  3522. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3523. return false;
  3524. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3525. << RHS->getSourceRange() << LCDecl;
  3526. return true;
  3527. }
  3528. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  3529. // Check incr-expr for canonical loop form and return true if it
  3530. // does not conform.
  3531. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3532. // ++var
  3533. // var++
  3534. // --var
  3535. // var--
  3536. // var += incr
  3537. // var -= incr
  3538. // var = var + incr
  3539. // var = incr + var
  3540. // var = var - incr
  3541. //
  3542. if (!S) {
  3543. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  3544. return true;
  3545. }
  3546. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3547. if (!ExprTemp->cleanupsHaveSideEffects())
  3548. S = ExprTemp->getSubExpr();
  3549. IncrementSrcRange = S->getSourceRange();
  3550. S = S->IgnoreParens();
  3551. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  3552. if (UO->isIncrementDecrementOp() &&
  3553. GetInitLCDecl(UO->getSubExpr()) == LCDecl)
  3554. return SetStep(SemaRef
  3555. .ActOnIntegerConstant(UO->getLocStart(),
  3556. (UO->isDecrementOp() ? -1 : 1))
  3557. .get(),
  3558. false);
  3559. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  3560. switch (BO->getOpcode()) {
  3561. case BO_AddAssign:
  3562. case BO_SubAssign:
  3563. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3564. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3565. break;
  3566. case BO_Assign:
  3567. if (GetInitLCDecl(BO->getLHS()) == LCDecl)
  3568. return CheckIncRHS(BO->getRHS());
  3569. break;
  3570. default:
  3571. break;
  3572. }
  3573. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3574. switch (CE->getOperator()) {
  3575. case OO_PlusPlus:
  3576. case OO_MinusMinus:
  3577. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3578. return SetStep(SemaRef
  3579. .ActOnIntegerConstant(
  3580. CE->getLocStart(),
  3581. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  3582. .get(),
  3583. false);
  3584. break;
  3585. case OO_PlusEqual:
  3586. case OO_MinusEqual:
  3587. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3588. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3589. break;
  3590. case OO_Equal:
  3591. if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
  3592. return CheckIncRHS(CE->getArg(1));
  3593. break;
  3594. default:
  3595. break;
  3596. }
  3597. }
  3598. if (Dependent() || SemaRef.CurContext->isDependentContext())
  3599. return false;
  3600. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3601. << S->getSourceRange() << LCDecl;
  3602. return true;
  3603. }
  3604. static ExprResult
  3605. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  3606. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3607. if (SemaRef.CurContext->isDependentContext())
  3608. return ExprResult(Capture);
  3609. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  3610. return SemaRef.PerformImplicitConversion(
  3611. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  3612. /*AllowExplicit=*/true);
  3613. auto I = Captures.find(Capture);
  3614. if (I != Captures.end())
  3615. return buildCapture(SemaRef, Capture, I->second);
  3616. DeclRefExpr *Ref = nullptr;
  3617. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  3618. Captures[Capture] = Ref;
  3619. return Res;
  3620. }
  3621. /// \brief Build the expression to calculate the number of iterations.
  3622. Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
  3623. Scope *S, const bool LimitedType,
  3624. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3625. ExprResult Diff;
  3626. auto VarType = LCDecl->getType().getNonReferenceType();
  3627. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3628. SemaRef.getLangOpts().CPlusPlus) {
  3629. // Upper - Lower
  3630. auto *UBExpr = TestIsLessOp ? UB : LB;
  3631. auto *LBExpr = TestIsLessOp ? LB : UB;
  3632. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  3633. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  3634. if (!Upper || !Lower)
  3635. return nullptr;
  3636. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3637. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3638. // BuildBinOp already emitted error, this one is to point user to upper
  3639. // and lower bound, and to tell what is passed to 'operator-'.
  3640. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3641. << Upper->getSourceRange() << Lower->getSourceRange();
  3642. return nullptr;
  3643. }
  3644. }
  3645. if (!Diff.isUsable())
  3646. return nullptr;
  3647. // Upper - Lower [- 1]
  3648. if (TestIsStrictOp)
  3649. Diff = SemaRef.BuildBinOp(
  3650. S, DefaultLoc, BO_Sub, Diff.get(),
  3651. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3652. if (!Diff.isUsable())
  3653. return nullptr;
  3654. // Upper - Lower [- 1] + Step
  3655. auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
  3656. if (!NewStep.isUsable())
  3657. return nullptr;
  3658. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3659. if (!Diff.isUsable())
  3660. return nullptr;
  3661. // Parentheses (for dumping/debugging purposes only).
  3662. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3663. if (!Diff.isUsable())
  3664. return nullptr;
  3665. // (Upper - Lower [- 1] + Step) / Step
  3666. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3667. if (!Diff.isUsable())
  3668. return nullptr;
  3669. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3670. QualType Type = Diff.get()->getType();
  3671. auto &C = SemaRef.Context;
  3672. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3673. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3674. if (!Type->isIntegerType() || UseVarType) {
  3675. unsigned NewSize =
  3676. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3677. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3678. : Type->hasSignedIntegerRepresentation();
  3679. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3680. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  3681. Diff = SemaRef.PerformImplicitConversion(
  3682. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3683. if (!Diff.isUsable())
  3684. return nullptr;
  3685. }
  3686. }
  3687. if (LimitedType) {
  3688. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3689. if (NewSize != C.getTypeSize(Type)) {
  3690. if (NewSize < C.getTypeSize(Type)) {
  3691. assert(NewSize == 64 && "incorrect loop var size");
  3692. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3693. << InitSrcRange << ConditionSrcRange;
  3694. }
  3695. QualType NewType = C.getIntTypeForBitwidth(
  3696. NewSize, Type->hasSignedIntegerRepresentation() ||
  3697. C.getTypeSize(Type) < NewSize);
  3698. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  3699. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3700. Sema::AA_Converting, true);
  3701. if (!Diff.isUsable())
  3702. return nullptr;
  3703. }
  3704. }
  3705. }
  3706. return Diff.get();
  3707. }
  3708. Expr *OpenMPIterationSpaceChecker::BuildPreCond(
  3709. Scope *S, Expr *Cond,
  3710. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
  3711. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3712. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3713. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3714. auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
  3715. auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
  3716. if (!NewLB.isUsable() || !NewUB.isUsable())
  3717. return nullptr;
  3718. auto CondExpr = SemaRef.BuildBinOp(
  3719. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3720. : (TestIsStrictOp ? BO_GT : BO_GE),
  3721. NewLB.get(), NewUB.get());
  3722. if (CondExpr.isUsable()) {
  3723. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  3724. SemaRef.Context.BoolTy))
  3725. CondExpr = SemaRef.PerformImplicitConversion(
  3726. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3727. /*AllowExplicit=*/true);
  3728. }
  3729. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3730. // Otherwise use original loop conditon and evaluate it in runtime.
  3731. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3732. }
  3733. /// \brief Build reference expression to the counter be used for codegen.
  3734. DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
  3735. llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
  3736. auto *VD = dyn_cast<VarDecl>(LCDecl);
  3737. if (!VD) {
  3738. VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
  3739. auto *Ref = buildDeclRefExpr(
  3740. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  3741. DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  3742. // If the loop control decl is explicitly marked as private, do not mark it
  3743. // as captured again.
  3744. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  3745. Captures.insert(std::make_pair(LCRef, Ref));
  3746. return Ref;
  3747. }
  3748. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  3749. DefaultLoc);
  3750. }
  3751. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3752. if (LCDecl && !LCDecl->isInvalidDecl()) {
  3753. auto Type = LCDecl->getType().getNonReferenceType();
  3754. auto *PrivateVar =
  3755. buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
  3756. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
  3757. if (PrivateVar->isInvalidDecl())
  3758. return nullptr;
  3759. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3760. }
  3761. return nullptr;
  3762. }
  3763. /// \brief Build initialization of the counter to be used for codegen.
  3764. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3765. /// \brief Build step of the counter be used for codegen.
  3766. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3767. /// \brief Iteration space of a single for loop.
  3768. struct LoopIterationSpace final {
  3769. /// \brief Condition of the loop.
  3770. Expr *PreCond = nullptr;
  3771. /// \brief This expression calculates the number of iterations in the loop.
  3772. /// It is always possible to calculate it before starting the loop.
  3773. Expr *NumIterations = nullptr;
  3774. /// \brief The loop counter variable.
  3775. Expr *CounterVar = nullptr;
  3776. /// \brief Private loop counter variable.
  3777. Expr *PrivateCounterVar = nullptr;
  3778. /// \brief This is initializer for the initial value of #CounterVar.
  3779. Expr *CounterInit = nullptr;
  3780. /// \brief This is step for the #CounterVar used to generate its update:
  3781. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3782. Expr *CounterStep = nullptr;
  3783. /// \brief Should step be subtracted?
  3784. bool Subtract = false;
  3785. /// \brief Source range of the loop init.
  3786. SourceRange InitSrcRange;
  3787. /// \brief Source range of the loop condition.
  3788. SourceRange CondSrcRange;
  3789. /// \brief Source range of the loop increment.
  3790. SourceRange IncSrcRange;
  3791. };
  3792. } // namespace
  3793. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3794. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3795. assert(Init && "Expected loop in canonical form.");
  3796. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3797. if (AssociatedLoops > 0 &&
  3798. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3799. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3800. if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
  3801. if (auto *D = ISC.GetLoopDecl()) {
  3802. auto *VD = dyn_cast<VarDecl>(D);
  3803. if (!VD) {
  3804. if (auto *Private = IsOpenMPCapturedDecl(D))
  3805. VD = Private;
  3806. else {
  3807. auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
  3808. /*WithInit=*/false);
  3809. VD = cast<VarDecl>(Ref->getDecl());
  3810. }
  3811. }
  3812. DSAStack->addLoopControlVariable(D, VD);
  3813. }
  3814. }
  3815. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3816. }
  3817. }
  3818. /// \brief Called on a for stmt to check and extract its iteration space
  3819. /// for further processing (such as collapsing).
  3820. static bool CheckOpenMPIterationSpace(
  3821. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3822. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3823. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3824. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3825. LoopIterationSpace &ResultIterSpace,
  3826. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3827. // OpenMP [2.6, Canonical Loop Form]
  3828. // for (init-expr; test-expr; incr-expr) structured-block
  3829. auto *For = dyn_cast_or_null<ForStmt>(S);
  3830. if (!For) {
  3831. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3832. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3833. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3834. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3835. if (NestedLoopCount > 1) {
  3836. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3837. SemaRef.Diag(DSA.getConstructLoc(),
  3838. diag::note_omp_collapse_ordered_expr)
  3839. << 2 << CollapseLoopCountExpr->getSourceRange()
  3840. << OrderedLoopCountExpr->getSourceRange();
  3841. else if (CollapseLoopCountExpr)
  3842. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3843. diag::note_omp_collapse_ordered_expr)
  3844. << 0 << CollapseLoopCountExpr->getSourceRange();
  3845. else
  3846. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3847. diag::note_omp_collapse_ordered_expr)
  3848. << 1 << OrderedLoopCountExpr->getSourceRange();
  3849. }
  3850. return true;
  3851. }
  3852. assert(For->getBody());
  3853. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3854. // Check init.
  3855. auto Init = For->getInit();
  3856. if (ISC.CheckInit(Init))
  3857. return true;
  3858. bool HasErrors = false;
  3859. // Check loop variable's type.
  3860. if (auto *LCDecl = ISC.GetLoopDecl()) {
  3861. auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
  3862. // OpenMP [2.6, Canonical Loop Form]
  3863. // Var is one of the following:
  3864. // A variable of signed or unsigned integer type.
  3865. // For C++, a variable of a random access iterator type.
  3866. // For C, a variable of a pointer type.
  3867. auto VarType = LCDecl->getType().getNonReferenceType();
  3868. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3869. !VarType->isPointerType() &&
  3870. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3871. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3872. << SemaRef.getLangOpts().CPlusPlus;
  3873. HasErrors = true;
  3874. }
  3875. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  3876. // a Construct
  3877. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3878. // parallel for construct is (are) private.
  3879. // The loop iteration variable in the associated for-loop of a simd
  3880. // construct with just one associated for-loop is linear with a
  3881. // constant-linear-step that is the increment of the associated for-loop.
  3882. // Exclude loop var from the list of variables with implicitly defined data
  3883. // sharing attributes.
  3884. VarsWithImplicitDSA.erase(LCDecl);
  3885. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  3886. // in a Construct, C/C++].
  3887. // The loop iteration variable in the associated for-loop of a simd
  3888. // construct with just one associated for-loop may be listed in a linear
  3889. // clause with a constant-linear-step that is the increment of the
  3890. // associated for-loop.
  3891. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3892. // parallel for construct may be listed in a private or lastprivate clause.
  3893. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  3894. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3895. // declared in the loop and it is predetermined as a private.
  3896. auto PredeterminedCKind =
  3897. isOpenMPSimdDirective(DKind)
  3898. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3899. : OMPC_private;
  3900. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3901. DVar.CKind != PredeterminedCKind) ||
  3902. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3903. isOpenMPDistributeDirective(DKind)) &&
  3904. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3905. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3906. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3907. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3908. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3909. << getOpenMPClauseName(PredeterminedCKind);
  3910. if (DVar.RefExpr == nullptr)
  3911. DVar.CKind = PredeterminedCKind;
  3912. ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  3913. HasErrors = true;
  3914. } else if (LoopDeclRefExpr != nullptr) {
  3915. // Make the loop iteration variable private (for worksharing constructs),
  3916. // linear (for simd directives with the only one associated loop) or
  3917. // lastprivate (for simd directives with several collapsed or ordered
  3918. // loops).
  3919. if (DVar.CKind == OMPC_unknown)
  3920. DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
  3921. [](OpenMPDirectiveKind) -> bool { return true; },
  3922. /*FromParent=*/false);
  3923. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  3924. }
  3925. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3926. // Check test-expr.
  3927. HasErrors |= ISC.CheckCond(For->getCond());
  3928. // Check incr-expr.
  3929. HasErrors |= ISC.CheckInc(For->getInc());
  3930. }
  3931. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3932. return HasErrors;
  3933. // Build the loop's iteration space representation.
  3934. ResultIterSpace.PreCond =
  3935. ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  3936. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  3937. DSA.getCurScope(),
  3938. (isOpenMPWorksharingDirective(DKind) ||
  3939. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  3940. Captures);
  3941. ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
  3942. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  3943. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  3944. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  3945. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  3946. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  3947. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  3948. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  3949. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  3950. ResultIterSpace.NumIterations == nullptr ||
  3951. ResultIterSpace.CounterVar == nullptr ||
  3952. ResultIterSpace.PrivateCounterVar == nullptr ||
  3953. ResultIterSpace.CounterInit == nullptr ||
  3954. ResultIterSpace.CounterStep == nullptr);
  3955. return HasErrors;
  3956. }
  3957. /// \brief Build 'VarRef = Start.
  3958. static ExprResult
  3959. BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  3960. ExprResult Start,
  3961. llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  3962. // Build 'VarRef = Start.
  3963. auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  3964. if (!NewStart.isUsable())
  3965. return ExprError();
  3966. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  3967. VarRef.get()->getType())) {
  3968. NewStart = SemaRef.PerformImplicitConversion(
  3969. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  3970. /*AllowExplicit=*/true);
  3971. if (!NewStart.isUsable())
  3972. return ExprError();
  3973. }
  3974. auto Init =
  3975. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  3976. return Init;
  3977. }
  3978. /// \brief Build 'VarRef = Start + Iter * Step'.
  3979. static ExprResult
  3980. BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
  3981. ExprResult VarRef, ExprResult Start, ExprResult Iter,
  3982. ExprResult Step, bool Subtract,
  3983. llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
  3984. // Add parentheses (for debugging purposes only).
  3985. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  3986. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  3987. !Step.isUsable())
  3988. return ExprError();
  3989. ExprResult NewStep = Step;
  3990. if (Captures)
  3991. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  3992. if (NewStep.isInvalid())
  3993. return ExprError();
  3994. ExprResult Update =
  3995. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  3996. if (!Update.isUsable())
  3997. return ExprError();
  3998. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  3999. // 'VarRef = Start (+|-) Iter * Step'.
  4000. ExprResult NewStart = Start;
  4001. if (Captures)
  4002. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4003. if (NewStart.isInvalid())
  4004. return ExprError();
  4005. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4006. ExprResult SavedUpdate = Update;
  4007. ExprResult UpdateVal;
  4008. if (VarRef.get()->getType()->isOverloadableType() ||
  4009. NewStart.get()->getType()->isOverloadableType() ||
  4010. Update.get()->getType()->isOverloadableType()) {
  4011. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4012. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4013. Update =
  4014. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4015. if (Update.isUsable()) {
  4016. UpdateVal =
  4017. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4018. VarRef.get(), SavedUpdate.get());
  4019. if (UpdateVal.isUsable()) {
  4020. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4021. UpdateVal.get());
  4022. }
  4023. }
  4024. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4025. }
  4026. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4027. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4028. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4029. NewStart.get(), SavedUpdate.get());
  4030. if (!Update.isUsable())
  4031. return ExprError();
  4032. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4033. VarRef.get()->getType())) {
  4034. Update = SemaRef.PerformImplicitConversion(
  4035. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4036. if (!Update.isUsable())
  4037. return ExprError();
  4038. }
  4039. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4040. }
  4041. return Update;
  4042. }
  4043. /// \brief Convert integer expression \a E to make it have at least \a Bits
  4044. /// bits.
  4045. static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4046. if (E == nullptr)
  4047. return ExprError();
  4048. auto &C = SemaRef.Context;
  4049. QualType OldType = E->getType();
  4050. unsigned HasBits = C.getTypeSize(OldType);
  4051. if (HasBits >= Bits)
  4052. return ExprResult(E);
  4053. // OK to convert to signed, because new type has more bits than old.
  4054. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4055. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4056. true);
  4057. }
  4058. /// \brief Check if the given expression \a E is a constant integer that fits
  4059. /// into \a Bits bits.
  4060. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  4061. if (E == nullptr)
  4062. return false;
  4063. llvm::APSInt Result;
  4064. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4065. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4066. return false;
  4067. }
  4068. /// Build preinits statement for the given declarations.
  4069. static Stmt *buildPreInits(ASTContext &Context,
  4070. MutableArrayRef<Decl *> PreInits) {
  4071. if (!PreInits.empty()) {
  4072. return new (Context) DeclStmt(
  4073. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4074. SourceLocation(), SourceLocation());
  4075. }
  4076. return nullptr;
  4077. }
  4078. /// Build preinits statement for the given declarations.
  4079. static Stmt *
  4080. buildPreInits(ASTContext &Context,
  4081. const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
  4082. if (!Captures.empty()) {
  4083. SmallVector<Decl *, 16> PreInits;
  4084. for (auto &Pair : Captures)
  4085. PreInits.push_back(Pair.second->getDecl());
  4086. return buildPreInits(Context, PreInits);
  4087. }
  4088. return nullptr;
  4089. }
  4090. /// Build postupdate expression for the given list of postupdates expressions.
  4091. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4092. Expr *PostUpdate = nullptr;
  4093. if (!PostUpdates.empty()) {
  4094. for (auto *E : PostUpdates) {
  4095. Expr *ConvE = S.BuildCStyleCastExpr(
  4096. E->getExprLoc(),
  4097. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4098. E->getExprLoc(), E)
  4099. .get();
  4100. PostUpdate = PostUpdate
  4101. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4102. PostUpdate, ConvE)
  4103. .get()
  4104. : ConvE;
  4105. }
  4106. }
  4107. return PostUpdate;
  4108. }
  4109. /// \brief Called on a for stmt to check itself and nested loops (if any).
  4110. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4111. /// number of collapsed loops otherwise.
  4112. static unsigned
  4113. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4114. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4115. DSAStackTy &DSA,
  4116. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  4117. OMPLoopDirective::HelperExprs &Built) {
  4118. unsigned NestedLoopCount = 1;
  4119. if (CollapseLoopCountExpr) {
  4120. // Found 'collapse' clause - calculate collapse number.
  4121. llvm::APSInt Result;
  4122. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4123. NestedLoopCount = Result.getLimitedValue();
  4124. }
  4125. if (OrderedLoopCountExpr) {
  4126. // Found 'ordered' clause - calculate collapse number.
  4127. llvm::APSInt Result;
  4128. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  4129. if (Result.getLimitedValue() < NestedLoopCount) {
  4130. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4131. diag::err_omp_wrong_ordered_loop_count)
  4132. << OrderedLoopCountExpr->getSourceRange();
  4133. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4134. diag::note_collapse_loop_count)
  4135. << CollapseLoopCountExpr->getSourceRange();
  4136. }
  4137. NestedLoopCount = Result.getLimitedValue();
  4138. }
  4139. }
  4140. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4141. // 'for simd', etc.).
  4142. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  4143. SmallVector<LoopIterationSpace, 4> IterSpaces;
  4144. IterSpaces.resize(NestedLoopCount);
  4145. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4146. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4147. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  4148. NestedLoopCount, CollapseLoopCountExpr,
  4149. OrderedLoopCountExpr, VarsWithImplicitDSA,
  4150. IterSpaces[Cnt], Captures))
  4151. return 0;
  4152. // Move on to the next nested for loop, or to the loop body.
  4153. // OpenMP [2.8.1, simd construct, Restrictions]
  4154. // All loops associated with the construct must be perfectly nested; that
  4155. // is, there must be no intervening code nor any OpenMP directive between
  4156. // any two loops.
  4157. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4158. }
  4159. Built.clear(/* size */ NestedLoopCount);
  4160. if (SemaRef.CurContext->isDependentContext())
  4161. return NestedLoopCount;
  4162. // An example of what is generated for the following code:
  4163. //
  4164. // #pragma omp simd collapse(2) ordered(2)
  4165. // for (i = 0; i < NI; ++i)
  4166. // for (k = 0; k < NK; ++k)
  4167. // for (j = J0; j < NJ; j+=2) {
  4168. // <loop body>
  4169. // }
  4170. //
  4171. // We generate the code below.
  4172. // Note: the loop body may be outlined in CodeGen.
  4173. // Note: some counters may be C++ classes, operator- is used to find number of
  4174. // iterations and operator+= to calculate counter value.
  4175. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4176. // or i64 is currently supported).
  4177. //
  4178. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4179. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4180. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4181. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4182. // // similar updates for vars in clauses (e.g. 'linear')
  4183. // <loop body (using local i and j)>
  4184. // }
  4185. // i = NI; // assign final values of counters
  4186. // j = NJ;
  4187. //
  4188. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4189. // the iteration counts of the collapsed for loops.
  4190. // Precondition tests if there is at least one iteration (all conditions are
  4191. // true).
  4192. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4193. auto N0 = IterSpaces[0].NumIterations;
  4194. ExprResult LastIteration32 = WidenIterationCount(
  4195. 32 /* Bits */, SemaRef
  4196. .PerformImplicitConversion(
  4197. N0->IgnoreImpCasts(), N0->getType(),
  4198. Sema::AA_Converting, /*AllowExplicit=*/true)
  4199. .get(),
  4200. SemaRef);
  4201. ExprResult LastIteration64 = WidenIterationCount(
  4202. 64 /* Bits */, SemaRef
  4203. .PerformImplicitConversion(
  4204. N0->IgnoreImpCasts(), N0->getType(),
  4205. Sema::AA_Converting, /*AllowExplicit=*/true)
  4206. .get(),
  4207. SemaRef);
  4208. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4209. return NestedLoopCount;
  4210. auto &C = SemaRef.Context;
  4211. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4212. Scope *CurScope = DSA.getCurScope();
  4213. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4214. if (PreCond.isUsable()) {
  4215. PreCond =
  4216. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4217. PreCond.get(), IterSpaces[Cnt].PreCond);
  4218. }
  4219. auto N = IterSpaces[Cnt].NumIterations;
  4220. SourceLocation Loc = N->getExprLoc();
  4221. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  4222. if (LastIteration32.isUsable())
  4223. LastIteration32 = SemaRef.BuildBinOp(
  4224. CurScope, Loc, BO_Mul, LastIteration32.get(),
  4225. SemaRef
  4226. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4227. Sema::AA_Converting,
  4228. /*AllowExplicit=*/true)
  4229. .get());
  4230. if (LastIteration64.isUsable())
  4231. LastIteration64 = SemaRef.BuildBinOp(
  4232. CurScope, Loc, BO_Mul, LastIteration64.get(),
  4233. SemaRef
  4234. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  4235. Sema::AA_Converting,
  4236. /*AllowExplicit=*/true)
  4237. .get());
  4238. }
  4239. // Choose either the 32-bit or 64-bit version.
  4240. ExprResult LastIteration = LastIteration64;
  4241. if (LastIteration32.isUsable() &&
  4242. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  4243. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  4244. FitsInto(
  4245. 32 /* Bits */,
  4246. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  4247. LastIteration64.get(), SemaRef)))
  4248. LastIteration = LastIteration32;
  4249. QualType VType = LastIteration.get()->getType();
  4250. QualType RealVType = VType;
  4251. QualType StrideVType = VType;
  4252. if (isOpenMPTaskLoopDirective(DKind)) {
  4253. VType =
  4254. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4255. StrideVType =
  4256. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4257. }
  4258. if (!LastIteration.isUsable())
  4259. return 0;
  4260. // Save the number of iterations.
  4261. ExprResult NumIterations = LastIteration;
  4262. {
  4263. LastIteration = SemaRef.BuildBinOp(
  4264. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  4265. LastIteration.get(),
  4266. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4267. if (!LastIteration.isUsable())
  4268. return 0;
  4269. }
  4270. // Calculate the last iteration number beforehand instead of doing this on
  4271. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  4272. llvm::APSInt Result;
  4273. bool IsConstant =
  4274. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  4275. ExprResult CalcLastIteration;
  4276. if (!IsConstant) {
  4277. ExprResult SaveRef =
  4278. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  4279. LastIteration = SaveRef;
  4280. // Prepare SaveRef + 1.
  4281. NumIterations = SemaRef.BuildBinOp(
  4282. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  4283. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4284. if (!NumIterations.isUsable())
  4285. return 0;
  4286. }
  4287. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  4288. // Build variables passed into runtime, necessary for worksharing directives.
  4289. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  4290. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4291. isOpenMPDistributeDirective(DKind)) {
  4292. // Lower bound variable, initialized with zero.
  4293. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  4294. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  4295. SemaRef.AddInitializerToDecl(LBDecl,
  4296. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4297. /*DirectInit*/ false);
  4298. // Upper bound variable, initialized with last iteration number.
  4299. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  4300. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  4301. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  4302. /*DirectInit*/ false);
  4303. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  4304. // This will be used to implement clause 'lastprivate'.
  4305. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  4306. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  4307. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  4308. SemaRef.AddInitializerToDecl(ILDecl,
  4309. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4310. /*DirectInit*/ false);
  4311. // Stride variable returned by runtime (we initialize it to 1 by default).
  4312. VarDecl *STDecl =
  4313. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  4314. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  4315. SemaRef.AddInitializerToDecl(STDecl,
  4316. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  4317. /*DirectInit*/ false);
  4318. // Build expression: UB = min(UB, LastIteration)
  4319. // It is necessary for CodeGen of directives with static scheduling.
  4320. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  4321. UB.get(), LastIteration.get());
  4322. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4323. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  4324. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  4325. CondOp.get());
  4326. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  4327. // If we have a combined directive that combines 'distribute', 'for' or
  4328. // 'simd' we need to be able to access the bounds of the schedule of the
  4329. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  4330. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  4331. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4332. // Lower bound variable, initialized with zero.
  4333. VarDecl *CombLBDecl =
  4334. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  4335. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  4336. SemaRef.AddInitializerToDecl(
  4337. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  4338. /*DirectInit*/ false);
  4339. // Upper bound variable, initialized with last iteration number.
  4340. VarDecl *CombUBDecl =
  4341. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  4342. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  4343. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  4344. /*DirectInit*/ false);
  4345. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  4346. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  4347. ExprResult CombCondOp =
  4348. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  4349. LastIteration.get(), CombUB.get());
  4350. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  4351. CombCondOp.get());
  4352. CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
  4353. auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  4354. // We expect to have at least 2 more parameters than the 'parallel'
  4355. // directive does - the lower and upper bounds of the previous schedule.
  4356. assert(CD->getNumParams() >= 4 &&
  4357. "Unexpected number of parameters in loop combined directive");
  4358. // Set the proper type for the bounds given what we learned from the
  4359. // enclosed loops.
  4360. auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  4361. auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  4362. // Previous lower and upper bounds are obtained from the region
  4363. // parameters.
  4364. PrevLB =
  4365. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  4366. PrevUB =
  4367. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  4368. }
  4369. }
  4370. // Build the iteration variable and its initialization before loop.
  4371. ExprResult IV;
  4372. ExprResult Init, CombInit;
  4373. {
  4374. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  4375. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  4376. Expr *RHS =
  4377. (isOpenMPWorksharingDirective(DKind) ||
  4378. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4379. ? LB.get()
  4380. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4381. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  4382. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  4383. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4384. Expr *CombRHS =
  4385. (isOpenMPWorksharingDirective(DKind) ||
  4386. isOpenMPTaskLoopDirective(DKind) ||
  4387. isOpenMPDistributeDirective(DKind))
  4388. ? CombLB.get()
  4389. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  4390. CombInit =
  4391. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  4392. CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
  4393. }
  4394. }
  4395. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  4396. SourceLocation CondLoc;
  4397. ExprResult Cond =
  4398. (isOpenMPWorksharingDirective(DKind) ||
  4399. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  4400. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  4401. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  4402. NumIterations.get());
  4403. ExprResult CombCond;
  4404. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4405. CombCond =
  4406. SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
  4407. }
  4408. // Loop increment (IV = IV + 1)
  4409. SourceLocation IncLoc;
  4410. ExprResult Inc =
  4411. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  4412. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  4413. if (!Inc.isUsable())
  4414. return 0;
  4415. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  4416. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  4417. if (!Inc.isUsable())
  4418. return 0;
  4419. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  4420. // Used for directives with static scheduling.
  4421. // In combined construct, add combined version that use CombLB and CombUB
  4422. // base variables for the update
  4423. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  4424. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  4425. isOpenMPDistributeDirective(DKind)) {
  4426. // LB + ST
  4427. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  4428. if (!NextLB.isUsable())
  4429. return 0;
  4430. // LB = LB + ST
  4431. NextLB =
  4432. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4433. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4434. if (!NextLB.isUsable())
  4435. return 0;
  4436. // UB + ST
  4437. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4438. if (!NextUB.isUsable())
  4439. return 0;
  4440. // UB = UB + ST
  4441. NextUB =
  4442. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4443. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4444. if (!NextUB.isUsable())
  4445. return 0;
  4446. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4447. CombNextLB =
  4448. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  4449. if (!NextLB.isUsable())
  4450. return 0;
  4451. // LB = LB + ST
  4452. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  4453. CombNextLB.get());
  4454. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
  4455. if (!CombNextLB.isUsable())
  4456. return 0;
  4457. // UB + ST
  4458. CombNextUB =
  4459. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  4460. if (!CombNextUB.isUsable())
  4461. return 0;
  4462. // UB = UB + ST
  4463. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  4464. CombNextUB.get());
  4465. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
  4466. if (!CombNextUB.isUsable())
  4467. return 0;
  4468. }
  4469. }
  4470. // Create increment expression for distribute loop when combined in a same
  4471. // directive with for as IV = IV + ST; ensure upper bound expression based
  4472. // on PrevUB instead of NumIterations - used to implement 'for' when found
  4473. // in combination with 'distribute', like in 'distribute parallel for'
  4474. SourceLocation DistIncLoc;
  4475. ExprResult DistCond, DistInc, PrevEUB;
  4476. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  4477. DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
  4478. assert(DistCond.isUsable() && "distribute cond expr was not built");
  4479. DistInc =
  4480. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  4481. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4482. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  4483. DistInc.get());
  4484. DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
  4485. assert(DistInc.isUsable() && "distribute inc expr was not built");
  4486. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  4487. // construct
  4488. SourceLocation DistEUBLoc;
  4489. ExprResult IsUBGreater =
  4490. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  4491. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  4492. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  4493. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  4494. CondOp.get());
  4495. PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
  4496. }
  4497. // Build updates and final values of the loop counters.
  4498. bool HasErrors = false;
  4499. Built.Counters.resize(NestedLoopCount);
  4500. Built.Inits.resize(NestedLoopCount);
  4501. Built.Updates.resize(NestedLoopCount);
  4502. Built.Finals.resize(NestedLoopCount);
  4503. SmallVector<Expr *, 4> LoopMultipliers;
  4504. {
  4505. ExprResult Div;
  4506. // Go from inner nested loop to outer.
  4507. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4508. LoopIterationSpace &IS = IterSpaces[Cnt];
  4509. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4510. // Build: Iter = (IV / Div) % IS.NumIters
  4511. // where Div is product of previous iterations' IS.NumIters.
  4512. ExprResult Iter;
  4513. if (Div.isUsable()) {
  4514. Iter =
  4515. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4516. } else {
  4517. Iter = IV;
  4518. assert((Cnt == (int)NestedLoopCount - 1) &&
  4519. "unusable div expected on first iteration only");
  4520. }
  4521. if (Cnt != 0 && Iter.isUsable())
  4522. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4523. IS.NumIterations);
  4524. if (!Iter.isUsable()) {
  4525. HasErrors = true;
  4526. break;
  4527. }
  4528. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4529. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  4530. auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
  4531. IS.CounterVar->getExprLoc(),
  4532. /*RefersToCapture=*/true);
  4533. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4534. IS.CounterInit, Captures);
  4535. if (!Init.isUsable()) {
  4536. HasErrors = true;
  4537. break;
  4538. }
  4539. ExprResult Update = BuildCounterUpdate(
  4540. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  4541. IS.CounterStep, IS.Subtract, &Captures);
  4542. if (!Update.isUsable()) {
  4543. HasErrors = true;
  4544. break;
  4545. }
  4546. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4547. ExprResult Final = BuildCounterUpdate(
  4548. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4549. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  4550. if (!Final.isUsable()) {
  4551. HasErrors = true;
  4552. break;
  4553. }
  4554. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4555. if (Cnt != 0) {
  4556. if (Div.isUnset())
  4557. Div = IS.NumIterations;
  4558. else
  4559. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4560. IS.NumIterations);
  4561. // Add parentheses (for debugging purposes only).
  4562. if (Div.isUsable())
  4563. Div = tryBuildCapture(SemaRef, Div.get(), Captures);
  4564. if (!Div.isUsable()) {
  4565. HasErrors = true;
  4566. break;
  4567. }
  4568. LoopMultipliers.push_back(Div.get());
  4569. }
  4570. if (!Update.isUsable() || !Final.isUsable()) {
  4571. HasErrors = true;
  4572. break;
  4573. }
  4574. // Save results
  4575. Built.Counters[Cnt] = IS.CounterVar;
  4576. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4577. Built.Inits[Cnt] = Init.get();
  4578. Built.Updates[Cnt] = Update.get();
  4579. Built.Finals[Cnt] = Final.get();
  4580. }
  4581. }
  4582. if (HasErrors)
  4583. return 0;
  4584. // Save results
  4585. Built.IterationVarRef = IV.get();
  4586. Built.LastIteration = LastIteration.get();
  4587. Built.NumIterations = NumIterations.get();
  4588. Built.CalcLastIteration =
  4589. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4590. Built.PreCond = PreCond.get();
  4591. Built.PreInits = buildPreInits(C, Captures);
  4592. Built.Cond = Cond.get();
  4593. Built.Init = Init.get();
  4594. Built.Inc = Inc.get();
  4595. Built.LB = LB.get();
  4596. Built.UB = UB.get();
  4597. Built.IL = IL.get();
  4598. Built.ST = ST.get();
  4599. Built.EUB = EUB.get();
  4600. Built.NLB = NextLB.get();
  4601. Built.NUB = NextUB.get();
  4602. Built.PrevLB = PrevLB.get();
  4603. Built.PrevUB = PrevUB.get();
  4604. Built.DistInc = DistInc.get();
  4605. Built.PrevEUB = PrevEUB.get();
  4606. Built.DistCombinedFields.LB = CombLB.get();
  4607. Built.DistCombinedFields.UB = CombUB.get();
  4608. Built.DistCombinedFields.EUB = CombEUB.get();
  4609. Built.DistCombinedFields.Init = CombInit.get();
  4610. Built.DistCombinedFields.Cond = CombCond.get();
  4611. Built.DistCombinedFields.NLB = CombNextLB.get();
  4612. Built.DistCombinedFields.NUB = CombNextUB.get();
  4613. Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
  4614. // Fill data for doacross depend clauses.
  4615. for (auto Pair : DSA.getDoacrossDependClauses()) {
  4616. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4617. Pair.first->setCounterValue(CounterVal);
  4618. else {
  4619. if (NestedLoopCount != Pair.second.size() ||
  4620. NestedLoopCount != LoopMultipliers.size() + 1) {
  4621. // Erroneous case - clause has some problems.
  4622. Pair.first->setCounterValue(CounterVal);
  4623. continue;
  4624. }
  4625. assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
  4626. auto I = Pair.second.rbegin();
  4627. auto IS = IterSpaces.rbegin();
  4628. auto ILM = LoopMultipliers.rbegin();
  4629. Expr *UpCounterVal = CounterVal;
  4630. Expr *Multiplier = nullptr;
  4631. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4632. if (I->first) {
  4633. assert(IS->CounterStep);
  4634. Expr *NormalizedOffset =
  4635. SemaRef
  4636. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
  4637. I->first, IS->CounterStep)
  4638. .get();
  4639. if (Multiplier) {
  4640. NormalizedOffset =
  4641. SemaRef
  4642. .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
  4643. NormalizedOffset, Multiplier)
  4644. .get();
  4645. }
  4646. assert(I->second == OO_Plus || I->second == OO_Minus);
  4647. BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
  4648. UpCounterVal = SemaRef
  4649. .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
  4650. UpCounterVal, NormalizedOffset)
  4651. .get();
  4652. }
  4653. Multiplier = *ILM;
  4654. ++I;
  4655. ++IS;
  4656. ++ILM;
  4657. }
  4658. Pair.first->setCounterValue(UpCounterVal);
  4659. }
  4660. }
  4661. return NestedLoopCount;
  4662. }
  4663. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4664. auto CollapseClauses =
  4665. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4666. if (CollapseClauses.begin() != CollapseClauses.end())
  4667. return (*CollapseClauses.begin())->getNumForLoops();
  4668. return nullptr;
  4669. }
  4670. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4671. auto OrderedClauses =
  4672. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4673. if (OrderedClauses.begin() != OrderedClauses.end())
  4674. return (*OrderedClauses.begin())->getNumForLoops();
  4675. return nullptr;
  4676. }
  4677. static bool checkSimdlenSafelenSpecified(Sema &S,
  4678. const ArrayRef<OMPClause *> Clauses) {
  4679. OMPSafelenClause *Safelen = nullptr;
  4680. OMPSimdlenClause *Simdlen = nullptr;
  4681. for (auto *Clause : Clauses) {
  4682. if (Clause->getClauseKind() == OMPC_safelen)
  4683. Safelen = cast<OMPSafelenClause>(Clause);
  4684. else if (Clause->getClauseKind() == OMPC_simdlen)
  4685. Simdlen = cast<OMPSimdlenClause>(Clause);
  4686. if (Safelen && Simdlen)
  4687. break;
  4688. }
  4689. if (Simdlen && Safelen) {
  4690. llvm::APSInt SimdlenRes, SafelenRes;
  4691. auto SimdlenLength = Simdlen->getSimdlen();
  4692. auto SafelenLength = Safelen->getSafelen();
  4693. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  4694. SimdlenLength->isInstantiationDependent() ||
  4695. SimdlenLength->containsUnexpandedParameterPack())
  4696. return false;
  4697. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  4698. SafelenLength->isInstantiationDependent() ||
  4699. SafelenLength->containsUnexpandedParameterPack())
  4700. return false;
  4701. SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
  4702. SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
  4703. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  4704. // If both simdlen and safelen clauses are specified, the value of the
  4705. // simdlen parameter must be less than or equal to the value of the safelen
  4706. // parameter.
  4707. if (SimdlenRes > SafelenRes) {
  4708. S.Diag(SimdlenLength->getExprLoc(),
  4709. diag::err_omp_wrong_simdlen_safelen_values)
  4710. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  4711. return true;
  4712. }
  4713. }
  4714. return false;
  4715. }
  4716. StmtResult Sema::ActOnOpenMPSimdDirective(
  4717. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4718. SourceLocation EndLoc,
  4719. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4720. if (!AStmt)
  4721. return StmtError();
  4722. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4723. OMPLoopDirective::HelperExprs B;
  4724. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4725. // define the nested loops number.
  4726. unsigned NestedLoopCount = CheckOpenMPLoop(
  4727. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4728. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4729. if (NestedLoopCount == 0)
  4730. return StmtError();
  4731. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4732. "omp simd loop exprs were not built");
  4733. if (!CurContext->isDependentContext()) {
  4734. // Finalize the clauses that need pre-built expressions for CodeGen.
  4735. for (auto C : Clauses) {
  4736. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4737. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4738. B.NumIterations, *this, CurScope,
  4739. DSAStack))
  4740. return StmtError();
  4741. }
  4742. }
  4743. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4744. return StmtError();
  4745. getCurFunction()->setHasBranchProtectedScope();
  4746. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4747. Clauses, AStmt, B);
  4748. }
  4749. StmtResult Sema::ActOnOpenMPForDirective(
  4750. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4751. SourceLocation EndLoc,
  4752. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4753. if (!AStmt)
  4754. return StmtError();
  4755. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4756. OMPLoopDirective::HelperExprs B;
  4757. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4758. // define the nested loops number.
  4759. unsigned NestedLoopCount = CheckOpenMPLoop(
  4760. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4761. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4762. if (NestedLoopCount == 0)
  4763. return StmtError();
  4764. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4765. "omp for loop exprs were not built");
  4766. if (!CurContext->isDependentContext()) {
  4767. // Finalize the clauses that need pre-built expressions for CodeGen.
  4768. for (auto C : Clauses) {
  4769. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4770. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4771. B.NumIterations, *this, CurScope,
  4772. DSAStack))
  4773. return StmtError();
  4774. }
  4775. }
  4776. getCurFunction()->setHasBranchProtectedScope();
  4777. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4778. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4779. }
  4780. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4781. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4782. SourceLocation EndLoc,
  4783. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4784. if (!AStmt)
  4785. return StmtError();
  4786. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4787. OMPLoopDirective::HelperExprs B;
  4788. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4789. // define the nested loops number.
  4790. unsigned NestedLoopCount =
  4791. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4792. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4793. VarsWithImplicitDSA, B);
  4794. if (NestedLoopCount == 0)
  4795. return StmtError();
  4796. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4797. "omp for simd loop exprs were not built");
  4798. if (!CurContext->isDependentContext()) {
  4799. // Finalize the clauses that need pre-built expressions for CodeGen.
  4800. for (auto C : Clauses) {
  4801. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4802. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4803. B.NumIterations, *this, CurScope,
  4804. DSAStack))
  4805. return StmtError();
  4806. }
  4807. }
  4808. if (checkSimdlenSafelenSpecified(*this, Clauses))
  4809. return StmtError();
  4810. getCurFunction()->setHasBranchProtectedScope();
  4811. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4812. Clauses, AStmt, B);
  4813. }
  4814. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4815. Stmt *AStmt,
  4816. SourceLocation StartLoc,
  4817. SourceLocation EndLoc) {
  4818. if (!AStmt)
  4819. return StmtError();
  4820. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4821. auto BaseStmt = AStmt;
  4822. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4823. BaseStmt = CS->getCapturedStmt();
  4824. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4825. auto S = C->children();
  4826. if (S.begin() == S.end())
  4827. return StmtError();
  4828. // All associated statements must be '#pragma omp section' except for
  4829. // the first one.
  4830. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4831. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4832. if (SectionStmt)
  4833. Diag(SectionStmt->getLocStart(),
  4834. diag::err_omp_sections_substmt_not_section);
  4835. return StmtError();
  4836. }
  4837. cast<OMPSectionDirective>(SectionStmt)
  4838. ->setHasCancel(DSAStack->isCancelRegion());
  4839. }
  4840. } else {
  4841. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4842. return StmtError();
  4843. }
  4844. getCurFunction()->setHasBranchProtectedScope();
  4845. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4846. DSAStack->isCancelRegion());
  4847. }
  4848. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4849. SourceLocation StartLoc,
  4850. SourceLocation EndLoc) {
  4851. if (!AStmt)
  4852. return StmtError();
  4853. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4854. getCurFunction()->setHasBranchProtectedScope();
  4855. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4856. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4857. DSAStack->isCancelRegion());
  4858. }
  4859. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4860. Stmt *AStmt,
  4861. SourceLocation StartLoc,
  4862. SourceLocation EndLoc) {
  4863. if (!AStmt)
  4864. return StmtError();
  4865. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4866. getCurFunction()->setHasBranchProtectedScope();
  4867. // OpenMP [2.7.3, single Construct, Restrictions]
  4868. // The copyprivate clause must not be used with the nowait clause.
  4869. OMPClause *Nowait = nullptr;
  4870. OMPClause *Copyprivate = nullptr;
  4871. for (auto *Clause : Clauses) {
  4872. if (Clause->getClauseKind() == OMPC_nowait)
  4873. Nowait = Clause;
  4874. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4875. Copyprivate = Clause;
  4876. if (Copyprivate && Nowait) {
  4877. Diag(Copyprivate->getLocStart(),
  4878. diag::err_omp_single_copyprivate_with_nowait);
  4879. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4880. return StmtError();
  4881. }
  4882. }
  4883. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4884. }
  4885. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4886. SourceLocation StartLoc,
  4887. SourceLocation EndLoc) {
  4888. if (!AStmt)
  4889. return StmtError();
  4890. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4891. getCurFunction()->setHasBranchProtectedScope();
  4892. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4893. }
  4894. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4895. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4896. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4897. if (!AStmt)
  4898. return StmtError();
  4899. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4900. bool ErrorFound = false;
  4901. llvm::APSInt Hint;
  4902. SourceLocation HintLoc;
  4903. bool DependentHint = false;
  4904. for (auto *C : Clauses) {
  4905. if (C->getClauseKind() == OMPC_hint) {
  4906. if (!DirName.getName()) {
  4907. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4908. ErrorFound = true;
  4909. }
  4910. Expr *E = cast<OMPHintClause>(C)->getHint();
  4911. if (E->isTypeDependent() || E->isValueDependent() ||
  4912. E->isInstantiationDependent())
  4913. DependentHint = true;
  4914. else {
  4915. Hint = E->EvaluateKnownConstInt(Context);
  4916. HintLoc = C->getLocStart();
  4917. }
  4918. }
  4919. }
  4920. if (ErrorFound)
  4921. return StmtError();
  4922. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4923. if (Pair.first && DirName.getName() && !DependentHint) {
  4924. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4925. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4926. if (HintLoc.isValid()) {
  4927. Diag(HintLoc, diag::note_omp_critical_hint_here)
  4928. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  4929. } else
  4930. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  4931. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  4932. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  4933. << 1
  4934. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  4935. /*Radix=*/10, /*Signed=*/false);
  4936. } else
  4937. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  4938. }
  4939. }
  4940. getCurFunction()->setHasBranchProtectedScope();
  4941. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  4942. Clauses, AStmt);
  4943. if (!Pair.first && DirName.getName() && !DependentHint)
  4944. DSAStack->addCriticalWithHint(Dir, Hint);
  4945. return Dir;
  4946. }
  4947. StmtResult Sema::ActOnOpenMPParallelForDirective(
  4948. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4949. SourceLocation EndLoc,
  4950. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4951. if (!AStmt)
  4952. return StmtError();
  4953. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4954. // 1.2.2 OpenMP Language Terminology
  4955. // Structured block - An executable statement with a single entry at the
  4956. // top and a single exit at the bottom.
  4957. // The point of exit cannot be a branch out of the structured block.
  4958. // longjmp() and throw() must not violate the entry/exit criteria.
  4959. CS->getCapturedDecl()->setNothrow();
  4960. OMPLoopDirective::HelperExprs B;
  4961. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4962. // define the nested loops number.
  4963. unsigned NestedLoopCount =
  4964. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  4965. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4966. VarsWithImplicitDSA, B);
  4967. if (NestedLoopCount == 0)
  4968. return StmtError();
  4969. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4970. "omp parallel for loop exprs were not built");
  4971. if (!CurContext->isDependentContext()) {
  4972. // Finalize the clauses that need pre-built expressions for CodeGen.
  4973. for (auto C : Clauses) {
  4974. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  4975. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4976. B.NumIterations, *this, CurScope,
  4977. DSAStack))
  4978. return StmtError();
  4979. }
  4980. }
  4981. getCurFunction()->setHasBranchProtectedScope();
  4982. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  4983. NestedLoopCount, Clauses, AStmt, B,
  4984. DSAStack->isCancelRegion());
  4985. }
  4986. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  4987. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4988. SourceLocation EndLoc,
  4989. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4990. if (!AStmt)
  4991. return StmtError();
  4992. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4993. // 1.2.2 OpenMP Language Terminology
  4994. // Structured block - An executable statement with a single entry at the
  4995. // top and a single exit at the bottom.
  4996. // The point of exit cannot be a branch out of the structured block.
  4997. // longjmp() and throw() must not violate the entry/exit criteria.
  4998. CS->getCapturedDecl()->setNothrow();
  4999. OMPLoopDirective::HelperExprs B;
  5000. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5001. // define the nested loops number.
  5002. unsigned NestedLoopCount =
  5003. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5004. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5005. VarsWithImplicitDSA, B);
  5006. if (NestedLoopCount == 0)
  5007. return StmtError();
  5008. if (!CurContext->isDependentContext()) {
  5009. // Finalize the clauses that need pre-built expressions for CodeGen.
  5010. for (auto C : Clauses) {
  5011. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5012. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5013. B.NumIterations, *this, CurScope,
  5014. DSAStack))
  5015. return StmtError();
  5016. }
  5017. }
  5018. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5019. return StmtError();
  5020. getCurFunction()->setHasBranchProtectedScope();
  5021. return OMPParallelForSimdDirective::Create(
  5022. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5023. }
  5024. StmtResult
  5025. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5026. Stmt *AStmt, SourceLocation StartLoc,
  5027. SourceLocation EndLoc) {
  5028. if (!AStmt)
  5029. return StmtError();
  5030. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5031. auto BaseStmt = AStmt;
  5032. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5033. BaseStmt = CS->getCapturedStmt();
  5034. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5035. auto S = C->children();
  5036. if (S.begin() == S.end())
  5037. return StmtError();
  5038. // All associated statements must be '#pragma omp section' except for
  5039. // the first one.
  5040. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5041. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5042. if (SectionStmt)
  5043. Diag(SectionStmt->getLocStart(),
  5044. diag::err_omp_parallel_sections_substmt_not_section);
  5045. return StmtError();
  5046. }
  5047. cast<OMPSectionDirective>(SectionStmt)
  5048. ->setHasCancel(DSAStack->isCancelRegion());
  5049. }
  5050. } else {
  5051. Diag(AStmt->getLocStart(),
  5052. diag::err_omp_parallel_sections_not_compound_stmt);
  5053. return StmtError();
  5054. }
  5055. getCurFunction()->setHasBranchProtectedScope();
  5056. return OMPParallelSectionsDirective::Create(
  5057. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5058. }
  5059. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5060. Stmt *AStmt, SourceLocation StartLoc,
  5061. SourceLocation EndLoc) {
  5062. if (!AStmt)
  5063. return StmtError();
  5064. auto *CS = cast<CapturedStmt>(AStmt);
  5065. // 1.2.2 OpenMP Language Terminology
  5066. // Structured block - An executable statement with a single entry at the
  5067. // top and a single exit at the bottom.
  5068. // The point of exit cannot be a branch out of the structured block.
  5069. // longjmp() and throw() must not violate the entry/exit criteria.
  5070. CS->getCapturedDecl()->setNothrow();
  5071. getCurFunction()->setHasBranchProtectedScope();
  5072. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5073. DSAStack->isCancelRegion());
  5074. }
  5075. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5076. SourceLocation EndLoc) {
  5077. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5078. }
  5079. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5080. SourceLocation EndLoc) {
  5081. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5082. }
  5083. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5084. SourceLocation EndLoc) {
  5085. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5086. }
  5087. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5088. Stmt *AStmt,
  5089. SourceLocation StartLoc,
  5090. SourceLocation EndLoc) {
  5091. if (!AStmt)
  5092. return StmtError();
  5093. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5094. getCurFunction()->setHasBranchProtectedScope();
  5095. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5096. AStmt,
  5097. DSAStack->getTaskgroupReductionRef());
  5098. }
  5099. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5100. SourceLocation StartLoc,
  5101. SourceLocation EndLoc) {
  5102. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5103. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5104. }
  5105. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5106. Stmt *AStmt,
  5107. SourceLocation StartLoc,
  5108. SourceLocation EndLoc) {
  5109. OMPClause *DependFound = nullptr;
  5110. OMPClause *DependSourceClause = nullptr;
  5111. OMPClause *DependSinkClause = nullptr;
  5112. bool ErrorFound = false;
  5113. OMPThreadsClause *TC = nullptr;
  5114. OMPSIMDClause *SC = nullptr;
  5115. for (auto *C : Clauses) {
  5116. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5117. DependFound = C;
  5118. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5119. if (DependSourceClause) {
  5120. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  5121. << getOpenMPDirectiveName(OMPD_ordered)
  5122. << getOpenMPClauseName(OMPC_depend) << 2;
  5123. ErrorFound = true;
  5124. } else
  5125. DependSourceClause = C;
  5126. if (DependSinkClause) {
  5127. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5128. << 0;
  5129. ErrorFound = true;
  5130. }
  5131. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5132. if (DependSourceClause) {
  5133. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  5134. << 1;
  5135. ErrorFound = true;
  5136. }
  5137. DependSinkClause = C;
  5138. }
  5139. } else if (C->getClauseKind() == OMPC_threads)
  5140. TC = cast<OMPThreadsClause>(C);
  5141. else if (C->getClauseKind() == OMPC_simd)
  5142. SC = cast<OMPSIMDClause>(C);
  5143. }
  5144. if (!ErrorFound && !SC &&
  5145. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5146. // OpenMP [2.8.1,simd Construct, Restrictions]
  5147. // An ordered construct with the simd clause is the only OpenMP construct
  5148. // that can appear in the simd region.
  5149. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5150. ErrorFound = true;
  5151. } else if (DependFound && (TC || SC)) {
  5152. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  5153. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5154. ErrorFound = true;
  5155. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  5156. Diag(DependFound->getLocStart(),
  5157. diag::err_omp_ordered_directive_without_param);
  5158. ErrorFound = true;
  5159. } else if (TC || Clauses.empty()) {
  5160. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  5161. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  5162. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5163. << (TC != nullptr);
  5164. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  5165. ErrorFound = true;
  5166. }
  5167. }
  5168. if ((!AStmt && !DependFound) || ErrorFound)
  5169. return StmtError();
  5170. if (AStmt) {
  5171. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5172. getCurFunction()->setHasBranchProtectedScope();
  5173. }
  5174. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5175. }
  5176. namespace {
  5177. /// \brief Helper class for checking expression in 'omp atomic [update]'
  5178. /// construct.
  5179. class OpenMPAtomicUpdateChecker {
  5180. /// \brief Error results for atomic update expressions.
  5181. enum ExprAnalysisErrorCode {
  5182. /// \brief A statement is not an expression statement.
  5183. NotAnExpression,
  5184. /// \brief Expression is not builtin binary or unary operation.
  5185. NotABinaryOrUnaryExpression,
  5186. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  5187. NotAnUnaryIncDecExpression,
  5188. /// \brief An expression is not of scalar type.
  5189. NotAScalarType,
  5190. /// \brief A binary operation is not an assignment operation.
  5191. NotAnAssignmentOp,
  5192. /// \brief RHS part of the binary operation is not a binary expression.
  5193. NotABinaryExpression,
  5194. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  5195. /// expression.
  5196. NotABinaryOperator,
  5197. /// \brief RHS binary operation does not have reference to the updated LHS
  5198. /// part.
  5199. NotAnUpdateExpression,
  5200. /// \brief No errors is found.
  5201. NoError
  5202. };
  5203. /// \brief Reference to Sema.
  5204. Sema &SemaRef;
  5205. /// \brief A location for note diagnostics (when error is found).
  5206. SourceLocation NoteLoc;
  5207. /// \brief 'x' lvalue part of the source atomic expression.
  5208. Expr *X;
  5209. /// \brief 'expr' rvalue part of the source atomic expression.
  5210. Expr *E;
  5211. /// \brief Helper expression of the form
  5212. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5213. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5214. Expr *UpdateExpr;
  5215. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  5216. /// important for non-associative operations.
  5217. bool IsXLHSInRHSPart;
  5218. BinaryOperatorKind Op;
  5219. SourceLocation OpLoc;
  5220. /// \brief true if the source expression is a postfix unary operation, false
  5221. /// if it is a prefix unary operation.
  5222. bool IsPostfixUpdate;
  5223. public:
  5224. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  5225. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  5226. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  5227. /// \brief Check specified statement that it is suitable for 'atomic update'
  5228. /// constructs and extract 'x', 'expr' and Operation from the original
  5229. /// expression. If DiagId and NoteId == 0, then only check is performed
  5230. /// without error notification.
  5231. /// \param DiagId Diagnostic which should be emitted if error is found.
  5232. /// \param NoteId Diagnostic note for the main error message.
  5233. /// \return true if statement is not an update expression, false otherwise.
  5234. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  5235. /// \brief Return the 'x' lvalue part of the source atomic expression.
  5236. Expr *getX() const { return X; }
  5237. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  5238. Expr *getExpr() const { return E; }
  5239. /// \brief Return the update expression used in calculation of the updated
  5240. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  5241. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  5242. Expr *getUpdateExpr() const { return UpdateExpr; }
  5243. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  5244. /// false otherwise.
  5245. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  5246. /// \brief true if the source expression is a postfix unary operation, false
  5247. /// if it is a prefix unary operation.
  5248. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  5249. private:
  5250. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  5251. unsigned NoteId = 0);
  5252. };
  5253. } // namespace
  5254. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  5255. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  5256. ExprAnalysisErrorCode ErrorFound = NoError;
  5257. SourceLocation ErrorLoc, NoteLoc;
  5258. SourceRange ErrorRange, NoteRange;
  5259. // Allowed constructs are:
  5260. // x = x binop expr;
  5261. // x = expr binop x;
  5262. if (AtomicBinOp->getOpcode() == BO_Assign) {
  5263. X = AtomicBinOp->getLHS();
  5264. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  5265. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  5266. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  5267. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  5268. AtomicInnerBinOp->isBitwiseOp()) {
  5269. Op = AtomicInnerBinOp->getOpcode();
  5270. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  5271. auto *LHS = AtomicInnerBinOp->getLHS();
  5272. auto *RHS = AtomicInnerBinOp->getRHS();
  5273. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  5274. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  5275. /*Canonical=*/true);
  5276. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  5277. /*Canonical=*/true);
  5278. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  5279. /*Canonical=*/true);
  5280. if (XId == LHSId) {
  5281. E = RHS;
  5282. IsXLHSInRHSPart = true;
  5283. } else if (XId == RHSId) {
  5284. E = LHS;
  5285. IsXLHSInRHSPart = false;
  5286. } else {
  5287. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5288. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5289. NoteLoc = X->getExprLoc();
  5290. NoteRange = X->getSourceRange();
  5291. ErrorFound = NotAnUpdateExpression;
  5292. }
  5293. } else {
  5294. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  5295. ErrorRange = AtomicInnerBinOp->getSourceRange();
  5296. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  5297. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5298. ErrorFound = NotABinaryOperator;
  5299. }
  5300. } else {
  5301. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  5302. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  5303. ErrorFound = NotABinaryExpression;
  5304. }
  5305. } else {
  5306. ErrorLoc = AtomicBinOp->getExprLoc();
  5307. ErrorRange = AtomicBinOp->getSourceRange();
  5308. NoteLoc = AtomicBinOp->getOperatorLoc();
  5309. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5310. ErrorFound = NotAnAssignmentOp;
  5311. }
  5312. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5313. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5314. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5315. return true;
  5316. } else if (SemaRef.CurContext->isDependentContext())
  5317. E = X = UpdateExpr = nullptr;
  5318. return ErrorFound != NoError;
  5319. }
  5320. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  5321. unsigned NoteId) {
  5322. ExprAnalysisErrorCode ErrorFound = NoError;
  5323. SourceLocation ErrorLoc, NoteLoc;
  5324. SourceRange ErrorRange, NoteRange;
  5325. // Allowed constructs are:
  5326. // x++;
  5327. // x--;
  5328. // ++x;
  5329. // --x;
  5330. // x binop= expr;
  5331. // x = x binop expr;
  5332. // x = expr binop x;
  5333. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  5334. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  5335. if (AtomicBody->getType()->isScalarType() ||
  5336. AtomicBody->isInstantiationDependent()) {
  5337. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  5338. AtomicBody->IgnoreParenImpCasts())) {
  5339. // Check for Compound Assignment Operation
  5340. Op = BinaryOperator::getOpForCompoundAssignment(
  5341. AtomicCompAssignOp->getOpcode());
  5342. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  5343. E = AtomicCompAssignOp->getRHS();
  5344. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  5345. IsXLHSInRHSPart = true;
  5346. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  5347. AtomicBody->IgnoreParenImpCasts())) {
  5348. // Check for Binary Operation
  5349. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  5350. return true;
  5351. } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  5352. AtomicBody->IgnoreParenImpCasts())) {
  5353. // Check for Unary Operation
  5354. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  5355. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  5356. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  5357. OpLoc = AtomicUnaryOp->getOperatorLoc();
  5358. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  5359. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  5360. IsXLHSInRHSPart = true;
  5361. } else {
  5362. ErrorFound = NotAnUnaryIncDecExpression;
  5363. ErrorLoc = AtomicUnaryOp->getExprLoc();
  5364. ErrorRange = AtomicUnaryOp->getSourceRange();
  5365. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  5366. NoteRange = SourceRange(NoteLoc, NoteLoc);
  5367. }
  5368. } else if (!AtomicBody->isInstantiationDependent()) {
  5369. ErrorFound = NotABinaryOrUnaryExpression;
  5370. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  5371. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  5372. }
  5373. } else {
  5374. ErrorFound = NotAScalarType;
  5375. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  5376. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5377. }
  5378. } else {
  5379. ErrorFound = NotAnExpression;
  5380. NoteLoc = ErrorLoc = S->getLocStart();
  5381. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5382. }
  5383. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  5384. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  5385. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  5386. return true;
  5387. } else if (SemaRef.CurContext->isDependentContext())
  5388. E = X = UpdateExpr = nullptr;
  5389. if (ErrorFound == NoError && E && X) {
  5390. // Build an update expression of form 'OpaqueValueExpr(x) binop
  5391. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  5392. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  5393. auto *OVEX = new (SemaRef.getASTContext())
  5394. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  5395. auto *OVEExpr = new (SemaRef.getASTContext())
  5396. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  5397. auto Update =
  5398. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  5399. IsXLHSInRHSPart ? OVEExpr : OVEX);
  5400. if (Update.isInvalid())
  5401. return true;
  5402. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  5403. Sema::AA_Casting);
  5404. if (Update.isInvalid())
  5405. return true;
  5406. UpdateExpr = Update.get();
  5407. }
  5408. return ErrorFound != NoError;
  5409. }
  5410. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  5411. Stmt *AStmt,
  5412. SourceLocation StartLoc,
  5413. SourceLocation EndLoc) {
  5414. if (!AStmt)
  5415. return StmtError();
  5416. auto *CS = cast<CapturedStmt>(AStmt);
  5417. // 1.2.2 OpenMP Language Terminology
  5418. // Structured block - An executable statement with a single entry at the
  5419. // top and a single exit at the bottom.
  5420. // The point of exit cannot be a branch out of the structured block.
  5421. // longjmp() and throw() must not violate the entry/exit criteria.
  5422. OpenMPClauseKind AtomicKind = OMPC_unknown;
  5423. SourceLocation AtomicKindLoc;
  5424. for (auto *C : Clauses) {
  5425. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  5426. C->getClauseKind() == OMPC_update ||
  5427. C->getClauseKind() == OMPC_capture) {
  5428. if (AtomicKind != OMPC_unknown) {
  5429. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  5430. << SourceRange(C->getLocStart(), C->getLocEnd());
  5431. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  5432. << getOpenMPClauseName(AtomicKind);
  5433. } else {
  5434. AtomicKind = C->getClauseKind();
  5435. AtomicKindLoc = C->getLocStart();
  5436. }
  5437. }
  5438. }
  5439. auto Body = CS->getCapturedStmt();
  5440. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  5441. Body = EWC->getSubExpr();
  5442. Expr *X = nullptr;
  5443. Expr *V = nullptr;
  5444. Expr *E = nullptr;
  5445. Expr *UE = nullptr;
  5446. bool IsXLHSInRHSPart = false;
  5447. bool IsPostfixUpdate = false;
  5448. // OpenMP [2.12.6, atomic Construct]
  5449. // In the next expressions:
  5450. // * x and v (as applicable) are both l-value expressions with scalar type.
  5451. // * During the execution of an atomic region, multiple syntactic
  5452. // occurrences of x must designate the same storage location.
  5453. // * Neither of v and expr (as applicable) may access the storage location
  5454. // designated by x.
  5455. // * Neither of x and expr (as applicable) may access the storage location
  5456. // designated by v.
  5457. // * expr is an expression with scalar type.
  5458. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  5459. // * binop, binop=, ++, and -- are not overloaded operators.
  5460. // * The expression x binop expr must be numerically equivalent to x binop
  5461. // (expr). This requirement is satisfied if the operators in expr have
  5462. // precedence greater than binop, or by using parentheses around expr or
  5463. // subexpressions of expr.
  5464. // * The expression expr binop x must be numerically equivalent to (expr)
  5465. // binop x. This requirement is satisfied if the operators in expr have
  5466. // precedence equal to or greater than binop, or by using parentheses around
  5467. // expr or subexpressions of expr.
  5468. // * For forms that allow multiple occurrences of x, the number of times
  5469. // that x is evaluated is unspecified.
  5470. if (AtomicKind == OMPC_read) {
  5471. enum {
  5472. NotAnExpression,
  5473. NotAnAssignmentOp,
  5474. NotAScalarType,
  5475. NotAnLValue,
  5476. NoError
  5477. } ErrorFound = NoError;
  5478. SourceLocation ErrorLoc, NoteLoc;
  5479. SourceRange ErrorRange, NoteRange;
  5480. // If clause is read:
  5481. // v = x;
  5482. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5483. auto *AtomicBinOp =
  5484. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5485. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5486. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5487. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  5488. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5489. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  5490. if (!X->isLValue() || !V->isLValue()) {
  5491. auto NotLValueExpr = X->isLValue() ? V : X;
  5492. ErrorFound = NotAnLValue;
  5493. ErrorLoc = AtomicBinOp->getExprLoc();
  5494. ErrorRange = AtomicBinOp->getSourceRange();
  5495. NoteLoc = NotLValueExpr->getExprLoc();
  5496. NoteRange = NotLValueExpr->getSourceRange();
  5497. }
  5498. } else if (!X->isInstantiationDependent() ||
  5499. !V->isInstantiationDependent()) {
  5500. auto NotScalarExpr =
  5501. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5502. ? V
  5503. : X;
  5504. ErrorFound = NotAScalarType;
  5505. ErrorLoc = AtomicBinOp->getExprLoc();
  5506. ErrorRange = AtomicBinOp->getSourceRange();
  5507. NoteLoc = NotScalarExpr->getExprLoc();
  5508. NoteRange = NotScalarExpr->getSourceRange();
  5509. }
  5510. } else if (!AtomicBody->isInstantiationDependent()) {
  5511. ErrorFound = NotAnAssignmentOp;
  5512. ErrorLoc = AtomicBody->getExprLoc();
  5513. ErrorRange = AtomicBody->getSourceRange();
  5514. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5515. : AtomicBody->getExprLoc();
  5516. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5517. : AtomicBody->getSourceRange();
  5518. }
  5519. } else {
  5520. ErrorFound = NotAnExpression;
  5521. NoteLoc = ErrorLoc = Body->getLocStart();
  5522. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5523. }
  5524. if (ErrorFound != NoError) {
  5525. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5526. << ErrorRange;
  5527. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5528. << NoteRange;
  5529. return StmtError();
  5530. } else if (CurContext->isDependentContext())
  5531. V = X = nullptr;
  5532. } else if (AtomicKind == OMPC_write) {
  5533. enum {
  5534. NotAnExpression,
  5535. NotAnAssignmentOp,
  5536. NotAScalarType,
  5537. NotAnLValue,
  5538. NoError
  5539. } ErrorFound = NoError;
  5540. SourceLocation ErrorLoc, NoteLoc;
  5541. SourceRange ErrorRange, NoteRange;
  5542. // If clause is write:
  5543. // x = expr;
  5544. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5545. auto *AtomicBinOp =
  5546. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5547. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5548. X = AtomicBinOp->getLHS();
  5549. E = AtomicBinOp->getRHS();
  5550. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5551. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5552. if (!X->isLValue()) {
  5553. ErrorFound = NotAnLValue;
  5554. ErrorLoc = AtomicBinOp->getExprLoc();
  5555. ErrorRange = AtomicBinOp->getSourceRange();
  5556. NoteLoc = X->getExprLoc();
  5557. NoteRange = X->getSourceRange();
  5558. }
  5559. } else if (!X->isInstantiationDependent() ||
  5560. !E->isInstantiationDependent()) {
  5561. auto NotScalarExpr =
  5562. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5563. ? E
  5564. : X;
  5565. ErrorFound = NotAScalarType;
  5566. ErrorLoc = AtomicBinOp->getExprLoc();
  5567. ErrorRange = AtomicBinOp->getSourceRange();
  5568. NoteLoc = NotScalarExpr->getExprLoc();
  5569. NoteRange = NotScalarExpr->getSourceRange();
  5570. }
  5571. } else if (!AtomicBody->isInstantiationDependent()) {
  5572. ErrorFound = NotAnAssignmentOp;
  5573. ErrorLoc = AtomicBody->getExprLoc();
  5574. ErrorRange = AtomicBody->getSourceRange();
  5575. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5576. : AtomicBody->getExprLoc();
  5577. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5578. : AtomicBody->getSourceRange();
  5579. }
  5580. } else {
  5581. ErrorFound = NotAnExpression;
  5582. NoteLoc = ErrorLoc = Body->getLocStart();
  5583. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5584. }
  5585. if (ErrorFound != NoError) {
  5586. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5587. << ErrorRange;
  5588. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5589. << NoteRange;
  5590. return StmtError();
  5591. } else if (CurContext->isDependentContext())
  5592. E = X = nullptr;
  5593. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5594. // If clause is update:
  5595. // x++;
  5596. // x--;
  5597. // ++x;
  5598. // --x;
  5599. // x binop= expr;
  5600. // x = x binop expr;
  5601. // x = expr binop x;
  5602. OpenMPAtomicUpdateChecker Checker(*this);
  5603. if (Checker.checkStatement(
  5604. Body, (AtomicKind == OMPC_update)
  5605. ? diag::err_omp_atomic_update_not_expression_statement
  5606. : diag::err_omp_atomic_not_expression_statement,
  5607. diag::note_omp_atomic_update))
  5608. return StmtError();
  5609. if (!CurContext->isDependentContext()) {
  5610. E = Checker.getExpr();
  5611. X = Checker.getX();
  5612. UE = Checker.getUpdateExpr();
  5613. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5614. }
  5615. } else if (AtomicKind == OMPC_capture) {
  5616. enum {
  5617. NotAnAssignmentOp,
  5618. NotACompoundStatement,
  5619. NotTwoSubstatements,
  5620. NotASpecificExpression,
  5621. NoError
  5622. } ErrorFound = NoError;
  5623. SourceLocation ErrorLoc, NoteLoc;
  5624. SourceRange ErrorRange, NoteRange;
  5625. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5626. // If clause is a capture:
  5627. // v = x++;
  5628. // v = x--;
  5629. // v = ++x;
  5630. // v = --x;
  5631. // v = x binop= expr;
  5632. // v = x = x binop expr;
  5633. // v = x = expr binop x;
  5634. auto *AtomicBinOp =
  5635. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5636. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5637. V = AtomicBinOp->getLHS();
  5638. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5639. OpenMPAtomicUpdateChecker Checker(*this);
  5640. if (Checker.checkStatement(
  5641. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5642. diag::note_omp_atomic_update))
  5643. return StmtError();
  5644. E = Checker.getExpr();
  5645. X = Checker.getX();
  5646. UE = Checker.getUpdateExpr();
  5647. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5648. IsPostfixUpdate = Checker.isPostfixUpdate();
  5649. } else if (!AtomicBody->isInstantiationDependent()) {
  5650. ErrorLoc = AtomicBody->getExprLoc();
  5651. ErrorRange = AtomicBody->getSourceRange();
  5652. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5653. : AtomicBody->getExprLoc();
  5654. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5655. : AtomicBody->getSourceRange();
  5656. ErrorFound = NotAnAssignmentOp;
  5657. }
  5658. if (ErrorFound != NoError) {
  5659. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5660. << ErrorRange;
  5661. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5662. return StmtError();
  5663. } else if (CurContext->isDependentContext()) {
  5664. UE = V = E = X = nullptr;
  5665. }
  5666. } else {
  5667. // If clause is a capture:
  5668. // { v = x; x = expr; }
  5669. // { v = x; x++; }
  5670. // { v = x; x--; }
  5671. // { v = x; ++x; }
  5672. // { v = x; --x; }
  5673. // { v = x; x binop= expr; }
  5674. // { v = x; x = x binop expr; }
  5675. // { v = x; x = expr binop x; }
  5676. // { x++; v = x; }
  5677. // { x--; v = x; }
  5678. // { ++x; v = x; }
  5679. // { --x; v = x; }
  5680. // { x binop= expr; v = x; }
  5681. // { x = x binop expr; v = x; }
  5682. // { x = expr binop x; v = x; }
  5683. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5684. // Check that this is { expr1; expr2; }
  5685. if (CS->size() == 2) {
  5686. auto *First = CS->body_front();
  5687. auto *Second = CS->body_back();
  5688. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5689. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5690. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5691. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5692. // Need to find what subexpression is 'v' and what is 'x'.
  5693. OpenMPAtomicUpdateChecker Checker(*this);
  5694. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5695. BinaryOperator *BinOp = nullptr;
  5696. if (IsUpdateExprFound) {
  5697. BinOp = dyn_cast<BinaryOperator>(First);
  5698. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5699. }
  5700. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5701. // { v = x; x++; }
  5702. // { v = x; x--; }
  5703. // { v = x; ++x; }
  5704. // { v = x; --x; }
  5705. // { v = x; x binop= expr; }
  5706. // { v = x; x = x binop expr; }
  5707. // { v = x; x = expr binop x; }
  5708. // Check that the first expression has form v = x.
  5709. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5710. llvm::FoldingSetNodeID XId, PossibleXId;
  5711. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5712. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5713. IsUpdateExprFound = XId == PossibleXId;
  5714. if (IsUpdateExprFound) {
  5715. V = BinOp->getLHS();
  5716. X = Checker.getX();
  5717. E = Checker.getExpr();
  5718. UE = Checker.getUpdateExpr();
  5719. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5720. IsPostfixUpdate = true;
  5721. }
  5722. }
  5723. if (!IsUpdateExprFound) {
  5724. IsUpdateExprFound = !Checker.checkStatement(First);
  5725. BinOp = nullptr;
  5726. if (IsUpdateExprFound) {
  5727. BinOp = dyn_cast<BinaryOperator>(Second);
  5728. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5729. }
  5730. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  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. // Check that the second expression has form v = x.
  5739. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5740. llvm::FoldingSetNodeID XId, PossibleXId;
  5741. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5742. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5743. IsUpdateExprFound = XId == PossibleXId;
  5744. if (IsUpdateExprFound) {
  5745. V = BinOp->getLHS();
  5746. X = Checker.getX();
  5747. E = Checker.getExpr();
  5748. UE = Checker.getUpdateExpr();
  5749. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5750. IsPostfixUpdate = false;
  5751. }
  5752. }
  5753. }
  5754. if (!IsUpdateExprFound) {
  5755. // { v = x; x = expr; }
  5756. auto *FirstExpr = dyn_cast<Expr>(First);
  5757. auto *SecondExpr = dyn_cast<Expr>(Second);
  5758. if (!FirstExpr || !SecondExpr ||
  5759. !(FirstExpr->isInstantiationDependent() ||
  5760. SecondExpr->isInstantiationDependent())) {
  5761. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5762. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5763. ErrorFound = NotAnAssignmentOp;
  5764. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5765. : First->getLocStart();
  5766. NoteRange = ErrorRange = FirstBinOp
  5767. ? FirstBinOp->getSourceRange()
  5768. : SourceRange(ErrorLoc, ErrorLoc);
  5769. } else {
  5770. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5771. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5772. ErrorFound = NotAnAssignmentOp;
  5773. NoteLoc = ErrorLoc = SecondBinOp
  5774. ? SecondBinOp->getOperatorLoc()
  5775. : Second->getLocStart();
  5776. NoteRange = ErrorRange =
  5777. SecondBinOp ? SecondBinOp->getSourceRange()
  5778. : SourceRange(ErrorLoc, ErrorLoc);
  5779. } else {
  5780. auto *PossibleXRHSInFirst =
  5781. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5782. auto *PossibleXLHSInSecond =
  5783. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5784. llvm::FoldingSetNodeID X1Id, X2Id;
  5785. PossibleXRHSInFirst->Profile(X1Id, Context,
  5786. /*Canonical=*/true);
  5787. PossibleXLHSInSecond->Profile(X2Id, Context,
  5788. /*Canonical=*/true);
  5789. IsUpdateExprFound = X1Id == X2Id;
  5790. if (IsUpdateExprFound) {
  5791. V = FirstBinOp->getLHS();
  5792. X = SecondBinOp->getLHS();
  5793. E = SecondBinOp->getRHS();
  5794. UE = nullptr;
  5795. IsXLHSInRHSPart = false;
  5796. IsPostfixUpdate = true;
  5797. } else {
  5798. ErrorFound = NotASpecificExpression;
  5799. ErrorLoc = FirstBinOp->getExprLoc();
  5800. ErrorRange = FirstBinOp->getSourceRange();
  5801. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5802. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5803. }
  5804. }
  5805. }
  5806. }
  5807. }
  5808. } else {
  5809. NoteLoc = ErrorLoc = Body->getLocStart();
  5810. NoteRange = ErrorRange =
  5811. SourceRange(Body->getLocStart(), Body->getLocStart());
  5812. ErrorFound = NotTwoSubstatements;
  5813. }
  5814. } else {
  5815. NoteLoc = ErrorLoc = Body->getLocStart();
  5816. NoteRange = ErrorRange =
  5817. SourceRange(Body->getLocStart(), Body->getLocStart());
  5818. ErrorFound = NotACompoundStatement;
  5819. }
  5820. if (ErrorFound != NoError) {
  5821. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5822. << ErrorRange;
  5823. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5824. return StmtError();
  5825. } else if (CurContext->isDependentContext()) {
  5826. UE = V = E = X = nullptr;
  5827. }
  5828. }
  5829. }
  5830. getCurFunction()->setHasBranchProtectedScope();
  5831. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5832. X, V, E, UE, IsXLHSInRHSPart,
  5833. IsPostfixUpdate);
  5834. }
  5835. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5836. Stmt *AStmt,
  5837. SourceLocation StartLoc,
  5838. SourceLocation EndLoc) {
  5839. if (!AStmt)
  5840. return StmtError();
  5841. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5842. // 1.2.2 OpenMP Language Terminology
  5843. // Structured block - An executable statement with a single entry at the
  5844. // top and a single exit at the bottom.
  5845. // The point of exit cannot be a branch out of the structured block.
  5846. // longjmp() and throw() must not violate the entry/exit criteria.
  5847. CS->getCapturedDecl()->setNothrow();
  5848. // OpenMP [2.16, Nesting of Regions]
  5849. // If specified, a teams construct must be contained within a target
  5850. // construct. That target construct must contain no statements or directives
  5851. // outside of the teams construct.
  5852. if (DSAStack->hasInnerTeamsRegion()) {
  5853. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5854. bool OMPTeamsFound = true;
  5855. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5856. auto I = CS->body_begin();
  5857. while (I != CS->body_end()) {
  5858. auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  5859. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5860. OMPTeamsFound = false;
  5861. break;
  5862. }
  5863. ++I;
  5864. }
  5865. assert(I != CS->body_end() && "Not found statement");
  5866. S = *I;
  5867. } else {
  5868. auto *OED = dyn_cast<OMPExecutableDirective>(S);
  5869. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  5870. }
  5871. if (!OMPTeamsFound) {
  5872. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5873. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5874. diag::note_omp_nested_teams_construct_here);
  5875. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5876. << isa<OMPExecutableDirective>(S);
  5877. return StmtError();
  5878. }
  5879. }
  5880. getCurFunction()->setHasBranchProtectedScope();
  5881. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5882. }
  5883. StmtResult
  5884. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5885. Stmt *AStmt, SourceLocation StartLoc,
  5886. SourceLocation EndLoc) {
  5887. if (!AStmt)
  5888. return StmtError();
  5889. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5890. // 1.2.2 OpenMP Language Terminology
  5891. // Structured block - An executable statement with a single entry at the
  5892. // top and a single exit at the bottom.
  5893. // The point of exit cannot be a branch out of the structured block.
  5894. // longjmp() and throw() must not violate the entry/exit criteria.
  5895. CS->getCapturedDecl()->setNothrow();
  5896. getCurFunction()->setHasBranchProtectedScope();
  5897. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5898. AStmt);
  5899. }
  5900. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  5901. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5902. SourceLocation EndLoc,
  5903. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5904. if (!AStmt)
  5905. return StmtError();
  5906. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5907. // 1.2.2 OpenMP Language Terminology
  5908. // Structured block - An executable statement with a single entry at the
  5909. // top and a single exit at the bottom.
  5910. // The point of exit cannot be a branch out of the structured block.
  5911. // longjmp() and throw() must not violate the entry/exit criteria.
  5912. CS->getCapturedDecl()->setNothrow();
  5913. OMPLoopDirective::HelperExprs B;
  5914. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5915. // define the nested loops number.
  5916. unsigned NestedLoopCount =
  5917. CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  5918. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5919. VarsWithImplicitDSA, B);
  5920. if (NestedLoopCount == 0)
  5921. return StmtError();
  5922. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5923. "omp target parallel for loop exprs were not built");
  5924. if (!CurContext->isDependentContext()) {
  5925. // Finalize the clauses that need pre-built expressions for CodeGen.
  5926. for (auto C : Clauses) {
  5927. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5928. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5929. B.NumIterations, *this, CurScope,
  5930. DSAStack))
  5931. return StmtError();
  5932. }
  5933. }
  5934. getCurFunction()->setHasBranchProtectedScope();
  5935. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  5936. NestedLoopCount, Clauses, AStmt,
  5937. B, DSAStack->isCancelRegion());
  5938. }
  5939. /// Check for existence of a map clause in the list of clauses.
  5940. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  5941. const OpenMPClauseKind K) {
  5942. return llvm::any_of(
  5943. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  5944. }
  5945. template <typename... Params>
  5946. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  5947. const Params... ClauseTypes) {
  5948. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  5949. }
  5950. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  5951. Stmt *AStmt,
  5952. SourceLocation StartLoc,
  5953. SourceLocation EndLoc) {
  5954. if (!AStmt)
  5955. return StmtError();
  5956. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5957. // OpenMP [2.10.1, Restrictions, p. 97]
  5958. // At least one map clause must appear on the directive.
  5959. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  5960. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  5961. << "'map' or 'use_device_ptr'"
  5962. << getOpenMPDirectiveName(OMPD_target_data);
  5963. return StmtError();
  5964. }
  5965. getCurFunction()->setHasBranchProtectedScope();
  5966. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5967. AStmt);
  5968. }
  5969. StmtResult
  5970. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  5971. SourceLocation StartLoc,
  5972. SourceLocation EndLoc) {
  5973. // OpenMP [2.10.2, Restrictions, p. 99]
  5974. // At least one map clause must appear on the directive.
  5975. if (!hasClauses(Clauses, OMPC_map)) {
  5976. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  5977. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  5978. return StmtError();
  5979. }
  5980. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
  5981. Clauses);
  5982. }
  5983. StmtResult
  5984. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  5985. SourceLocation StartLoc,
  5986. SourceLocation EndLoc) {
  5987. // OpenMP [2.10.3, Restrictions, p. 102]
  5988. // At least one map clause must appear on the directive.
  5989. if (!hasClauses(Clauses, OMPC_map)) {
  5990. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  5991. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  5992. return StmtError();
  5993. }
  5994. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5995. }
  5996. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  5997. SourceLocation StartLoc,
  5998. SourceLocation EndLoc) {
  5999. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6000. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6001. return StmtError();
  6002. }
  6003. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
  6004. }
  6005. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6006. Stmt *AStmt, SourceLocation StartLoc,
  6007. SourceLocation EndLoc) {
  6008. if (!AStmt)
  6009. return StmtError();
  6010. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6011. // 1.2.2 OpenMP Language Terminology
  6012. // Structured block - An executable statement with a single entry at the
  6013. // top and a single exit at the bottom.
  6014. // The point of exit cannot be a branch out of the structured block.
  6015. // longjmp() and throw() must not violate the entry/exit criteria.
  6016. CS->getCapturedDecl()->setNothrow();
  6017. getCurFunction()->setHasBranchProtectedScope();
  6018. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6019. }
  6020. StmtResult
  6021. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6022. SourceLocation EndLoc,
  6023. OpenMPDirectiveKind CancelRegion) {
  6024. if (DSAStack->isParentNowaitRegion()) {
  6025. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6026. return StmtError();
  6027. }
  6028. if (DSAStack->isParentOrderedRegion()) {
  6029. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6030. return StmtError();
  6031. }
  6032. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6033. CancelRegion);
  6034. }
  6035. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6036. SourceLocation StartLoc,
  6037. SourceLocation EndLoc,
  6038. OpenMPDirectiveKind CancelRegion) {
  6039. if (DSAStack->isParentNowaitRegion()) {
  6040. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6041. return StmtError();
  6042. }
  6043. if (DSAStack->isParentOrderedRegion()) {
  6044. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6045. return StmtError();
  6046. }
  6047. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6048. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6049. CancelRegion);
  6050. }
  6051. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6052. ArrayRef<OMPClause *> Clauses) {
  6053. OMPClause *PrevClause = nullptr;
  6054. bool ErrorFound = false;
  6055. for (auto *C : Clauses) {
  6056. if (C->getClauseKind() == OMPC_grainsize ||
  6057. C->getClauseKind() == OMPC_num_tasks) {
  6058. if (!PrevClause)
  6059. PrevClause = C;
  6060. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6061. S.Diag(C->getLocStart(),
  6062. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6063. << getOpenMPClauseName(C->getClauseKind())
  6064. << getOpenMPClauseName(PrevClause->getClauseKind());
  6065. S.Diag(PrevClause->getLocStart(),
  6066. diag::note_omp_previous_grainsize_num_tasks)
  6067. << getOpenMPClauseName(PrevClause->getClauseKind());
  6068. ErrorFound = true;
  6069. }
  6070. }
  6071. }
  6072. return ErrorFound;
  6073. }
  6074. static bool checkReductionClauseWithNogroup(Sema &S,
  6075. ArrayRef<OMPClause *> Clauses) {
  6076. OMPClause *ReductionClause = nullptr;
  6077. OMPClause *NogroupClause = nullptr;
  6078. for (auto *C : Clauses) {
  6079. if (C->getClauseKind() == OMPC_reduction) {
  6080. ReductionClause = C;
  6081. if (NogroupClause)
  6082. break;
  6083. continue;
  6084. }
  6085. if (C->getClauseKind() == OMPC_nogroup) {
  6086. NogroupClause = C;
  6087. if (ReductionClause)
  6088. break;
  6089. continue;
  6090. }
  6091. }
  6092. if (ReductionClause && NogroupClause) {
  6093. S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
  6094. << SourceRange(NogroupClause->getLocStart(),
  6095. NogroupClause->getLocEnd());
  6096. return true;
  6097. }
  6098. return false;
  6099. }
  6100. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  6101. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6102. SourceLocation EndLoc,
  6103. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6104. if (!AStmt)
  6105. return StmtError();
  6106. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6107. OMPLoopDirective::HelperExprs B;
  6108. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6109. // define the nested loops number.
  6110. unsigned NestedLoopCount =
  6111. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  6112. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6113. VarsWithImplicitDSA, B);
  6114. if (NestedLoopCount == 0)
  6115. return StmtError();
  6116. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6117. "omp for loop exprs were not built");
  6118. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6119. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6120. // not appear on the same taskloop directive.
  6121. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6122. return StmtError();
  6123. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6124. // If a reduction clause is present on the taskloop directive, the nogroup
  6125. // clause must not be specified.
  6126. if (checkReductionClauseWithNogroup(*this, Clauses))
  6127. return StmtError();
  6128. getCurFunction()->setHasBranchProtectedScope();
  6129. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  6130. NestedLoopCount, Clauses, AStmt, B);
  6131. }
  6132. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  6133. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6134. SourceLocation EndLoc,
  6135. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6136. if (!AStmt)
  6137. return StmtError();
  6138. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6139. OMPLoopDirective::HelperExprs B;
  6140. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6141. // define the nested loops number.
  6142. unsigned NestedLoopCount =
  6143. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  6144. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  6145. VarsWithImplicitDSA, B);
  6146. if (NestedLoopCount == 0)
  6147. return StmtError();
  6148. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6149. "omp for loop exprs were not built");
  6150. if (!CurContext->isDependentContext()) {
  6151. // Finalize the clauses that need pre-built expressions for CodeGen.
  6152. for (auto C : Clauses) {
  6153. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6154. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6155. B.NumIterations, *this, CurScope,
  6156. DSAStack))
  6157. return StmtError();
  6158. }
  6159. }
  6160. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6161. // The grainsize clause and num_tasks clause are mutually exclusive and may
  6162. // not appear on the same taskloop directive.
  6163. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  6164. return StmtError();
  6165. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  6166. // If a reduction clause is present on the taskloop directive, the nogroup
  6167. // clause must not be specified.
  6168. if (checkReductionClauseWithNogroup(*this, Clauses))
  6169. return StmtError();
  6170. getCurFunction()->setHasBranchProtectedScope();
  6171. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  6172. NestedLoopCount, Clauses, AStmt, B);
  6173. }
  6174. StmtResult Sema::ActOnOpenMPDistributeDirective(
  6175. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6176. SourceLocation EndLoc,
  6177. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6178. if (!AStmt)
  6179. return StmtError();
  6180. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6181. OMPLoopDirective::HelperExprs B;
  6182. // In presence of clause 'collapse' with number of loops, it will
  6183. // define the nested loops number.
  6184. unsigned NestedLoopCount =
  6185. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  6186. nullptr /*ordered not a clause on distribute*/, AStmt,
  6187. *this, *DSAStack, VarsWithImplicitDSA, B);
  6188. if (NestedLoopCount == 0)
  6189. return StmtError();
  6190. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6191. "omp for loop exprs were not built");
  6192. getCurFunction()->setHasBranchProtectedScope();
  6193. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  6194. NestedLoopCount, Clauses, AStmt, B);
  6195. }
  6196. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  6197. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6198. SourceLocation EndLoc,
  6199. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6200. if (!AStmt)
  6201. return StmtError();
  6202. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6203. // 1.2.2 OpenMP Language Terminology
  6204. // Structured block - An executable statement with a single entry at the
  6205. // top and a single exit at the bottom.
  6206. // The point of exit cannot be a branch out of the structured block.
  6207. // longjmp() and throw() must not violate the entry/exit criteria.
  6208. CS->getCapturedDecl()->setNothrow();
  6209. OMPLoopDirective::HelperExprs B;
  6210. // In presence of clause 'collapse' with number of loops, it will
  6211. // define the nested loops number.
  6212. unsigned NestedLoopCount = CheckOpenMPLoop(
  6213. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6214. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6215. VarsWithImplicitDSA, B);
  6216. if (NestedLoopCount == 0)
  6217. return StmtError();
  6218. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6219. "omp for loop exprs were not built");
  6220. getCurFunction()->setHasBranchProtectedScope();
  6221. return OMPDistributeParallelForDirective::Create(
  6222. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6223. }
  6224. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  6225. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6226. SourceLocation EndLoc,
  6227. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6228. if (!AStmt)
  6229. return StmtError();
  6230. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6231. // 1.2.2 OpenMP Language Terminology
  6232. // Structured block - An executable statement with a single entry at the
  6233. // top and a single exit at the bottom.
  6234. // The point of exit cannot be a branch out of the structured block.
  6235. // longjmp() and throw() must not violate the entry/exit criteria.
  6236. CS->getCapturedDecl()->setNothrow();
  6237. OMPLoopDirective::HelperExprs B;
  6238. // In presence of clause 'collapse' with number of loops, it will
  6239. // define the nested loops number.
  6240. unsigned NestedLoopCount = CheckOpenMPLoop(
  6241. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6242. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6243. VarsWithImplicitDSA, B);
  6244. if (NestedLoopCount == 0)
  6245. return StmtError();
  6246. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6247. "omp for loop exprs were not built");
  6248. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6249. return StmtError();
  6250. getCurFunction()->setHasBranchProtectedScope();
  6251. return OMPDistributeParallelForSimdDirective::Create(
  6252. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6253. }
  6254. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  6255. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6256. SourceLocation EndLoc,
  6257. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6258. if (!AStmt)
  6259. return StmtError();
  6260. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6261. // 1.2.2 OpenMP Language Terminology
  6262. // Structured block - An executable statement with a single entry at the
  6263. // top and a single exit at the bottom.
  6264. // The point of exit cannot be a branch out of the structured block.
  6265. // longjmp() and throw() must not violate the entry/exit criteria.
  6266. CS->getCapturedDecl()->setNothrow();
  6267. OMPLoopDirective::HelperExprs B;
  6268. // In presence of clause 'collapse' with number of loops, it will
  6269. // define the nested loops number.
  6270. unsigned NestedLoopCount =
  6271. CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  6272. nullptr /*ordered not a clause on distribute*/, AStmt,
  6273. *this, *DSAStack, VarsWithImplicitDSA, B);
  6274. if (NestedLoopCount == 0)
  6275. return StmtError();
  6276. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6277. "omp for loop exprs were not built");
  6278. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6279. return StmtError();
  6280. getCurFunction()->setHasBranchProtectedScope();
  6281. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  6282. NestedLoopCount, Clauses, AStmt, B);
  6283. }
  6284. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  6285. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6286. SourceLocation EndLoc,
  6287. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6288. if (!AStmt)
  6289. return StmtError();
  6290. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6291. // 1.2.2 OpenMP Language Terminology
  6292. // Structured block - An executable statement with a single entry at the
  6293. // top and a single exit at the bottom.
  6294. // The point of exit cannot be a branch out of the structured block.
  6295. // longjmp() and throw() must not violate the entry/exit criteria.
  6296. CS->getCapturedDecl()->setNothrow();
  6297. OMPLoopDirective::HelperExprs B;
  6298. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6299. // define the nested loops number.
  6300. unsigned NestedLoopCount = CheckOpenMPLoop(
  6301. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6302. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6303. VarsWithImplicitDSA, B);
  6304. if (NestedLoopCount == 0)
  6305. return StmtError();
  6306. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6307. "omp target parallel for simd loop exprs were not built");
  6308. if (!CurContext->isDependentContext()) {
  6309. // Finalize the clauses that need pre-built expressions for CodeGen.
  6310. for (auto C : Clauses) {
  6311. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6312. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6313. B.NumIterations, *this, CurScope,
  6314. DSAStack))
  6315. return StmtError();
  6316. }
  6317. }
  6318. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6319. return StmtError();
  6320. getCurFunction()->setHasBranchProtectedScope();
  6321. return OMPTargetParallelForSimdDirective::Create(
  6322. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6323. }
  6324. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  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. OMPLoopDirective::HelperExprs B;
  6338. // In presence of clause 'collapse' with number of loops, it will define the
  6339. // nested loops number.
  6340. unsigned NestedLoopCount =
  6341. CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  6342. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6343. VarsWithImplicitDSA, B);
  6344. if (NestedLoopCount == 0)
  6345. return StmtError();
  6346. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6347. "omp target simd loop exprs were not built");
  6348. if (!CurContext->isDependentContext()) {
  6349. // Finalize the clauses that need pre-built expressions for CodeGen.
  6350. for (auto C : Clauses) {
  6351. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6352. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6353. B.NumIterations, *this, CurScope,
  6354. DSAStack))
  6355. return StmtError();
  6356. }
  6357. }
  6358. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6359. return StmtError();
  6360. getCurFunction()->setHasBranchProtectedScope();
  6361. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  6362. NestedLoopCount, Clauses, AStmt, B);
  6363. }
  6364. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  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. OMPLoopDirective::HelperExprs B;
  6378. // In presence of clause 'collapse' with number of loops, it will
  6379. // define the nested loops number.
  6380. unsigned NestedLoopCount =
  6381. CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  6382. nullptr /*ordered not a clause on distribute*/, AStmt,
  6383. *this, *DSAStack, VarsWithImplicitDSA, B);
  6384. if (NestedLoopCount == 0)
  6385. return StmtError();
  6386. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6387. "omp teams distribute loop exprs were not built");
  6388. getCurFunction()->setHasBranchProtectedScope();
  6389. return OMPTeamsDistributeDirective::Create(
  6390. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6391. }
  6392. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  6393. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6394. SourceLocation EndLoc,
  6395. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6396. if (!AStmt)
  6397. return StmtError();
  6398. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6399. // 1.2.2 OpenMP Language Terminology
  6400. // Structured block - An executable statement with a single entry at the
  6401. // top and a single exit at the bottom.
  6402. // The point of exit cannot be a branch out of the structured block.
  6403. // longjmp() and throw() must not violate the entry/exit criteria.
  6404. CS->getCapturedDecl()->setNothrow();
  6405. OMPLoopDirective::HelperExprs B;
  6406. // In presence of clause 'collapse' with number of loops, it will
  6407. // define the nested loops number.
  6408. unsigned NestedLoopCount = CheckOpenMPLoop(
  6409. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6410. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6411. VarsWithImplicitDSA, B);
  6412. if (NestedLoopCount == 0)
  6413. return StmtError();
  6414. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6415. "omp teams distribute simd loop exprs were not built");
  6416. if (!CurContext->isDependentContext()) {
  6417. // Finalize the clauses that need pre-built expressions for CodeGen.
  6418. for (auto C : Clauses) {
  6419. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6420. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6421. B.NumIterations, *this, CurScope,
  6422. DSAStack))
  6423. return StmtError();
  6424. }
  6425. }
  6426. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6427. return StmtError();
  6428. getCurFunction()->setHasBranchProtectedScope();
  6429. return OMPTeamsDistributeSimdDirective::Create(
  6430. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6431. }
  6432. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6433. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6434. SourceLocation EndLoc,
  6435. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6436. if (!AStmt)
  6437. return StmtError();
  6438. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6439. // 1.2.2 OpenMP Language Terminology
  6440. // Structured block - An executable statement with a single entry at the
  6441. // top and a single exit at the bottom.
  6442. // The point of exit cannot be a branch out of the structured block.
  6443. // longjmp() and throw() must not violate the entry/exit criteria.
  6444. CS->getCapturedDecl()->setNothrow();
  6445. OMPLoopDirective::HelperExprs B;
  6446. // In presence of clause 'collapse' with number of loops, it will
  6447. // define the nested loops number.
  6448. auto NestedLoopCount = CheckOpenMPLoop(
  6449. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6450. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6451. VarsWithImplicitDSA, B);
  6452. if (NestedLoopCount == 0)
  6453. return StmtError();
  6454. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6455. "omp for loop exprs were not built");
  6456. if (!CurContext->isDependentContext()) {
  6457. // Finalize the clauses that need pre-built expressions for CodeGen.
  6458. for (auto C : Clauses) {
  6459. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6460. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6461. B.NumIterations, *this, CurScope,
  6462. DSAStack))
  6463. return StmtError();
  6464. }
  6465. }
  6466. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6467. return StmtError();
  6468. getCurFunction()->setHasBranchProtectedScope();
  6469. return OMPTeamsDistributeParallelForSimdDirective::Create(
  6470. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6471. }
  6472. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  6473. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6474. SourceLocation EndLoc,
  6475. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6476. if (!AStmt)
  6477. return StmtError();
  6478. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6479. // 1.2.2 OpenMP Language Terminology
  6480. // Structured block - An executable statement with a single entry at the
  6481. // top and a single exit at the bottom.
  6482. // The point of exit cannot be a branch out of the structured block.
  6483. // longjmp() and throw() must not violate the entry/exit criteria.
  6484. CS->getCapturedDecl()->setNothrow();
  6485. OMPLoopDirective::HelperExprs B;
  6486. // In presence of clause 'collapse' with number of loops, it will
  6487. // define the nested loops number.
  6488. unsigned NestedLoopCount = CheckOpenMPLoop(
  6489. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  6490. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6491. VarsWithImplicitDSA, B);
  6492. if (NestedLoopCount == 0)
  6493. return StmtError();
  6494. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6495. "omp for loop exprs were not built");
  6496. if (!CurContext->isDependentContext()) {
  6497. // Finalize the clauses that need pre-built expressions for CodeGen.
  6498. for (auto C : Clauses) {
  6499. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6500. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6501. B.NumIterations, *this, CurScope,
  6502. DSAStack))
  6503. return StmtError();
  6504. }
  6505. }
  6506. getCurFunction()->setHasBranchProtectedScope();
  6507. return OMPTeamsDistributeParallelForDirective::Create(
  6508. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6509. }
  6510. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6511. Stmt *AStmt,
  6512. SourceLocation StartLoc,
  6513. SourceLocation EndLoc) {
  6514. if (!AStmt)
  6515. return StmtError();
  6516. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6517. // 1.2.2 OpenMP Language Terminology
  6518. // Structured block - An executable statement with a single entry at the
  6519. // top and a single exit at the bottom.
  6520. // The point of exit cannot be a branch out of the structured block.
  6521. // longjmp() and throw() must not violate the entry/exit criteria.
  6522. CS->getCapturedDecl()->setNothrow();
  6523. getCurFunction()->setHasBranchProtectedScope();
  6524. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6525. AStmt);
  6526. }
  6527. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  6528. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6529. SourceLocation EndLoc,
  6530. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6531. if (!AStmt)
  6532. return StmtError();
  6533. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6534. // 1.2.2 OpenMP Language Terminology
  6535. // Structured block - An executable statement with a single entry at the
  6536. // top and a single exit at the bottom.
  6537. // The point of exit cannot be a branch out of the structured block.
  6538. // longjmp() and throw() must not violate the entry/exit criteria.
  6539. CS->getCapturedDecl()->setNothrow();
  6540. OMPLoopDirective::HelperExprs B;
  6541. // In presence of clause 'collapse' with number of loops, it will
  6542. // define the nested loops number.
  6543. auto NestedLoopCount = CheckOpenMPLoop(
  6544. OMPD_target_teams_distribute,
  6545. getCollapseNumberExpr(Clauses),
  6546. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6547. VarsWithImplicitDSA, B);
  6548. if (NestedLoopCount == 0)
  6549. return StmtError();
  6550. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6551. "omp target teams distribute loop exprs were not built");
  6552. getCurFunction()->setHasBranchProtectedScope();
  6553. return OMPTargetTeamsDistributeDirective::Create(
  6554. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6555. }
  6556. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  6557. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6558. SourceLocation EndLoc,
  6559. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6560. if (!AStmt)
  6561. return StmtError();
  6562. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6563. // 1.2.2 OpenMP Language Terminology
  6564. // Structured block - An executable statement with a single entry at the
  6565. // top and a single exit at the bottom.
  6566. // The point of exit cannot be a branch out of the structured block.
  6567. // longjmp() and throw() must not violate the entry/exit criteria.
  6568. CS->getCapturedDecl()->setNothrow();
  6569. OMPLoopDirective::HelperExprs B;
  6570. // In presence of clause 'collapse' with number of loops, it will
  6571. // define the nested loops number.
  6572. auto NestedLoopCount = CheckOpenMPLoop(
  6573. OMPD_target_teams_distribute_parallel_for,
  6574. getCollapseNumberExpr(Clauses),
  6575. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6576. VarsWithImplicitDSA, B);
  6577. if (NestedLoopCount == 0)
  6578. return StmtError();
  6579. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6580. "omp target teams distribute parallel for loop exprs were not built");
  6581. if (!CurContext->isDependentContext()) {
  6582. // Finalize the clauses that need pre-built expressions for CodeGen.
  6583. for (auto C : Clauses) {
  6584. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6585. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6586. B.NumIterations, *this, CurScope,
  6587. DSAStack))
  6588. return StmtError();
  6589. }
  6590. }
  6591. getCurFunction()->setHasBranchProtectedScope();
  6592. return OMPTargetTeamsDistributeParallelForDirective::Create(
  6593. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6594. }
  6595. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  6596. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6597. SourceLocation EndLoc,
  6598. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6599. if (!AStmt)
  6600. return StmtError();
  6601. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  6602. // 1.2.2 OpenMP Language Terminology
  6603. // Structured block - An executable statement with a single entry at the
  6604. // top and a single exit at the bottom.
  6605. // The point of exit cannot be a branch out of the structured block.
  6606. // longjmp() and throw() must not violate the entry/exit criteria.
  6607. CS->getCapturedDecl()->setNothrow();
  6608. OMPLoopDirective::HelperExprs B;
  6609. // In presence of clause 'collapse' with number of loops, it will
  6610. // define the nested loops number.
  6611. auto NestedLoopCount = CheckOpenMPLoop(
  6612. OMPD_target_teams_distribute_parallel_for_simd,
  6613. getCollapseNumberExpr(Clauses),
  6614. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6615. VarsWithImplicitDSA, B);
  6616. if (NestedLoopCount == 0)
  6617. return StmtError();
  6618. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6619. "omp target teams distribute parallel for simd loop exprs were not "
  6620. "built");
  6621. if (!CurContext->isDependentContext()) {
  6622. // Finalize the clauses that need pre-built expressions for CodeGen.
  6623. for (auto C : Clauses) {
  6624. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6625. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6626. B.NumIterations, *this, CurScope,
  6627. DSAStack))
  6628. return StmtError();
  6629. }
  6630. }
  6631. getCurFunction()->setHasBranchProtectedScope();
  6632. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  6633. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6634. }
  6635. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  6636. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6637. SourceLocation EndLoc,
  6638. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  6639. if (!AStmt)
  6640. return StmtError();
  6641. auto *CS = cast<CapturedStmt>(AStmt);
  6642. // 1.2.2 OpenMP Language Terminology
  6643. // Structured block - An executable statement with a single entry at the
  6644. // top and a single exit at the bottom.
  6645. // The point of exit cannot be a branch out of the structured block.
  6646. // longjmp() and throw() must not violate the entry/exit criteria.
  6647. CS->getCapturedDecl()->setNothrow();
  6648. OMPLoopDirective::HelperExprs B;
  6649. // In presence of clause 'collapse' with number of loops, it will
  6650. // define the nested loops number.
  6651. auto NestedLoopCount = CheckOpenMPLoop(
  6652. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  6653. nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
  6654. VarsWithImplicitDSA, B);
  6655. if (NestedLoopCount == 0)
  6656. return StmtError();
  6657. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6658. "omp target teams distribute simd loop exprs were not built");
  6659. getCurFunction()->setHasBranchProtectedScope();
  6660. return OMPTargetTeamsDistributeSimdDirective::Create(
  6661. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6662. }
  6663. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  6664. SourceLocation StartLoc,
  6665. SourceLocation LParenLoc,
  6666. SourceLocation EndLoc) {
  6667. OMPClause *Res = nullptr;
  6668. switch (Kind) {
  6669. case OMPC_final:
  6670. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  6671. break;
  6672. case OMPC_num_threads:
  6673. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6674. break;
  6675. case OMPC_safelen:
  6676. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6677. break;
  6678. case OMPC_simdlen:
  6679. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  6680. break;
  6681. case OMPC_collapse:
  6682. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  6683. break;
  6684. case OMPC_ordered:
  6685. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  6686. break;
  6687. case OMPC_device:
  6688. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  6689. break;
  6690. case OMPC_num_teams:
  6691. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  6692. break;
  6693. case OMPC_thread_limit:
  6694. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  6695. break;
  6696. case OMPC_priority:
  6697. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  6698. break;
  6699. case OMPC_grainsize:
  6700. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  6701. break;
  6702. case OMPC_num_tasks:
  6703. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  6704. break;
  6705. case OMPC_hint:
  6706. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  6707. break;
  6708. case OMPC_if:
  6709. case OMPC_default:
  6710. case OMPC_proc_bind:
  6711. case OMPC_schedule:
  6712. case OMPC_private:
  6713. case OMPC_firstprivate:
  6714. case OMPC_lastprivate:
  6715. case OMPC_shared:
  6716. case OMPC_reduction:
  6717. case OMPC_task_reduction:
  6718. case OMPC_in_reduction:
  6719. case OMPC_linear:
  6720. case OMPC_aligned:
  6721. case OMPC_copyin:
  6722. case OMPC_copyprivate:
  6723. case OMPC_nowait:
  6724. case OMPC_untied:
  6725. case OMPC_mergeable:
  6726. case OMPC_threadprivate:
  6727. case OMPC_flush:
  6728. case OMPC_read:
  6729. case OMPC_write:
  6730. case OMPC_update:
  6731. case OMPC_capture:
  6732. case OMPC_seq_cst:
  6733. case OMPC_depend:
  6734. case OMPC_threads:
  6735. case OMPC_simd:
  6736. case OMPC_map:
  6737. case OMPC_nogroup:
  6738. case OMPC_dist_schedule:
  6739. case OMPC_defaultmap:
  6740. case OMPC_unknown:
  6741. case OMPC_uniform:
  6742. case OMPC_to:
  6743. case OMPC_from:
  6744. case OMPC_use_device_ptr:
  6745. case OMPC_is_device_ptr:
  6746. llvm_unreachable("Clause is not allowed.");
  6747. }
  6748. return Res;
  6749. }
  6750. // An OpenMP directive such as 'target parallel' has two captured regions:
  6751. // for the 'target' and 'parallel' respectively. This function returns
  6752. // the region in which to capture expressions associated with a clause.
  6753. // A return value of OMPD_unknown signifies that the expression should not
  6754. // be captured.
  6755. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  6756. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  6757. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  6758. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  6759. switch (CKind) {
  6760. case OMPC_if:
  6761. switch (DKind) {
  6762. case OMPD_target_parallel:
  6763. // If this clause applies to the nested 'parallel' region, capture within
  6764. // the 'target' region, otherwise do not capture.
  6765. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  6766. CaptureRegion = OMPD_target;
  6767. break;
  6768. case OMPD_cancel:
  6769. case OMPD_parallel:
  6770. case OMPD_parallel_sections:
  6771. case OMPD_parallel_for:
  6772. case OMPD_parallel_for_simd:
  6773. case OMPD_target:
  6774. case OMPD_target_simd:
  6775. case OMPD_target_parallel_for:
  6776. case OMPD_target_parallel_for_simd:
  6777. case OMPD_target_teams:
  6778. case OMPD_target_teams_distribute:
  6779. case OMPD_target_teams_distribute_simd:
  6780. case OMPD_target_teams_distribute_parallel_for:
  6781. case OMPD_target_teams_distribute_parallel_for_simd:
  6782. case OMPD_teams_distribute_parallel_for:
  6783. case OMPD_teams_distribute_parallel_for_simd:
  6784. case OMPD_distribute_parallel_for:
  6785. case OMPD_distribute_parallel_for_simd:
  6786. case OMPD_task:
  6787. case OMPD_taskloop:
  6788. case OMPD_taskloop_simd:
  6789. case OMPD_target_data:
  6790. case OMPD_target_enter_data:
  6791. case OMPD_target_exit_data:
  6792. case OMPD_target_update:
  6793. // Do not capture if-clause expressions.
  6794. break;
  6795. case OMPD_threadprivate:
  6796. case OMPD_taskyield:
  6797. case OMPD_barrier:
  6798. case OMPD_taskwait:
  6799. case OMPD_cancellation_point:
  6800. case OMPD_flush:
  6801. case OMPD_declare_reduction:
  6802. case OMPD_declare_simd:
  6803. case OMPD_declare_target:
  6804. case OMPD_end_declare_target:
  6805. case OMPD_teams:
  6806. case OMPD_simd:
  6807. case OMPD_for:
  6808. case OMPD_for_simd:
  6809. case OMPD_sections:
  6810. case OMPD_section:
  6811. case OMPD_single:
  6812. case OMPD_master:
  6813. case OMPD_critical:
  6814. case OMPD_taskgroup:
  6815. case OMPD_distribute:
  6816. case OMPD_ordered:
  6817. case OMPD_atomic:
  6818. case OMPD_distribute_simd:
  6819. case OMPD_teams_distribute:
  6820. case OMPD_teams_distribute_simd:
  6821. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  6822. case OMPD_unknown:
  6823. llvm_unreachable("Unknown OpenMP directive");
  6824. }
  6825. break;
  6826. case OMPC_num_threads:
  6827. switch (DKind) {
  6828. case OMPD_target_parallel:
  6829. CaptureRegion = OMPD_target;
  6830. break;
  6831. case OMPD_cancel:
  6832. case OMPD_parallel:
  6833. case OMPD_parallel_sections:
  6834. case OMPD_parallel_for:
  6835. case OMPD_parallel_for_simd:
  6836. case OMPD_target:
  6837. case OMPD_target_simd:
  6838. case OMPD_target_parallel_for:
  6839. case OMPD_target_parallel_for_simd:
  6840. case OMPD_target_teams:
  6841. case OMPD_target_teams_distribute:
  6842. case OMPD_target_teams_distribute_simd:
  6843. case OMPD_target_teams_distribute_parallel_for:
  6844. case OMPD_target_teams_distribute_parallel_for_simd:
  6845. case OMPD_teams_distribute_parallel_for:
  6846. case OMPD_teams_distribute_parallel_for_simd:
  6847. case OMPD_distribute_parallel_for:
  6848. case OMPD_distribute_parallel_for_simd:
  6849. case OMPD_task:
  6850. case OMPD_taskloop:
  6851. case OMPD_taskloop_simd:
  6852. case OMPD_target_data:
  6853. case OMPD_target_enter_data:
  6854. case OMPD_target_exit_data:
  6855. case OMPD_target_update:
  6856. // Do not capture num_threads-clause expressions.
  6857. break;
  6858. case OMPD_threadprivate:
  6859. case OMPD_taskyield:
  6860. case OMPD_barrier:
  6861. case OMPD_taskwait:
  6862. case OMPD_cancellation_point:
  6863. case OMPD_flush:
  6864. case OMPD_declare_reduction:
  6865. case OMPD_declare_simd:
  6866. case OMPD_declare_target:
  6867. case OMPD_end_declare_target:
  6868. case OMPD_teams:
  6869. case OMPD_simd:
  6870. case OMPD_for:
  6871. case OMPD_for_simd:
  6872. case OMPD_sections:
  6873. case OMPD_section:
  6874. case OMPD_single:
  6875. case OMPD_master:
  6876. case OMPD_critical:
  6877. case OMPD_taskgroup:
  6878. case OMPD_distribute:
  6879. case OMPD_ordered:
  6880. case OMPD_atomic:
  6881. case OMPD_distribute_simd:
  6882. case OMPD_teams_distribute:
  6883. case OMPD_teams_distribute_simd:
  6884. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  6885. case OMPD_unknown:
  6886. llvm_unreachable("Unknown OpenMP directive");
  6887. }
  6888. break;
  6889. case OMPC_num_teams:
  6890. switch (DKind) {
  6891. case OMPD_target_teams:
  6892. CaptureRegion = OMPD_target;
  6893. break;
  6894. case OMPD_cancel:
  6895. case OMPD_parallel:
  6896. case OMPD_parallel_sections:
  6897. case OMPD_parallel_for:
  6898. case OMPD_parallel_for_simd:
  6899. case OMPD_target:
  6900. case OMPD_target_simd:
  6901. case OMPD_target_parallel:
  6902. case OMPD_target_parallel_for:
  6903. case OMPD_target_parallel_for_simd:
  6904. case OMPD_target_teams_distribute:
  6905. case OMPD_target_teams_distribute_simd:
  6906. case OMPD_target_teams_distribute_parallel_for:
  6907. case OMPD_target_teams_distribute_parallel_for_simd:
  6908. case OMPD_teams_distribute_parallel_for:
  6909. case OMPD_teams_distribute_parallel_for_simd:
  6910. case OMPD_distribute_parallel_for:
  6911. case OMPD_distribute_parallel_for_simd:
  6912. case OMPD_task:
  6913. case OMPD_taskloop:
  6914. case OMPD_taskloop_simd:
  6915. case OMPD_target_data:
  6916. case OMPD_target_enter_data:
  6917. case OMPD_target_exit_data:
  6918. case OMPD_target_update:
  6919. case OMPD_teams:
  6920. case OMPD_teams_distribute:
  6921. case OMPD_teams_distribute_simd:
  6922. // Do not capture num_teams-clause expressions.
  6923. break;
  6924. case OMPD_threadprivate:
  6925. case OMPD_taskyield:
  6926. case OMPD_barrier:
  6927. case OMPD_taskwait:
  6928. case OMPD_cancellation_point:
  6929. case OMPD_flush:
  6930. case OMPD_declare_reduction:
  6931. case OMPD_declare_simd:
  6932. case OMPD_declare_target:
  6933. case OMPD_end_declare_target:
  6934. case OMPD_simd:
  6935. case OMPD_for:
  6936. case OMPD_for_simd:
  6937. case OMPD_sections:
  6938. case OMPD_section:
  6939. case OMPD_single:
  6940. case OMPD_master:
  6941. case OMPD_critical:
  6942. case OMPD_taskgroup:
  6943. case OMPD_distribute:
  6944. case OMPD_ordered:
  6945. case OMPD_atomic:
  6946. case OMPD_distribute_simd:
  6947. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  6948. case OMPD_unknown:
  6949. llvm_unreachable("Unknown OpenMP directive");
  6950. }
  6951. break;
  6952. case OMPC_thread_limit:
  6953. switch (DKind) {
  6954. case OMPD_target_teams:
  6955. CaptureRegion = OMPD_target;
  6956. break;
  6957. case OMPD_cancel:
  6958. case OMPD_parallel:
  6959. case OMPD_parallel_sections:
  6960. case OMPD_parallel_for:
  6961. case OMPD_parallel_for_simd:
  6962. case OMPD_target:
  6963. case OMPD_target_simd:
  6964. case OMPD_target_parallel:
  6965. case OMPD_target_parallel_for:
  6966. case OMPD_target_parallel_for_simd:
  6967. case OMPD_target_teams_distribute:
  6968. case OMPD_target_teams_distribute_simd:
  6969. case OMPD_target_teams_distribute_parallel_for:
  6970. case OMPD_target_teams_distribute_parallel_for_simd:
  6971. case OMPD_teams_distribute_parallel_for:
  6972. case OMPD_teams_distribute_parallel_for_simd:
  6973. case OMPD_distribute_parallel_for:
  6974. case OMPD_distribute_parallel_for_simd:
  6975. case OMPD_task:
  6976. case OMPD_taskloop:
  6977. case OMPD_taskloop_simd:
  6978. case OMPD_target_data:
  6979. case OMPD_target_enter_data:
  6980. case OMPD_target_exit_data:
  6981. case OMPD_target_update:
  6982. case OMPD_teams:
  6983. case OMPD_teams_distribute:
  6984. case OMPD_teams_distribute_simd:
  6985. // Do not capture thread_limit-clause expressions.
  6986. break;
  6987. case OMPD_threadprivate:
  6988. case OMPD_taskyield:
  6989. case OMPD_barrier:
  6990. case OMPD_taskwait:
  6991. case OMPD_cancellation_point:
  6992. case OMPD_flush:
  6993. case OMPD_declare_reduction:
  6994. case OMPD_declare_simd:
  6995. case OMPD_declare_target:
  6996. case OMPD_end_declare_target:
  6997. case OMPD_simd:
  6998. case OMPD_for:
  6999. case OMPD_for_simd:
  7000. case OMPD_sections:
  7001. case OMPD_section:
  7002. case OMPD_single:
  7003. case OMPD_master:
  7004. case OMPD_critical:
  7005. case OMPD_taskgroup:
  7006. case OMPD_distribute:
  7007. case OMPD_ordered:
  7008. case OMPD_atomic:
  7009. case OMPD_distribute_simd:
  7010. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  7011. case OMPD_unknown:
  7012. llvm_unreachable("Unknown OpenMP directive");
  7013. }
  7014. break;
  7015. case OMPC_schedule:
  7016. case OMPC_dist_schedule:
  7017. case OMPC_firstprivate:
  7018. case OMPC_lastprivate:
  7019. case OMPC_reduction:
  7020. case OMPC_task_reduction:
  7021. case OMPC_in_reduction:
  7022. case OMPC_linear:
  7023. case OMPC_default:
  7024. case OMPC_proc_bind:
  7025. case OMPC_final:
  7026. case OMPC_safelen:
  7027. case OMPC_simdlen:
  7028. case OMPC_collapse:
  7029. case OMPC_private:
  7030. case OMPC_shared:
  7031. case OMPC_aligned:
  7032. case OMPC_copyin:
  7033. case OMPC_copyprivate:
  7034. case OMPC_ordered:
  7035. case OMPC_nowait:
  7036. case OMPC_untied:
  7037. case OMPC_mergeable:
  7038. case OMPC_threadprivate:
  7039. case OMPC_flush:
  7040. case OMPC_read:
  7041. case OMPC_write:
  7042. case OMPC_update:
  7043. case OMPC_capture:
  7044. case OMPC_seq_cst:
  7045. case OMPC_depend:
  7046. case OMPC_device:
  7047. case OMPC_threads:
  7048. case OMPC_simd:
  7049. case OMPC_map:
  7050. case OMPC_priority:
  7051. case OMPC_grainsize:
  7052. case OMPC_nogroup:
  7053. case OMPC_num_tasks:
  7054. case OMPC_hint:
  7055. case OMPC_defaultmap:
  7056. case OMPC_unknown:
  7057. case OMPC_uniform:
  7058. case OMPC_to:
  7059. case OMPC_from:
  7060. case OMPC_use_device_ptr:
  7061. case OMPC_is_device_ptr:
  7062. llvm_unreachable("Unexpected OpenMP clause.");
  7063. }
  7064. return CaptureRegion;
  7065. }
  7066. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  7067. Expr *Condition, SourceLocation StartLoc,
  7068. SourceLocation LParenLoc,
  7069. SourceLocation NameModifierLoc,
  7070. SourceLocation ColonLoc,
  7071. SourceLocation EndLoc) {
  7072. Expr *ValExpr = Condition;
  7073. Stmt *HelperValStmt = nullptr;
  7074. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7075. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7076. !Condition->isInstantiationDependent() &&
  7077. !Condition->containsUnexpandedParameterPack()) {
  7078. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7079. if (Val.isInvalid())
  7080. return nullptr;
  7081. ValExpr = MakeFullExpr(Val.get()).get();
  7082. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7083. CaptureRegion =
  7084. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  7085. if (CaptureRegion != OMPD_unknown) {
  7086. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7087. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7088. HelperValStmt = buildPreInits(Context, Captures);
  7089. }
  7090. }
  7091. return new (Context)
  7092. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  7093. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  7094. }
  7095. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  7096. SourceLocation StartLoc,
  7097. SourceLocation LParenLoc,
  7098. SourceLocation EndLoc) {
  7099. Expr *ValExpr = Condition;
  7100. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  7101. !Condition->isInstantiationDependent() &&
  7102. !Condition->containsUnexpandedParameterPack()) {
  7103. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  7104. if (Val.isInvalid())
  7105. return nullptr;
  7106. ValExpr = MakeFullExpr(Val.get()).get();
  7107. }
  7108. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  7109. }
  7110. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  7111. Expr *Op) {
  7112. if (!Op)
  7113. return ExprError();
  7114. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  7115. public:
  7116. IntConvertDiagnoser()
  7117. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  7118. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  7119. QualType T) override {
  7120. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  7121. }
  7122. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  7123. QualType T) override {
  7124. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  7125. }
  7126. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  7127. QualType T,
  7128. QualType ConvTy) override {
  7129. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  7130. }
  7131. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  7132. QualType ConvTy) override {
  7133. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7134. << ConvTy->isEnumeralType() << ConvTy;
  7135. }
  7136. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  7137. QualType T) override {
  7138. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  7139. }
  7140. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  7141. QualType ConvTy) override {
  7142. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  7143. << ConvTy->isEnumeralType() << ConvTy;
  7144. }
  7145. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  7146. QualType) override {
  7147. llvm_unreachable("conversion functions are permitted");
  7148. }
  7149. } ConvertDiagnoser;
  7150. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  7151. }
  7152. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  7153. OpenMPClauseKind CKind,
  7154. bool StrictlyPositive) {
  7155. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  7156. !ValExpr->isInstantiationDependent()) {
  7157. SourceLocation Loc = ValExpr->getExprLoc();
  7158. ExprResult Value =
  7159. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  7160. if (Value.isInvalid())
  7161. return false;
  7162. ValExpr = Value.get();
  7163. // The expression must evaluate to a non-negative integer value.
  7164. llvm::APSInt Result;
  7165. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  7166. Result.isSigned() &&
  7167. !((!StrictlyPositive && Result.isNonNegative()) ||
  7168. (StrictlyPositive && Result.isStrictlyPositive()))) {
  7169. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  7170. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7171. << ValExpr->getSourceRange();
  7172. return false;
  7173. }
  7174. }
  7175. return true;
  7176. }
  7177. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  7178. SourceLocation StartLoc,
  7179. SourceLocation LParenLoc,
  7180. SourceLocation EndLoc) {
  7181. Expr *ValExpr = NumThreads;
  7182. Stmt *HelperValStmt = nullptr;
  7183. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7184. // OpenMP [2.5, Restrictions]
  7185. // The num_threads expression must evaluate to a positive integer value.
  7186. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  7187. /*StrictlyPositive=*/true))
  7188. return nullptr;
  7189. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  7190. CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  7191. if (CaptureRegion != OMPD_unknown) {
  7192. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7193. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7194. HelperValStmt = buildPreInits(Context, Captures);
  7195. }
  7196. return new (Context) OMPNumThreadsClause(
  7197. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  7198. }
  7199. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  7200. OpenMPClauseKind CKind,
  7201. bool StrictlyPositive) {
  7202. if (!E)
  7203. return ExprError();
  7204. if (E->isValueDependent() || E->isTypeDependent() ||
  7205. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  7206. return E;
  7207. llvm::APSInt Result;
  7208. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  7209. if (ICE.isInvalid())
  7210. return ExprError();
  7211. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  7212. (!StrictlyPositive && !Result.isNonNegative())) {
  7213. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  7214. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  7215. << E->getSourceRange();
  7216. return ExprError();
  7217. }
  7218. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  7219. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  7220. << E->getSourceRange();
  7221. return ExprError();
  7222. }
  7223. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  7224. DSAStack->setAssociatedLoops(Result.getExtValue());
  7225. else if (CKind == OMPC_ordered)
  7226. DSAStack->setAssociatedLoops(Result.getExtValue());
  7227. return ICE;
  7228. }
  7229. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  7230. SourceLocation LParenLoc,
  7231. SourceLocation EndLoc) {
  7232. // OpenMP [2.8.1, simd construct, Description]
  7233. // The parameter of the safelen clause must be a constant
  7234. // positive integer expression.
  7235. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  7236. if (Safelen.isInvalid())
  7237. return nullptr;
  7238. return new (Context)
  7239. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  7240. }
  7241. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  7242. SourceLocation LParenLoc,
  7243. SourceLocation EndLoc) {
  7244. // OpenMP [2.8.1, simd construct, Description]
  7245. // The parameter of the simdlen clause must be a constant
  7246. // positive integer expression.
  7247. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  7248. if (Simdlen.isInvalid())
  7249. return nullptr;
  7250. return new (Context)
  7251. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  7252. }
  7253. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  7254. SourceLocation StartLoc,
  7255. SourceLocation LParenLoc,
  7256. SourceLocation EndLoc) {
  7257. // OpenMP [2.7.1, loop construct, Description]
  7258. // OpenMP [2.8.1, simd construct, Description]
  7259. // OpenMP [2.9.6, distribute construct, Description]
  7260. // The parameter of the collapse clause must be a constant
  7261. // positive integer expression.
  7262. ExprResult NumForLoopsResult =
  7263. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  7264. if (NumForLoopsResult.isInvalid())
  7265. return nullptr;
  7266. return new (Context)
  7267. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  7268. }
  7269. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  7270. SourceLocation EndLoc,
  7271. SourceLocation LParenLoc,
  7272. Expr *NumForLoops) {
  7273. // OpenMP [2.7.1, loop construct, Description]
  7274. // OpenMP [2.8.1, simd construct, Description]
  7275. // OpenMP [2.9.6, distribute construct, Description]
  7276. // The parameter of the ordered clause must be a constant
  7277. // positive integer expression if any.
  7278. if (NumForLoops && LParenLoc.isValid()) {
  7279. ExprResult NumForLoopsResult =
  7280. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  7281. if (NumForLoopsResult.isInvalid())
  7282. return nullptr;
  7283. NumForLoops = NumForLoopsResult.get();
  7284. } else
  7285. NumForLoops = nullptr;
  7286. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  7287. return new (Context)
  7288. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  7289. }
  7290. OMPClause *Sema::ActOnOpenMPSimpleClause(
  7291. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  7292. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  7293. OMPClause *Res = nullptr;
  7294. switch (Kind) {
  7295. case OMPC_default:
  7296. Res =
  7297. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  7298. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  7299. break;
  7300. case OMPC_proc_bind:
  7301. Res = ActOnOpenMPProcBindClause(
  7302. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  7303. LParenLoc, EndLoc);
  7304. break;
  7305. case OMPC_if:
  7306. case OMPC_final:
  7307. case OMPC_num_threads:
  7308. case OMPC_safelen:
  7309. case OMPC_simdlen:
  7310. case OMPC_collapse:
  7311. case OMPC_schedule:
  7312. case OMPC_private:
  7313. case OMPC_firstprivate:
  7314. case OMPC_lastprivate:
  7315. case OMPC_shared:
  7316. case OMPC_reduction:
  7317. case OMPC_task_reduction:
  7318. case OMPC_in_reduction:
  7319. case OMPC_linear:
  7320. case OMPC_aligned:
  7321. case OMPC_copyin:
  7322. case OMPC_copyprivate:
  7323. case OMPC_ordered:
  7324. case OMPC_nowait:
  7325. case OMPC_untied:
  7326. case OMPC_mergeable:
  7327. case OMPC_threadprivate:
  7328. case OMPC_flush:
  7329. case OMPC_read:
  7330. case OMPC_write:
  7331. case OMPC_update:
  7332. case OMPC_capture:
  7333. case OMPC_seq_cst:
  7334. case OMPC_depend:
  7335. case OMPC_device:
  7336. case OMPC_threads:
  7337. case OMPC_simd:
  7338. case OMPC_map:
  7339. case OMPC_num_teams:
  7340. case OMPC_thread_limit:
  7341. case OMPC_priority:
  7342. case OMPC_grainsize:
  7343. case OMPC_nogroup:
  7344. case OMPC_num_tasks:
  7345. case OMPC_hint:
  7346. case OMPC_dist_schedule:
  7347. case OMPC_defaultmap:
  7348. case OMPC_unknown:
  7349. case OMPC_uniform:
  7350. case OMPC_to:
  7351. case OMPC_from:
  7352. case OMPC_use_device_ptr:
  7353. case OMPC_is_device_ptr:
  7354. llvm_unreachable("Clause is not allowed.");
  7355. }
  7356. return Res;
  7357. }
  7358. static std::string
  7359. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  7360. ArrayRef<unsigned> Exclude = llvm::None) {
  7361. std::string Values;
  7362. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  7363. unsigned Skipped = Exclude.size();
  7364. auto S = Exclude.begin(), E = Exclude.end();
  7365. for (unsigned i = First; i < Last; ++i) {
  7366. if (std::find(S, E, i) != E) {
  7367. --Skipped;
  7368. continue;
  7369. }
  7370. Values += "'";
  7371. Values += getOpenMPSimpleClauseTypeName(K, i);
  7372. Values += "'";
  7373. if (i == Bound - Skipped)
  7374. Values += " or ";
  7375. else if (i != Bound + 1 - Skipped)
  7376. Values += ", ";
  7377. }
  7378. return Values;
  7379. }
  7380. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  7381. SourceLocation KindKwLoc,
  7382. SourceLocation StartLoc,
  7383. SourceLocation LParenLoc,
  7384. SourceLocation EndLoc) {
  7385. if (Kind == OMPC_DEFAULT_unknown) {
  7386. static_assert(OMPC_DEFAULT_unknown > 0,
  7387. "OMPC_DEFAULT_unknown not greater than 0");
  7388. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7389. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  7390. /*Last=*/OMPC_DEFAULT_unknown)
  7391. << getOpenMPClauseName(OMPC_default);
  7392. return nullptr;
  7393. }
  7394. switch (Kind) {
  7395. case OMPC_DEFAULT_none:
  7396. DSAStack->setDefaultDSANone(KindKwLoc);
  7397. break;
  7398. case OMPC_DEFAULT_shared:
  7399. DSAStack->setDefaultDSAShared(KindKwLoc);
  7400. break;
  7401. case OMPC_DEFAULT_unknown:
  7402. llvm_unreachable("Clause kind is not allowed.");
  7403. break;
  7404. }
  7405. return new (Context)
  7406. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7407. }
  7408. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  7409. SourceLocation KindKwLoc,
  7410. SourceLocation StartLoc,
  7411. SourceLocation LParenLoc,
  7412. SourceLocation EndLoc) {
  7413. if (Kind == OMPC_PROC_BIND_unknown) {
  7414. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  7415. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  7416. /*Last=*/OMPC_PROC_BIND_unknown)
  7417. << getOpenMPClauseName(OMPC_proc_bind);
  7418. return nullptr;
  7419. }
  7420. return new (Context)
  7421. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  7422. }
  7423. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  7424. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  7425. SourceLocation StartLoc, SourceLocation LParenLoc,
  7426. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  7427. SourceLocation EndLoc) {
  7428. OMPClause *Res = nullptr;
  7429. switch (Kind) {
  7430. case OMPC_schedule:
  7431. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  7432. assert(Argument.size() == NumberOfElements &&
  7433. ArgumentLoc.size() == NumberOfElements);
  7434. Res = ActOnOpenMPScheduleClause(
  7435. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  7436. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  7437. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  7438. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  7439. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  7440. break;
  7441. case OMPC_if:
  7442. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  7443. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  7444. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  7445. DelimLoc, EndLoc);
  7446. break;
  7447. case OMPC_dist_schedule:
  7448. Res = ActOnOpenMPDistScheduleClause(
  7449. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  7450. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  7451. break;
  7452. case OMPC_defaultmap:
  7453. enum { Modifier, DefaultmapKind };
  7454. Res = ActOnOpenMPDefaultmapClause(
  7455. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  7456. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  7457. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  7458. EndLoc);
  7459. break;
  7460. case OMPC_final:
  7461. case OMPC_num_threads:
  7462. case OMPC_safelen:
  7463. case OMPC_simdlen:
  7464. case OMPC_collapse:
  7465. case OMPC_default:
  7466. case OMPC_proc_bind:
  7467. case OMPC_private:
  7468. case OMPC_firstprivate:
  7469. case OMPC_lastprivate:
  7470. case OMPC_shared:
  7471. case OMPC_reduction:
  7472. case OMPC_task_reduction:
  7473. case OMPC_in_reduction:
  7474. case OMPC_linear:
  7475. case OMPC_aligned:
  7476. case OMPC_copyin:
  7477. case OMPC_copyprivate:
  7478. case OMPC_ordered:
  7479. case OMPC_nowait:
  7480. case OMPC_untied:
  7481. case OMPC_mergeable:
  7482. case OMPC_threadprivate:
  7483. case OMPC_flush:
  7484. case OMPC_read:
  7485. case OMPC_write:
  7486. case OMPC_update:
  7487. case OMPC_capture:
  7488. case OMPC_seq_cst:
  7489. case OMPC_depend:
  7490. case OMPC_device:
  7491. case OMPC_threads:
  7492. case OMPC_simd:
  7493. case OMPC_map:
  7494. case OMPC_num_teams:
  7495. case OMPC_thread_limit:
  7496. case OMPC_priority:
  7497. case OMPC_grainsize:
  7498. case OMPC_nogroup:
  7499. case OMPC_num_tasks:
  7500. case OMPC_hint:
  7501. case OMPC_unknown:
  7502. case OMPC_uniform:
  7503. case OMPC_to:
  7504. case OMPC_from:
  7505. case OMPC_use_device_ptr:
  7506. case OMPC_is_device_ptr:
  7507. llvm_unreachable("Clause is not allowed.");
  7508. }
  7509. return Res;
  7510. }
  7511. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  7512. OpenMPScheduleClauseModifier M2,
  7513. SourceLocation M1Loc, SourceLocation M2Loc) {
  7514. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  7515. SmallVector<unsigned, 2> Excluded;
  7516. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  7517. Excluded.push_back(M2);
  7518. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  7519. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  7520. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  7521. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  7522. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  7523. << getListOfPossibleValues(OMPC_schedule,
  7524. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  7525. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  7526. Excluded)
  7527. << getOpenMPClauseName(OMPC_schedule);
  7528. return true;
  7529. }
  7530. return false;
  7531. }
  7532. OMPClause *Sema::ActOnOpenMPScheduleClause(
  7533. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  7534. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  7535. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  7536. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  7537. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  7538. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  7539. return nullptr;
  7540. // OpenMP, 2.7.1, Loop Construct, Restrictions
  7541. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  7542. // but not both.
  7543. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  7544. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  7545. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  7546. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  7547. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  7548. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  7549. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  7550. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  7551. return nullptr;
  7552. }
  7553. if (Kind == OMPC_SCHEDULE_unknown) {
  7554. std::string Values;
  7555. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  7556. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  7557. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  7558. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  7559. Exclude);
  7560. } else {
  7561. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  7562. /*Last=*/OMPC_SCHEDULE_unknown);
  7563. }
  7564. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  7565. << Values << getOpenMPClauseName(OMPC_schedule);
  7566. return nullptr;
  7567. }
  7568. // OpenMP, 2.7.1, Loop Construct, Restrictions
  7569. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  7570. // schedule(guided).
  7571. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  7572. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  7573. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  7574. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  7575. diag::err_omp_schedule_nonmonotonic_static);
  7576. return nullptr;
  7577. }
  7578. Expr *ValExpr = ChunkSize;
  7579. Stmt *HelperValStmt = nullptr;
  7580. if (ChunkSize) {
  7581. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  7582. !ChunkSize->isInstantiationDependent() &&
  7583. !ChunkSize->containsUnexpandedParameterPack()) {
  7584. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  7585. ExprResult Val =
  7586. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  7587. if (Val.isInvalid())
  7588. return nullptr;
  7589. ValExpr = Val.get();
  7590. // OpenMP [2.7.1, Restrictions]
  7591. // chunk_size must be a loop invariant integer expression with a positive
  7592. // value.
  7593. llvm::APSInt Result;
  7594. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  7595. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  7596. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  7597. << "schedule" << 1 << ChunkSize->getSourceRange();
  7598. return nullptr;
  7599. }
  7600. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  7601. !CurContext->isDependentContext()) {
  7602. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  7603. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  7604. HelperValStmt = buildPreInits(Context, Captures);
  7605. }
  7606. }
  7607. }
  7608. return new (Context)
  7609. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  7610. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  7611. }
  7612. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  7613. SourceLocation StartLoc,
  7614. SourceLocation EndLoc) {
  7615. OMPClause *Res = nullptr;
  7616. switch (Kind) {
  7617. case OMPC_ordered:
  7618. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  7619. break;
  7620. case OMPC_nowait:
  7621. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  7622. break;
  7623. case OMPC_untied:
  7624. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  7625. break;
  7626. case OMPC_mergeable:
  7627. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  7628. break;
  7629. case OMPC_read:
  7630. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  7631. break;
  7632. case OMPC_write:
  7633. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  7634. break;
  7635. case OMPC_update:
  7636. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  7637. break;
  7638. case OMPC_capture:
  7639. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  7640. break;
  7641. case OMPC_seq_cst:
  7642. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  7643. break;
  7644. case OMPC_threads:
  7645. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  7646. break;
  7647. case OMPC_simd:
  7648. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  7649. break;
  7650. case OMPC_nogroup:
  7651. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  7652. break;
  7653. case OMPC_if:
  7654. case OMPC_final:
  7655. case OMPC_num_threads:
  7656. case OMPC_safelen:
  7657. case OMPC_simdlen:
  7658. case OMPC_collapse:
  7659. case OMPC_schedule:
  7660. case OMPC_private:
  7661. case OMPC_firstprivate:
  7662. case OMPC_lastprivate:
  7663. case OMPC_shared:
  7664. case OMPC_reduction:
  7665. case OMPC_task_reduction:
  7666. case OMPC_in_reduction:
  7667. case OMPC_linear:
  7668. case OMPC_aligned:
  7669. case OMPC_copyin:
  7670. case OMPC_copyprivate:
  7671. case OMPC_default:
  7672. case OMPC_proc_bind:
  7673. case OMPC_threadprivate:
  7674. case OMPC_flush:
  7675. case OMPC_depend:
  7676. case OMPC_device:
  7677. case OMPC_map:
  7678. case OMPC_num_teams:
  7679. case OMPC_thread_limit:
  7680. case OMPC_priority:
  7681. case OMPC_grainsize:
  7682. case OMPC_num_tasks:
  7683. case OMPC_hint:
  7684. case OMPC_dist_schedule:
  7685. case OMPC_defaultmap:
  7686. case OMPC_unknown:
  7687. case OMPC_uniform:
  7688. case OMPC_to:
  7689. case OMPC_from:
  7690. case OMPC_use_device_ptr:
  7691. case OMPC_is_device_ptr:
  7692. llvm_unreachable("Clause is not allowed.");
  7693. }
  7694. return Res;
  7695. }
  7696. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  7697. SourceLocation EndLoc) {
  7698. DSAStack->setNowaitRegion();
  7699. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  7700. }
  7701. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  7702. SourceLocation EndLoc) {
  7703. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  7704. }
  7705. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  7706. SourceLocation EndLoc) {
  7707. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  7708. }
  7709. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  7710. SourceLocation EndLoc) {
  7711. return new (Context) OMPReadClause(StartLoc, EndLoc);
  7712. }
  7713. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  7714. SourceLocation EndLoc) {
  7715. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  7716. }
  7717. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  7718. SourceLocation EndLoc) {
  7719. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  7720. }
  7721. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  7722. SourceLocation EndLoc) {
  7723. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  7724. }
  7725. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  7726. SourceLocation EndLoc) {
  7727. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  7728. }
  7729. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  7730. SourceLocation EndLoc) {
  7731. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  7732. }
  7733. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  7734. SourceLocation EndLoc) {
  7735. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  7736. }
  7737. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  7738. SourceLocation EndLoc) {
  7739. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  7740. }
  7741. OMPClause *Sema::ActOnOpenMPVarListClause(
  7742. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  7743. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  7744. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  7745. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  7746. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  7747. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  7748. SourceLocation DepLinMapLoc) {
  7749. OMPClause *Res = nullptr;
  7750. switch (Kind) {
  7751. case OMPC_private:
  7752. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  7753. break;
  7754. case OMPC_firstprivate:
  7755. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  7756. break;
  7757. case OMPC_lastprivate:
  7758. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  7759. break;
  7760. case OMPC_shared:
  7761. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  7762. break;
  7763. case OMPC_reduction:
  7764. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  7765. EndLoc, ReductionIdScopeSpec, ReductionId);
  7766. break;
  7767. case OMPC_task_reduction:
  7768. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  7769. EndLoc, ReductionIdScopeSpec,
  7770. ReductionId);
  7771. break;
  7772. case OMPC_in_reduction:
  7773. Res =
  7774. ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  7775. EndLoc, ReductionIdScopeSpec, ReductionId);
  7776. break;
  7777. case OMPC_linear:
  7778. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  7779. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  7780. break;
  7781. case OMPC_aligned:
  7782. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  7783. ColonLoc, EndLoc);
  7784. break;
  7785. case OMPC_copyin:
  7786. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  7787. break;
  7788. case OMPC_copyprivate:
  7789. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  7790. break;
  7791. case OMPC_flush:
  7792. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  7793. break;
  7794. case OMPC_depend:
  7795. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  7796. StartLoc, LParenLoc, EndLoc);
  7797. break;
  7798. case OMPC_map:
  7799. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  7800. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  7801. LParenLoc, EndLoc);
  7802. break;
  7803. case OMPC_to:
  7804. Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
  7805. break;
  7806. case OMPC_from:
  7807. Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
  7808. break;
  7809. case OMPC_use_device_ptr:
  7810. Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  7811. break;
  7812. case OMPC_is_device_ptr:
  7813. Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
  7814. break;
  7815. case OMPC_if:
  7816. case OMPC_final:
  7817. case OMPC_num_threads:
  7818. case OMPC_safelen:
  7819. case OMPC_simdlen:
  7820. case OMPC_collapse:
  7821. case OMPC_default:
  7822. case OMPC_proc_bind:
  7823. case OMPC_schedule:
  7824. case OMPC_ordered:
  7825. case OMPC_nowait:
  7826. case OMPC_untied:
  7827. case OMPC_mergeable:
  7828. case OMPC_threadprivate:
  7829. case OMPC_read:
  7830. case OMPC_write:
  7831. case OMPC_update:
  7832. case OMPC_capture:
  7833. case OMPC_seq_cst:
  7834. case OMPC_device:
  7835. case OMPC_threads:
  7836. case OMPC_simd:
  7837. case OMPC_num_teams:
  7838. case OMPC_thread_limit:
  7839. case OMPC_priority:
  7840. case OMPC_grainsize:
  7841. case OMPC_nogroup:
  7842. case OMPC_num_tasks:
  7843. case OMPC_hint:
  7844. case OMPC_dist_schedule:
  7845. case OMPC_defaultmap:
  7846. case OMPC_unknown:
  7847. case OMPC_uniform:
  7848. llvm_unreachable("Clause is not allowed.");
  7849. }
  7850. return Res;
  7851. }
  7852. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  7853. ExprObjectKind OK, SourceLocation Loc) {
  7854. ExprResult Res = BuildDeclRefExpr(
  7855. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  7856. if (!Res.isUsable())
  7857. return ExprError();
  7858. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  7859. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  7860. if (!Res.isUsable())
  7861. return ExprError();
  7862. }
  7863. if (VK != VK_LValue && Res.get()->isGLValue()) {
  7864. Res = DefaultLvalueConversion(Res.get());
  7865. if (!Res.isUsable())
  7866. return ExprError();
  7867. }
  7868. return Res;
  7869. }
  7870. static std::pair<ValueDecl *, bool>
  7871. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  7872. SourceRange &ERange, bool AllowArraySection = false) {
  7873. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  7874. RefExpr->containsUnexpandedParameterPack())
  7875. return std::make_pair(nullptr, true);
  7876. // OpenMP [3.1, C/C++]
  7877. // A list item is a variable name.
  7878. // OpenMP [2.9.3.3, Restrictions, p.1]
  7879. // A variable that is part of another variable (as an array or
  7880. // structure element) cannot appear in a private clause.
  7881. RefExpr = RefExpr->IgnoreParens();
  7882. enum {
  7883. NoArrayExpr = -1,
  7884. ArraySubscript = 0,
  7885. OMPArraySection = 1
  7886. } IsArrayExpr = NoArrayExpr;
  7887. if (AllowArraySection) {
  7888. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  7889. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  7890. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  7891. Base = TempASE->getBase()->IgnoreParenImpCasts();
  7892. RefExpr = Base;
  7893. IsArrayExpr = ArraySubscript;
  7894. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  7895. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  7896. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  7897. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  7898. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  7899. Base = TempASE->getBase()->IgnoreParenImpCasts();
  7900. RefExpr = Base;
  7901. IsArrayExpr = OMPArraySection;
  7902. }
  7903. }
  7904. ELoc = RefExpr->getExprLoc();
  7905. ERange = RefExpr->getSourceRange();
  7906. RefExpr = RefExpr->IgnoreParenImpCasts();
  7907. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  7908. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  7909. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  7910. (S.getCurrentThisType().isNull() || !ME ||
  7911. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  7912. !isa<FieldDecl>(ME->getMemberDecl()))) {
  7913. if (IsArrayExpr != NoArrayExpr)
  7914. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  7915. << ERange;
  7916. else {
  7917. S.Diag(ELoc,
  7918. AllowArraySection
  7919. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  7920. : diag::err_omp_expected_var_name_member_expr)
  7921. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  7922. }
  7923. return std::make_pair(nullptr, false);
  7924. }
  7925. return std::make_pair(
  7926. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  7927. }
  7928. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  7929. SourceLocation StartLoc,
  7930. SourceLocation LParenLoc,
  7931. SourceLocation EndLoc) {
  7932. SmallVector<Expr *, 8> Vars;
  7933. SmallVector<Expr *, 8> PrivateCopies;
  7934. for (auto &RefExpr : VarList) {
  7935. assert(RefExpr && "NULL expr in OpenMP private clause.");
  7936. SourceLocation ELoc;
  7937. SourceRange ERange;
  7938. Expr *SimpleRefExpr = RefExpr;
  7939. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  7940. if (Res.second) {
  7941. // It will be analyzed later.
  7942. Vars.push_back(RefExpr);
  7943. PrivateCopies.push_back(nullptr);
  7944. }
  7945. ValueDecl *D = Res.first;
  7946. if (!D)
  7947. continue;
  7948. QualType Type = D->getType();
  7949. auto *VD = dyn_cast<VarDecl>(D);
  7950. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  7951. // A variable that appears in a private clause must not have an incomplete
  7952. // type or a reference type.
  7953. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  7954. continue;
  7955. Type = Type.getNonReferenceType();
  7956. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  7957. // in a Construct]
  7958. // Variables with the predetermined data-sharing attributes may not be
  7959. // listed in data-sharing attributes clauses, except for the cases
  7960. // listed below. For these exceptions only, listing a predetermined
  7961. // variable in a data-sharing attribute clause is allowed and overrides
  7962. // the variable's predetermined data-sharing attributes.
  7963. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  7964. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  7965. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  7966. << getOpenMPClauseName(OMPC_private);
  7967. ReportOriginalDSA(*this, DSAStack, D, DVar);
  7968. continue;
  7969. }
  7970. auto CurrDir = DSAStack->getCurrentDirective();
  7971. // Variably modified types are not supported for tasks.
  7972. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  7973. isOpenMPTaskingDirective(CurrDir)) {
  7974. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  7975. << getOpenMPClauseName(OMPC_private) << Type
  7976. << getOpenMPDirectiveName(CurrDir);
  7977. bool IsDecl =
  7978. !VD ||
  7979. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  7980. Diag(D->getLocation(),
  7981. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7982. << D;
  7983. continue;
  7984. }
  7985. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  7986. // A list item cannot appear in both a map clause and a data-sharing
  7987. // attribute clause on the same construct
  7988. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  7989. CurrDir == OMPD_target_teams ||
  7990. CurrDir == OMPD_target_teams_distribute ||
  7991. CurrDir == OMPD_target_teams_distribute_parallel_for ||
  7992. CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
  7993. CurrDir == OMPD_target_teams_distribute_simd ||
  7994. CurrDir == OMPD_target_parallel_for_simd ||
  7995. CurrDir == OMPD_target_parallel_for) {
  7996. OpenMPClauseKind ConflictKind;
  7997. if (DSAStack->checkMappableExprComponentListsForDecl(
  7998. VD, /*CurrentRegionOnly=*/true,
  7999. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8000. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8001. ConflictKind = WhereFoundClauseKind;
  8002. return true;
  8003. })) {
  8004. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8005. << getOpenMPClauseName(OMPC_private)
  8006. << getOpenMPClauseName(ConflictKind)
  8007. << getOpenMPDirectiveName(CurrDir);
  8008. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8009. continue;
  8010. }
  8011. }
  8012. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  8013. // A variable of class type (or array thereof) that appears in a private
  8014. // clause requires an accessible, unambiguous default constructor for the
  8015. // class type.
  8016. // Generate helper private variable and initialize it with the default
  8017. // value. The address of the original variable is replaced by the address of
  8018. // the new private variable in CodeGen. This new variable is not added to
  8019. // IdResolver, so the code in the OpenMP region uses original variable for
  8020. // proper diagnostics.
  8021. Type = Type.getUnqualifiedType();
  8022. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8023. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8024. ActOnUninitializedDecl(VDPrivate);
  8025. if (VDPrivate->isInvalidDecl())
  8026. continue;
  8027. auto VDPrivateRefExpr = buildDeclRefExpr(
  8028. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  8029. DeclRefExpr *Ref = nullptr;
  8030. if (!VD && !CurContext->isDependentContext())
  8031. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8032. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  8033. Vars.push_back((VD || CurContext->isDependentContext())
  8034. ? RefExpr->IgnoreParens()
  8035. : Ref);
  8036. PrivateCopies.push_back(VDPrivateRefExpr);
  8037. }
  8038. if (Vars.empty())
  8039. return nullptr;
  8040. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8041. PrivateCopies);
  8042. }
  8043. namespace {
  8044. class DiagsUninitializedSeveretyRAII {
  8045. private:
  8046. DiagnosticsEngine &Diags;
  8047. SourceLocation SavedLoc;
  8048. bool IsIgnored;
  8049. public:
  8050. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  8051. bool IsIgnored)
  8052. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  8053. if (!IsIgnored) {
  8054. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  8055. /*Map*/ diag::Severity::Ignored, Loc);
  8056. }
  8057. }
  8058. ~DiagsUninitializedSeveretyRAII() {
  8059. if (!IsIgnored)
  8060. Diags.popMappings(SavedLoc);
  8061. }
  8062. };
  8063. }
  8064. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  8065. SourceLocation StartLoc,
  8066. SourceLocation LParenLoc,
  8067. SourceLocation EndLoc) {
  8068. SmallVector<Expr *, 8> Vars;
  8069. SmallVector<Expr *, 8> PrivateCopies;
  8070. SmallVector<Expr *, 8> Inits;
  8071. SmallVector<Decl *, 4> ExprCaptures;
  8072. bool IsImplicitClause =
  8073. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  8074. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  8075. for (auto &RefExpr : VarList) {
  8076. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  8077. SourceLocation ELoc;
  8078. SourceRange ERange;
  8079. Expr *SimpleRefExpr = RefExpr;
  8080. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8081. if (Res.second) {
  8082. // It will be analyzed later.
  8083. Vars.push_back(RefExpr);
  8084. PrivateCopies.push_back(nullptr);
  8085. Inits.push_back(nullptr);
  8086. }
  8087. ValueDecl *D = Res.first;
  8088. if (!D)
  8089. continue;
  8090. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  8091. QualType Type = D->getType();
  8092. auto *VD = dyn_cast<VarDecl>(D);
  8093. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8094. // A variable that appears in a private clause must not have an incomplete
  8095. // type or a reference type.
  8096. if (RequireCompleteType(ELoc, Type,
  8097. diag::err_omp_firstprivate_incomplete_type))
  8098. continue;
  8099. Type = Type.getNonReferenceType();
  8100. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  8101. // A variable of class type (or array thereof) that appears in a private
  8102. // clause requires an accessible, unambiguous copy constructor for the
  8103. // class type.
  8104. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  8105. // If an implicit firstprivate variable found it was checked already.
  8106. DSAStackTy::DSAVarData TopDVar;
  8107. if (!IsImplicitClause) {
  8108. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8109. TopDVar = DVar;
  8110. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8111. bool IsConstant = ElemType.isConstant(Context);
  8112. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  8113. // A list item that specifies a given variable may not appear in more
  8114. // than one clause on the same directive, except that a variable may be
  8115. // specified in both firstprivate and lastprivate clauses.
  8116. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8117. // A list item may appear in a firstprivate or lastprivate clause but not
  8118. // both.
  8119. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  8120. (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
  8121. DVar.RefExpr) {
  8122. Diag(ELoc, diag::err_omp_wrong_dsa)
  8123. << getOpenMPClauseName(DVar.CKind)
  8124. << getOpenMPClauseName(OMPC_firstprivate);
  8125. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8126. continue;
  8127. }
  8128. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8129. // in a Construct]
  8130. // Variables with the predetermined data-sharing attributes may not be
  8131. // listed in data-sharing attributes clauses, except for the cases
  8132. // listed below. For these exceptions only, listing a predetermined
  8133. // variable in a data-sharing attribute clause is allowed and overrides
  8134. // the variable's predetermined data-sharing attributes.
  8135. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8136. // in a Construct, C/C++, p.2]
  8137. // Variables with const-qualified type having no mutable member may be
  8138. // listed in a firstprivate clause, even if they are static data members.
  8139. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  8140. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  8141. Diag(ELoc, diag::err_omp_wrong_dsa)
  8142. << getOpenMPClauseName(DVar.CKind)
  8143. << getOpenMPClauseName(OMPC_firstprivate);
  8144. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8145. continue;
  8146. }
  8147. // OpenMP [2.9.3.4, Restrictions, p.2]
  8148. // A list item that is private within a parallel region must not appear
  8149. // in a firstprivate clause on a worksharing construct if any of the
  8150. // worksharing regions arising from the worksharing construct ever bind
  8151. // to any of the parallel regions arising from the parallel construct.
  8152. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8153. // A list item that is private within a teams region must not appear in a
  8154. // firstprivate clause on a distribute construct if any of the distribute
  8155. // regions arising from the distribute construct ever bind to any of the
  8156. // teams regions arising from the teams construct.
  8157. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  8158. // A list item that appears in a reduction clause of a teams construct
  8159. // must not appear in a firstprivate clause on a distribute construct if
  8160. // any of the distribute regions arising from the distribute construct
  8161. // ever bind to any of the teams regions arising from the teams construct.
  8162. if ((isOpenMPWorksharingDirective(CurrDir) ||
  8163. isOpenMPDistributeDirective(CurrDir)) &&
  8164. !isOpenMPParallelDirective(CurrDir) &&
  8165. !isOpenMPTeamsDirective(CurrDir)) {
  8166. DVar = DSAStack->getImplicitDSA(D, true);
  8167. if (DVar.CKind != OMPC_shared &&
  8168. (isOpenMPParallelDirective(DVar.DKind) ||
  8169. isOpenMPTeamsDirective(DVar.DKind) ||
  8170. DVar.DKind == OMPD_unknown)) {
  8171. Diag(ELoc, diag::err_omp_required_access)
  8172. << getOpenMPClauseName(OMPC_firstprivate)
  8173. << getOpenMPClauseName(OMPC_shared);
  8174. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8175. continue;
  8176. }
  8177. }
  8178. // OpenMP [2.9.3.4, Restrictions, p.3]
  8179. // A list item that appears in a reduction clause of a parallel construct
  8180. // must not appear in a firstprivate clause on a worksharing or task
  8181. // construct if any of the worksharing or task regions arising from the
  8182. // worksharing or task construct ever bind to any of the parallel regions
  8183. // arising from the parallel construct.
  8184. // OpenMP [2.9.3.4, Restrictions, p.4]
  8185. // A list item that appears in a reduction clause in worksharing
  8186. // construct must not appear in a firstprivate clause in a task construct
  8187. // encountered during execution of any of the worksharing regions arising
  8188. // from the worksharing construct.
  8189. if (isOpenMPTaskingDirective(CurrDir)) {
  8190. DVar = DSAStack->hasInnermostDSA(
  8191. D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
  8192. [](OpenMPDirectiveKind K) -> bool {
  8193. return isOpenMPParallelDirective(K) ||
  8194. isOpenMPWorksharingDirective(K) ||
  8195. isOpenMPTeamsDirective(K);
  8196. },
  8197. /*FromParent=*/true);
  8198. if (DVar.CKind == OMPC_reduction &&
  8199. (isOpenMPParallelDirective(DVar.DKind) ||
  8200. isOpenMPWorksharingDirective(DVar.DKind) ||
  8201. isOpenMPTeamsDirective(DVar.DKind))) {
  8202. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  8203. << getOpenMPDirectiveName(DVar.DKind);
  8204. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8205. continue;
  8206. }
  8207. }
  8208. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  8209. // A list item cannot appear in both a map clause and a data-sharing
  8210. // attribute clause on the same construct
  8211. if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
  8212. CurrDir == OMPD_target_teams ||
  8213. CurrDir == OMPD_target_teams_distribute ||
  8214. CurrDir == OMPD_target_teams_distribute_parallel_for ||
  8215. CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
  8216. CurrDir == OMPD_target_teams_distribute_simd ||
  8217. CurrDir == OMPD_target_parallel_for_simd ||
  8218. CurrDir == OMPD_target_parallel_for) {
  8219. OpenMPClauseKind ConflictKind;
  8220. if (DSAStack->checkMappableExprComponentListsForDecl(
  8221. VD, /*CurrentRegionOnly=*/true,
  8222. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  8223. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  8224. ConflictKind = WhereFoundClauseKind;
  8225. return true;
  8226. })) {
  8227. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  8228. << getOpenMPClauseName(OMPC_firstprivate)
  8229. << getOpenMPClauseName(ConflictKind)
  8230. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8231. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8232. continue;
  8233. }
  8234. }
  8235. }
  8236. // Variably modified types are not supported for tasks.
  8237. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  8238. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  8239. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  8240. << getOpenMPClauseName(OMPC_firstprivate) << Type
  8241. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  8242. bool IsDecl =
  8243. !VD ||
  8244. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  8245. Diag(D->getLocation(),
  8246. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8247. << D;
  8248. continue;
  8249. }
  8250. Type = Type.getUnqualifiedType();
  8251. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  8252. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8253. // Generate helper private variable and initialize it with the value of the
  8254. // original variable. The address of the original variable is replaced by
  8255. // the address of the new private variable in the CodeGen. This new variable
  8256. // is not added to IdResolver, so the code in the OpenMP region uses
  8257. // original variable for proper diagnostics and variable capturing.
  8258. Expr *VDInitRefExpr = nullptr;
  8259. // For arrays generate initializer for single element and replace it by the
  8260. // original array element in CodeGen.
  8261. if (Type->isArrayType()) {
  8262. auto VDInit =
  8263. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  8264. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  8265. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  8266. ElemType = ElemType.getUnqualifiedType();
  8267. auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  8268. ".firstprivate.temp");
  8269. InitializedEntity Entity =
  8270. InitializedEntity::InitializeVariable(VDInitTemp);
  8271. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  8272. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  8273. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  8274. if (Result.isInvalid())
  8275. VDPrivate->setInvalidDecl();
  8276. else
  8277. VDPrivate->setInit(Result.getAs<Expr>());
  8278. // Remove temp variable declaration.
  8279. Context.Deallocate(VDInitTemp);
  8280. } else {
  8281. auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  8282. ".firstprivate.temp");
  8283. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  8284. RefExpr->getExprLoc());
  8285. AddInitializerToDecl(VDPrivate,
  8286. DefaultLvalueConversion(VDInitRefExpr).get(),
  8287. /*DirectInit=*/false);
  8288. }
  8289. if (VDPrivate->isInvalidDecl()) {
  8290. if (IsImplicitClause) {
  8291. Diag(RefExpr->getExprLoc(),
  8292. diag::note_omp_task_predetermined_firstprivate_here);
  8293. }
  8294. continue;
  8295. }
  8296. CurContext->addDecl(VDPrivate);
  8297. auto VDPrivateRefExpr = buildDeclRefExpr(
  8298. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  8299. RefExpr->getExprLoc());
  8300. DeclRefExpr *Ref = nullptr;
  8301. if (!VD && !CurContext->isDependentContext()) {
  8302. if (TopDVar.CKind == OMPC_lastprivate)
  8303. Ref = TopDVar.PrivateCopy;
  8304. else {
  8305. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8306. if (!IsOpenMPCapturedDecl(D))
  8307. ExprCaptures.push_back(Ref->getDecl());
  8308. }
  8309. }
  8310. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  8311. Vars.push_back((VD || CurContext->isDependentContext())
  8312. ? RefExpr->IgnoreParens()
  8313. : Ref);
  8314. PrivateCopies.push_back(VDPrivateRefExpr);
  8315. Inits.push_back(VDInitRefExpr);
  8316. }
  8317. if (Vars.empty())
  8318. return nullptr;
  8319. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8320. Vars, PrivateCopies, Inits,
  8321. buildPreInits(Context, ExprCaptures));
  8322. }
  8323. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  8324. SourceLocation StartLoc,
  8325. SourceLocation LParenLoc,
  8326. SourceLocation EndLoc) {
  8327. SmallVector<Expr *, 8> Vars;
  8328. SmallVector<Expr *, 8> SrcExprs;
  8329. SmallVector<Expr *, 8> DstExprs;
  8330. SmallVector<Expr *, 8> AssignmentOps;
  8331. SmallVector<Decl *, 4> ExprCaptures;
  8332. SmallVector<Expr *, 4> ExprPostUpdates;
  8333. for (auto &RefExpr : VarList) {
  8334. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8335. SourceLocation ELoc;
  8336. SourceRange ERange;
  8337. Expr *SimpleRefExpr = RefExpr;
  8338. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8339. if (Res.second) {
  8340. // It will be analyzed later.
  8341. Vars.push_back(RefExpr);
  8342. SrcExprs.push_back(nullptr);
  8343. DstExprs.push_back(nullptr);
  8344. AssignmentOps.push_back(nullptr);
  8345. }
  8346. ValueDecl *D = Res.first;
  8347. if (!D)
  8348. continue;
  8349. QualType Type = D->getType();
  8350. auto *VD = dyn_cast<VarDecl>(D);
  8351. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  8352. // A variable that appears in a lastprivate clause must not have an
  8353. // incomplete type or a reference type.
  8354. if (RequireCompleteType(ELoc, Type,
  8355. diag::err_omp_lastprivate_incomplete_type))
  8356. continue;
  8357. Type = Type.getNonReferenceType();
  8358. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  8359. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  8360. // in a Construct]
  8361. // Variables with the predetermined data-sharing attributes may not be
  8362. // listed in data-sharing attributes clauses, except for the cases
  8363. // listed below.
  8364. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  8365. // A list item may appear in a firstprivate or lastprivate clause but not
  8366. // both.
  8367. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8368. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  8369. (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
  8370. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  8371. Diag(ELoc, diag::err_omp_wrong_dsa)
  8372. << getOpenMPClauseName(DVar.CKind)
  8373. << getOpenMPClauseName(OMPC_lastprivate);
  8374. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8375. continue;
  8376. }
  8377. // OpenMP [2.14.3.5, Restrictions, p.2]
  8378. // A list item that is private within a parallel region, or that appears in
  8379. // the reduction clause of a parallel construct, must not appear in a
  8380. // lastprivate clause on a worksharing construct if any of the corresponding
  8381. // worksharing regions ever binds to any of the corresponding parallel
  8382. // regions.
  8383. DSAStackTy::DSAVarData TopDVar = DVar;
  8384. if (isOpenMPWorksharingDirective(CurrDir) &&
  8385. !isOpenMPParallelDirective(CurrDir) &&
  8386. !isOpenMPTeamsDirective(CurrDir)) {
  8387. DVar = DSAStack->getImplicitDSA(D, true);
  8388. if (DVar.CKind != OMPC_shared) {
  8389. Diag(ELoc, diag::err_omp_required_access)
  8390. << getOpenMPClauseName(OMPC_lastprivate)
  8391. << getOpenMPClauseName(OMPC_shared);
  8392. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8393. continue;
  8394. }
  8395. }
  8396. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  8397. // A variable of class type (or array thereof) that appears in a
  8398. // lastprivate clause requires an accessible, unambiguous default
  8399. // constructor for the class type, unless the list item is also specified
  8400. // in a firstprivate clause.
  8401. // A variable of class type (or array thereof) that appears in a
  8402. // lastprivate clause requires an accessible, unambiguous copy assignment
  8403. // operator for the class type.
  8404. Type = Context.getBaseElementType(Type).getNonReferenceType();
  8405. auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  8406. Type.getUnqualifiedType(), ".lastprivate.src",
  8407. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8408. auto *PseudoSrcExpr =
  8409. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  8410. auto *DstVD =
  8411. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  8412. D->hasAttrs() ? &D->getAttrs() : nullptr);
  8413. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  8414. // For arrays generate assignment operation for single element and replace
  8415. // it by the original array element in CodeGen.
  8416. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  8417. PseudoDstExpr, PseudoSrcExpr);
  8418. if (AssignmentOp.isInvalid())
  8419. continue;
  8420. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  8421. /*DiscardedValue=*/true);
  8422. if (AssignmentOp.isInvalid())
  8423. continue;
  8424. DeclRefExpr *Ref = nullptr;
  8425. if (!VD && !CurContext->isDependentContext()) {
  8426. if (TopDVar.CKind == OMPC_firstprivate)
  8427. Ref = TopDVar.PrivateCopy;
  8428. else {
  8429. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  8430. if (!IsOpenMPCapturedDecl(D))
  8431. ExprCaptures.push_back(Ref->getDecl());
  8432. }
  8433. if (TopDVar.CKind == OMPC_firstprivate ||
  8434. (!IsOpenMPCapturedDecl(D) &&
  8435. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  8436. ExprResult RefRes = DefaultLvalueConversion(Ref);
  8437. if (!RefRes.isUsable())
  8438. continue;
  8439. ExprResult PostUpdateRes =
  8440. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  8441. RefRes.get());
  8442. if (!PostUpdateRes.isUsable())
  8443. continue;
  8444. ExprPostUpdates.push_back(
  8445. IgnoredValueConversions(PostUpdateRes.get()).get());
  8446. }
  8447. }
  8448. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  8449. Vars.push_back((VD || CurContext->isDependentContext())
  8450. ? RefExpr->IgnoreParens()
  8451. : Ref);
  8452. SrcExprs.push_back(PseudoSrcExpr);
  8453. DstExprs.push_back(PseudoDstExpr);
  8454. AssignmentOps.push_back(AssignmentOp.get());
  8455. }
  8456. if (Vars.empty())
  8457. return nullptr;
  8458. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  8459. Vars, SrcExprs, DstExprs, AssignmentOps,
  8460. buildPreInits(Context, ExprCaptures),
  8461. buildPostUpdate(*this, ExprPostUpdates));
  8462. }
  8463. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  8464. SourceLocation StartLoc,
  8465. SourceLocation LParenLoc,
  8466. SourceLocation EndLoc) {
  8467. SmallVector<Expr *, 8> Vars;
  8468. for (auto &RefExpr : VarList) {
  8469. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  8470. SourceLocation ELoc;
  8471. SourceRange ERange;
  8472. Expr *SimpleRefExpr = RefExpr;
  8473. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  8474. if (Res.second) {
  8475. // It will be analyzed later.
  8476. Vars.push_back(RefExpr);
  8477. }
  8478. ValueDecl *D = Res.first;
  8479. if (!D)
  8480. continue;
  8481. auto *VD = dyn_cast<VarDecl>(D);
  8482. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  8483. // in a Construct]
  8484. // Variables with the predetermined data-sharing attributes may not be
  8485. // listed in data-sharing attributes clauses, except for the cases
  8486. // listed below. For these exceptions only, listing a predetermined
  8487. // variable in a data-sharing attribute clause is allowed and overrides
  8488. // the variable's predetermined data-sharing attributes.
  8489. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  8490. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  8491. DVar.RefExpr) {
  8492. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  8493. << getOpenMPClauseName(OMPC_shared);
  8494. ReportOriginalDSA(*this, DSAStack, D, DVar);
  8495. continue;
  8496. }
  8497. DeclRefExpr *Ref = nullptr;
  8498. if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  8499. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  8500. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  8501. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  8502. ? RefExpr->IgnoreParens()
  8503. : Ref);
  8504. }
  8505. if (Vars.empty())
  8506. return nullptr;
  8507. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  8508. }
  8509. namespace {
  8510. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  8511. DSAStackTy *Stack;
  8512. public:
  8513. bool VisitDeclRefExpr(DeclRefExpr *E) {
  8514. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  8515. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  8516. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  8517. return false;
  8518. if (DVar.CKind != OMPC_unknown)
  8519. return true;
  8520. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  8521. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
  8522. /*FromParent=*/true);
  8523. if (DVarPrivate.CKind != OMPC_unknown)
  8524. return true;
  8525. return false;
  8526. }
  8527. return false;
  8528. }
  8529. bool VisitStmt(Stmt *S) {
  8530. for (auto Child : S->children()) {
  8531. if (Child && Visit(Child))
  8532. return true;
  8533. }
  8534. return false;
  8535. }
  8536. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  8537. };
  8538. } // namespace
  8539. namespace {
  8540. // Transform MemberExpression for specified FieldDecl of current class to
  8541. // DeclRefExpr to specified OMPCapturedExprDecl.
  8542. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  8543. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  8544. ValueDecl *Field;
  8545. DeclRefExpr *CapturedExpr;
  8546. public:
  8547. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  8548. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  8549. ExprResult TransformMemberExpr(MemberExpr *E) {
  8550. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  8551. E->getMemberDecl() == Field) {
  8552. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  8553. return CapturedExpr;
  8554. }
  8555. return BaseTransform::TransformMemberExpr(E);
  8556. }
  8557. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  8558. };
  8559. } // namespace
  8560. template <typename T>
  8561. static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
  8562. const llvm::function_ref<T(ValueDecl *)> &Gen) {
  8563. for (auto &Set : Lookups) {
  8564. for (auto *D : Set) {
  8565. if (auto Res = Gen(cast<ValueDecl>(D)))
  8566. return Res;
  8567. }
  8568. }
  8569. return T();
  8570. }
  8571. static ExprResult
  8572. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  8573. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  8574. const DeclarationNameInfo &ReductionId, QualType Ty,
  8575. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  8576. if (ReductionIdScopeSpec.isInvalid())
  8577. return ExprError();
  8578. SmallVector<UnresolvedSet<8>, 4> Lookups;
  8579. if (S) {
  8580. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  8581. Lookup.suppressDiagnostics();
  8582. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  8583. auto *D = Lookup.getRepresentativeDecl();
  8584. do {
  8585. S = S->getParent();
  8586. } while (S && !S->isDeclScope(D));
  8587. if (S)
  8588. S = S->getParent();
  8589. Lookups.push_back(UnresolvedSet<8>());
  8590. Lookups.back().append(Lookup.begin(), Lookup.end());
  8591. Lookup.clear();
  8592. }
  8593. } else if (auto *ULE =
  8594. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  8595. Lookups.push_back(UnresolvedSet<8>());
  8596. Decl *PrevD = nullptr;
  8597. for (auto *D : ULE->decls()) {
  8598. if (D == PrevD)
  8599. Lookups.push_back(UnresolvedSet<8>());
  8600. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  8601. Lookups.back().addDecl(DRD);
  8602. PrevD = D;
  8603. }
  8604. }
  8605. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  8606. Ty->isInstantiationDependentType() ||
  8607. Ty->containsUnexpandedParameterPack() ||
  8608. filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
  8609. return !D->isInvalidDecl() &&
  8610. (D->getType()->isDependentType() ||
  8611. D->getType()->isInstantiationDependentType() ||
  8612. D->getType()->containsUnexpandedParameterPack());
  8613. })) {
  8614. UnresolvedSet<8> ResSet;
  8615. for (auto &Set : Lookups) {
  8616. ResSet.append(Set.begin(), Set.end());
  8617. // The last item marks the end of all declarations at the specified scope.
  8618. ResSet.addDecl(Set[Set.size() - 1]);
  8619. }
  8620. return UnresolvedLookupExpr::Create(
  8621. SemaRef.Context, /*NamingClass=*/nullptr,
  8622. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  8623. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  8624. }
  8625. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  8626. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  8627. if (!D->isInvalidDecl() &&
  8628. SemaRef.Context.hasSameType(D->getType(), Ty))
  8629. return D;
  8630. return nullptr;
  8631. }))
  8632. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  8633. if (auto *VD = filterLookupForUDR<ValueDecl *>(
  8634. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  8635. if (!D->isInvalidDecl() &&
  8636. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  8637. !Ty.isMoreQualifiedThan(D->getType()))
  8638. return D;
  8639. return nullptr;
  8640. })) {
  8641. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  8642. /*DetectVirtual=*/false);
  8643. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  8644. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  8645. VD->getType().getUnqualifiedType()))) {
  8646. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  8647. /*DiagID=*/0) !=
  8648. Sema::AR_inaccessible) {
  8649. SemaRef.BuildBasePathArray(Paths, BasePath);
  8650. return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
  8651. }
  8652. }
  8653. }
  8654. }
  8655. if (ReductionIdScopeSpec.isSet()) {
  8656. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  8657. return ExprError();
  8658. }
  8659. return ExprEmpty();
  8660. }
  8661. namespace {
  8662. /// Data for the reduction-based clauses.
  8663. struct ReductionData {
  8664. /// List of original reduction items.
  8665. SmallVector<Expr *, 8> Vars;
  8666. /// List of private copies of the reduction items.
  8667. SmallVector<Expr *, 8> Privates;
  8668. /// LHS expressions for the reduction_op expressions.
  8669. SmallVector<Expr *, 8> LHSs;
  8670. /// RHS expressions for the reduction_op expressions.
  8671. SmallVector<Expr *, 8> RHSs;
  8672. /// Reduction operation expression.
  8673. SmallVector<Expr *, 8> ReductionOps;
  8674. /// Taskgroup descriptors for the corresponding reduction items in
  8675. /// in_reduction clauses.
  8676. SmallVector<Expr *, 8> TaskgroupDescriptors;
  8677. /// List of captures for clause.
  8678. SmallVector<Decl *, 4> ExprCaptures;
  8679. /// List of postupdate expressions.
  8680. SmallVector<Expr *, 4> ExprPostUpdates;
  8681. ReductionData() = delete;
  8682. /// Reserves required memory for the reduction data.
  8683. ReductionData(unsigned Size) {
  8684. Vars.reserve(Size);
  8685. Privates.reserve(Size);
  8686. LHSs.reserve(Size);
  8687. RHSs.reserve(Size);
  8688. ReductionOps.reserve(Size);
  8689. TaskgroupDescriptors.reserve(Size);
  8690. ExprCaptures.reserve(Size);
  8691. ExprPostUpdates.reserve(Size);
  8692. }
  8693. /// Stores reduction item and reduction operation only (required for dependent
  8694. /// reduction item).
  8695. void push(Expr *Item, Expr *ReductionOp) {
  8696. Vars.emplace_back(Item);
  8697. Privates.emplace_back(nullptr);
  8698. LHSs.emplace_back(nullptr);
  8699. RHSs.emplace_back(nullptr);
  8700. ReductionOps.emplace_back(ReductionOp);
  8701. TaskgroupDescriptors.emplace_back(nullptr);
  8702. }
  8703. /// Stores reduction data.
  8704. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  8705. Expr *TaskgroupDescriptor) {
  8706. Vars.emplace_back(Item);
  8707. Privates.emplace_back(Private);
  8708. LHSs.emplace_back(LHS);
  8709. RHSs.emplace_back(RHS);
  8710. ReductionOps.emplace_back(ReductionOp);
  8711. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  8712. }
  8713. };
  8714. } // namespace
  8715. static bool CheckOMPArraySectionConstantForReduction(
  8716. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  8717. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  8718. const Expr *Length = OASE->getLength();
  8719. if (Length == nullptr) {
  8720. // For array sections of the form [1:] or [:], we would need to analyze
  8721. // the lower bound...
  8722. if (OASE->getColonLoc().isValid())
  8723. return false;
  8724. // This is an array subscript which has implicit length 1!
  8725. SingleElement = true;
  8726. ArraySizes.push_back(llvm::APSInt::get(1));
  8727. } else {
  8728. llvm::APSInt ConstantLengthValue;
  8729. if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
  8730. return false;
  8731. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  8732. ArraySizes.push_back(ConstantLengthValue);
  8733. }
  8734. // Get the base of this array section and walk up from there.
  8735. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  8736. // We require length = 1 for all array sections except the right-most to
  8737. // guarantee that the memory region is contiguous and has no holes in it.
  8738. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  8739. Length = TempOASE->getLength();
  8740. if (Length == nullptr) {
  8741. // For array sections of the form [1:] or [:], we would need to analyze
  8742. // the lower bound...
  8743. if (OASE->getColonLoc().isValid())
  8744. return false;
  8745. // This is an array subscript which has implicit length 1!
  8746. ArraySizes.push_back(llvm::APSInt::get(1));
  8747. } else {
  8748. llvm::APSInt ConstantLengthValue;
  8749. if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
  8750. ConstantLengthValue.getSExtValue() != 1)
  8751. return false;
  8752. ArraySizes.push_back(ConstantLengthValue);
  8753. }
  8754. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  8755. }
  8756. // If we have a single element, we don't need to add the implicit lengths.
  8757. if (!SingleElement) {
  8758. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  8759. // Has implicit length 1!
  8760. ArraySizes.push_back(llvm::APSInt::get(1));
  8761. Base = TempASE->getBase()->IgnoreParenImpCasts();
  8762. }
  8763. }
  8764. // This array section can be privatized as a single value or as a constant
  8765. // sized array.
  8766. return true;
  8767. }
  8768. static bool ActOnOMPReductionKindClause(
  8769. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  8770. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  8771. SourceLocation ColonLoc, SourceLocation EndLoc,
  8772. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  8773. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  8774. auto DN = ReductionId.getName();
  8775. auto OOK = DN.getCXXOverloadedOperator();
  8776. BinaryOperatorKind BOK = BO_Comma;
  8777. ASTContext &Context = S.Context;
  8778. // OpenMP [2.14.3.6, reduction clause]
  8779. // C
  8780. // reduction-identifier is either an identifier or one of the following
  8781. // operators: +, -, *, &, |, ^, && and ||
  8782. // C++
  8783. // reduction-identifier is either an id-expression or one of the following
  8784. // operators: +, -, *, &, |, ^, && and ||
  8785. switch (OOK) {
  8786. case OO_Plus:
  8787. case OO_Minus:
  8788. BOK = BO_Add;
  8789. break;
  8790. case OO_Star:
  8791. BOK = BO_Mul;
  8792. break;
  8793. case OO_Amp:
  8794. BOK = BO_And;
  8795. break;
  8796. case OO_Pipe:
  8797. BOK = BO_Or;
  8798. break;
  8799. case OO_Caret:
  8800. BOK = BO_Xor;
  8801. break;
  8802. case OO_AmpAmp:
  8803. BOK = BO_LAnd;
  8804. break;
  8805. case OO_PipePipe:
  8806. BOK = BO_LOr;
  8807. break;
  8808. case OO_New:
  8809. case OO_Delete:
  8810. case OO_Array_New:
  8811. case OO_Array_Delete:
  8812. case OO_Slash:
  8813. case OO_Percent:
  8814. case OO_Tilde:
  8815. case OO_Exclaim:
  8816. case OO_Equal:
  8817. case OO_Less:
  8818. case OO_Greater:
  8819. case OO_LessEqual:
  8820. case OO_GreaterEqual:
  8821. case OO_PlusEqual:
  8822. case OO_MinusEqual:
  8823. case OO_StarEqual:
  8824. case OO_SlashEqual:
  8825. case OO_PercentEqual:
  8826. case OO_CaretEqual:
  8827. case OO_AmpEqual:
  8828. case OO_PipeEqual:
  8829. case OO_LessLess:
  8830. case OO_GreaterGreater:
  8831. case OO_LessLessEqual:
  8832. case OO_GreaterGreaterEqual:
  8833. case OO_EqualEqual:
  8834. case OO_ExclaimEqual:
  8835. case OO_PlusPlus:
  8836. case OO_MinusMinus:
  8837. case OO_Comma:
  8838. case OO_ArrowStar:
  8839. case OO_Arrow:
  8840. case OO_Call:
  8841. case OO_Subscript:
  8842. case OO_Conditional:
  8843. case OO_Coawait:
  8844. case NUM_OVERLOADED_OPERATORS:
  8845. llvm_unreachable("Unexpected reduction identifier");
  8846. case OO_None:
  8847. if (auto *II = DN.getAsIdentifierInfo()) {
  8848. if (II->isStr("max"))
  8849. BOK = BO_GT;
  8850. else if (II->isStr("min"))
  8851. BOK = BO_LT;
  8852. }
  8853. break;
  8854. }
  8855. SourceRange ReductionIdRange;
  8856. if (ReductionIdScopeSpec.isValid())
  8857. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  8858. else
  8859. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  8860. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  8861. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  8862. bool FirstIter = true;
  8863. for (auto RefExpr : VarList) {
  8864. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  8865. // OpenMP [2.1, C/C++]
  8866. // A list item is a variable or array section, subject to the restrictions
  8867. // specified in Section 2.4 on page 42 and in each of the sections
  8868. // describing clauses and directives for which a list appears.
  8869. // OpenMP [2.14.3.3, Restrictions, p.1]
  8870. // A variable that is part of another variable (as an array or
  8871. // structure element) cannot appear in a private clause.
  8872. if (!FirstIter && IR != ER)
  8873. ++IR;
  8874. FirstIter = false;
  8875. SourceLocation ELoc;
  8876. SourceRange ERange;
  8877. Expr *SimpleRefExpr = RefExpr;
  8878. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  8879. /*AllowArraySection=*/true);
  8880. if (Res.second) {
  8881. // Try to find 'declare reduction' corresponding construct before using
  8882. // builtin/overloaded operators.
  8883. QualType Type = Context.DependentTy;
  8884. CXXCastPath BasePath;
  8885. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  8886. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  8887. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  8888. Expr *ReductionOp = nullptr;
  8889. if (S.CurContext->isDependentContext() &&
  8890. (DeclareReductionRef.isUnset() ||
  8891. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  8892. ReductionOp = DeclareReductionRef.get();
  8893. // It will be analyzed later.
  8894. RD.push(RefExpr, ReductionOp);
  8895. }
  8896. ValueDecl *D = Res.first;
  8897. if (!D)
  8898. continue;
  8899. Expr *TaskgroupDescriptor = nullptr;
  8900. QualType Type;
  8901. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  8902. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  8903. if (ASE)
  8904. Type = ASE->getType().getNonReferenceType();
  8905. else if (OASE) {
  8906. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  8907. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  8908. Type = ATy->getElementType();
  8909. else
  8910. Type = BaseType->getPointeeType();
  8911. Type = Type.getNonReferenceType();
  8912. } else
  8913. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  8914. auto *VD = dyn_cast<VarDecl>(D);
  8915. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  8916. // A variable that appears in a private clause must not have an incomplete
  8917. // type or a reference type.
  8918. if (S.RequireCompleteType(ELoc, Type,
  8919. diag::err_omp_reduction_incomplete_type))
  8920. continue;
  8921. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  8922. // A list item that appears in a reduction clause must not be
  8923. // const-qualified.
  8924. if (Type.getNonReferenceType().isConstant(Context)) {
  8925. S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
  8926. if (!ASE && !OASE) {
  8927. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  8928. VarDecl::DeclarationOnly;
  8929. S.Diag(D->getLocation(),
  8930. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  8931. << D;
  8932. }
  8933. continue;
  8934. }
  8935. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  8936. // If a list-item is a reference type then it must bind to the same object
  8937. // for all threads of the team.
  8938. if (!ASE && !OASE && VD) {
  8939. VarDecl *VDDef = VD->getDefinition();
  8940. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  8941. DSARefChecker Check(Stack);
  8942. if (Check.Visit(VDDef->getInit())) {
  8943. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  8944. << getOpenMPClauseName(ClauseKind) << ERange;
  8945. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  8946. continue;
  8947. }
  8948. }
  8949. }
  8950. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  8951. // in a Construct]
  8952. // Variables with the predetermined data-sharing attributes may not be
  8953. // listed in data-sharing attributes clauses, except for the cases
  8954. // listed below. For these exceptions only, listing a predetermined
  8955. // variable in a data-sharing attribute clause is allowed and overrides
  8956. // the variable's predetermined data-sharing attributes.
  8957. // OpenMP [2.14.3.6, Restrictions, p.3]
  8958. // Any number of reduction clauses can be specified on the directive,
  8959. // but a list item can appear only once in the reduction clauses for that
  8960. // directive.
  8961. DSAStackTy::DSAVarData DVar;
  8962. DVar = Stack->getTopDSA(D, false);
  8963. if (DVar.CKind == OMPC_reduction) {
  8964. S.Diag(ELoc, diag::err_omp_once_referenced)
  8965. << getOpenMPClauseName(ClauseKind);
  8966. if (DVar.RefExpr)
  8967. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  8968. continue;
  8969. } else if (DVar.CKind != OMPC_unknown) {
  8970. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  8971. << getOpenMPClauseName(DVar.CKind)
  8972. << getOpenMPClauseName(OMPC_reduction);
  8973. ReportOriginalDSA(S, Stack, D, DVar);
  8974. continue;
  8975. }
  8976. // OpenMP [2.14.3.6, Restrictions, p.1]
  8977. // A list item that appears in a reduction clause of a worksharing
  8978. // construct must be shared in the parallel regions to which any of the
  8979. // worksharing regions arising from the worksharing construct bind.
  8980. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  8981. if (isOpenMPWorksharingDirective(CurrDir) &&
  8982. !isOpenMPParallelDirective(CurrDir) &&
  8983. !isOpenMPTeamsDirective(CurrDir)) {
  8984. DVar = Stack->getImplicitDSA(D, true);
  8985. if (DVar.CKind != OMPC_shared) {
  8986. S.Diag(ELoc, diag::err_omp_required_access)
  8987. << getOpenMPClauseName(OMPC_reduction)
  8988. << getOpenMPClauseName(OMPC_shared);
  8989. ReportOriginalDSA(S, Stack, D, DVar);
  8990. continue;
  8991. }
  8992. }
  8993. // Try to find 'declare reduction' corresponding construct before using
  8994. // builtin/overloaded operators.
  8995. CXXCastPath BasePath;
  8996. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  8997. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  8998. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  8999. if (DeclareReductionRef.isInvalid())
  9000. continue;
  9001. if (S.CurContext->isDependentContext() &&
  9002. (DeclareReductionRef.isUnset() ||
  9003. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  9004. RD.push(RefExpr, DeclareReductionRef.get());
  9005. continue;
  9006. }
  9007. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  9008. // Not allowed reduction identifier is found.
  9009. S.Diag(ReductionId.getLocStart(),
  9010. diag::err_omp_unknown_reduction_identifier)
  9011. << Type << ReductionIdRange;
  9012. continue;
  9013. }
  9014. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  9015. // The type of a list item that appears in a reduction clause must be valid
  9016. // for the reduction-identifier. For a max or min reduction in C, the type
  9017. // of the list item must be an allowed arithmetic data type: char, int,
  9018. // float, double, or _Bool, possibly modified with long, short, signed, or
  9019. // unsigned. For a max or min reduction in C++, the type of the list item
  9020. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  9021. // double, or bool, possibly modified with long, short, signed, or unsigned.
  9022. if (DeclareReductionRef.isUnset()) {
  9023. if ((BOK == BO_GT || BOK == BO_LT) &&
  9024. !(Type->isScalarType() ||
  9025. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  9026. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  9027. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  9028. if (!ASE && !OASE) {
  9029. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9030. VarDecl::DeclarationOnly;
  9031. S.Diag(D->getLocation(),
  9032. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9033. << D;
  9034. }
  9035. continue;
  9036. }
  9037. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  9038. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  9039. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  9040. << getOpenMPClauseName(ClauseKind);
  9041. if (!ASE && !OASE) {
  9042. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9043. VarDecl::DeclarationOnly;
  9044. S.Diag(D->getLocation(),
  9045. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9046. << D;
  9047. }
  9048. continue;
  9049. }
  9050. }
  9051. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  9052. auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  9053. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9054. auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  9055. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9056. auto PrivateTy = Type;
  9057. // Try if we can determine constant lengths for all array sections and avoid
  9058. // the VLA.
  9059. bool ConstantLengthOASE = false;
  9060. if (OASE) {
  9061. bool SingleElement;
  9062. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  9063. ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
  9064. Context, OASE, SingleElement, ArraySizes);
  9065. // If we don't have a single element, we must emit a constant array type.
  9066. if (ConstantLengthOASE && !SingleElement) {
  9067. for (auto &Size : ArraySizes) {
  9068. PrivateTy = Context.getConstantArrayType(
  9069. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  9070. }
  9071. }
  9072. }
  9073. if ((OASE && !ConstantLengthOASE) ||
  9074. (!OASE && !ASE &&
  9075. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  9076. // For arrays/array sections only:
  9077. // Create pseudo array type for private copy. The size for this array will
  9078. // be generated during codegen.
  9079. // For array subscripts or single variables Private Ty is the same as Type
  9080. // (type of the variable or single array element).
  9081. PrivateTy = Context.getVariableArrayType(
  9082. Type,
  9083. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  9084. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  9085. } else if (!ASE && !OASE &&
  9086. Context.getAsArrayType(D->getType().getNonReferenceType()))
  9087. PrivateTy = D->getType().getNonReferenceType();
  9088. // Private copy.
  9089. auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  9090. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9091. // Add initializer for private variable.
  9092. Expr *Init = nullptr;
  9093. auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  9094. auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  9095. if (DeclareReductionRef.isUsable()) {
  9096. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  9097. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  9098. if (DRD->getInitializer()) {
  9099. Init = DRDRef;
  9100. RHSVD->setInit(DRDRef);
  9101. RHSVD->setInitStyle(VarDecl::CallInit);
  9102. }
  9103. } else {
  9104. switch (BOK) {
  9105. case BO_Add:
  9106. case BO_Xor:
  9107. case BO_Or:
  9108. case BO_LOr:
  9109. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  9110. if (Type->isScalarType() || Type->isAnyComplexType())
  9111. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  9112. break;
  9113. case BO_Mul:
  9114. case BO_LAnd:
  9115. if (Type->isScalarType() || Type->isAnyComplexType()) {
  9116. // '*' and '&&' reduction ops - initializer is '1'.
  9117. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  9118. }
  9119. break;
  9120. case BO_And: {
  9121. // '&' reduction op - initializer is '~0'.
  9122. QualType OrigType = Type;
  9123. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  9124. Type = ComplexTy->getElementType();
  9125. if (Type->isRealFloatingType()) {
  9126. llvm::APFloat InitValue =
  9127. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  9128. /*isIEEE=*/true);
  9129. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9130. Type, ELoc);
  9131. } else if (Type->isScalarType()) {
  9132. auto Size = Context.getTypeSize(Type);
  9133. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  9134. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  9135. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9136. }
  9137. if (Init && OrigType->isAnyComplexType()) {
  9138. // Init = 0xFFFF + 0xFFFFi;
  9139. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  9140. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  9141. }
  9142. Type = OrigType;
  9143. break;
  9144. }
  9145. case BO_LT:
  9146. case BO_GT: {
  9147. // 'min' reduction op - initializer is 'Largest representable number in
  9148. // the reduction list item type'.
  9149. // 'max' reduction op - initializer is 'Least representable number in
  9150. // the reduction list item type'.
  9151. if (Type->isIntegerType() || Type->isPointerType()) {
  9152. bool IsSigned = Type->hasSignedIntegerRepresentation();
  9153. auto Size = Context.getTypeSize(Type);
  9154. QualType IntTy =
  9155. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  9156. llvm::APInt InitValue =
  9157. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  9158. : llvm::APInt::getMinValue(Size)
  9159. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  9160. : llvm::APInt::getMaxValue(Size);
  9161. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  9162. if (Type->isPointerType()) {
  9163. // Cast to pointer type.
  9164. auto CastExpr = S.BuildCStyleCastExpr(
  9165. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  9166. if (CastExpr.isInvalid())
  9167. continue;
  9168. Init = CastExpr.get();
  9169. }
  9170. } else if (Type->isRealFloatingType()) {
  9171. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  9172. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  9173. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  9174. Type, ELoc);
  9175. }
  9176. break;
  9177. }
  9178. case BO_PtrMemD:
  9179. case BO_PtrMemI:
  9180. case BO_MulAssign:
  9181. case BO_Div:
  9182. case BO_Rem:
  9183. case BO_Sub:
  9184. case BO_Shl:
  9185. case BO_Shr:
  9186. case BO_LE:
  9187. case BO_GE:
  9188. case BO_EQ:
  9189. case BO_NE:
  9190. case BO_AndAssign:
  9191. case BO_XorAssign:
  9192. case BO_OrAssign:
  9193. case BO_Assign:
  9194. case BO_AddAssign:
  9195. case BO_SubAssign:
  9196. case BO_DivAssign:
  9197. case BO_RemAssign:
  9198. case BO_ShlAssign:
  9199. case BO_ShrAssign:
  9200. case BO_Comma:
  9201. llvm_unreachable("Unexpected reduction operation");
  9202. }
  9203. }
  9204. if (Init && DeclareReductionRef.isUnset())
  9205. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  9206. else if (!Init)
  9207. S.ActOnUninitializedDecl(RHSVD);
  9208. if (RHSVD->isInvalidDecl())
  9209. continue;
  9210. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  9211. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  9212. << Type << ReductionIdRange;
  9213. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  9214. VarDecl::DeclarationOnly;
  9215. S.Diag(D->getLocation(),
  9216. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9217. << D;
  9218. continue;
  9219. }
  9220. // Store initializer for single element in private copy. Will be used during
  9221. // codegen.
  9222. PrivateVD->setInit(RHSVD->getInit());
  9223. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  9224. auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  9225. ExprResult ReductionOp;
  9226. if (DeclareReductionRef.isUsable()) {
  9227. QualType RedTy = DeclareReductionRef.get()->getType();
  9228. QualType PtrRedTy = Context.getPointerType(RedTy);
  9229. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  9230. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  9231. if (!BasePath.empty()) {
  9232. LHS = S.DefaultLvalueConversion(LHS.get());
  9233. RHS = S.DefaultLvalueConversion(RHS.get());
  9234. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9235. CK_UncheckedDerivedToBase, LHS.get(),
  9236. &BasePath, LHS.get()->getValueKind());
  9237. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  9238. CK_UncheckedDerivedToBase, RHS.get(),
  9239. &BasePath, RHS.get()->getValueKind());
  9240. }
  9241. FunctionProtoType::ExtProtoInfo EPI;
  9242. QualType Params[] = {PtrRedTy, PtrRedTy};
  9243. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  9244. auto *OVE = new (Context) OpaqueValueExpr(
  9245. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  9246. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  9247. Expr *Args[] = {LHS.get(), RHS.get()};
  9248. ReductionOp = new (Context)
  9249. CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  9250. } else {
  9251. ReductionOp = S.BuildBinOp(
  9252. Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
  9253. if (ReductionOp.isUsable()) {
  9254. if (BOK != BO_LT && BOK != BO_GT) {
  9255. ReductionOp =
  9256. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9257. BO_Assign, LHSDRE, ReductionOp.get());
  9258. } else {
  9259. auto *ConditionalOp = new (Context)
  9260. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  9261. Type, VK_LValue, OK_Ordinary);
  9262. ReductionOp =
  9263. S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
  9264. BO_Assign, LHSDRE, ConditionalOp);
  9265. }
  9266. if (ReductionOp.isUsable())
  9267. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
  9268. }
  9269. if (!ReductionOp.isUsable())
  9270. continue;
  9271. }
  9272. // OpenMP [2.15.4.6, Restrictions, p.2]
  9273. // A list item that appears in an in_reduction clause of a task construct
  9274. // must appear in a task_reduction clause of a construct associated with a
  9275. // taskgroup region that includes the participating task in its taskgroup
  9276. // set. The construct associated with the innermost region that meets this
  9277. // condition must specify the same reduction-identifier as the in_reduction
  9278. // clause.
  9279. if (ClauseKind == OMPC_in_reduction) {
  9280. SourceRange ParentSR;
  9281. BinaryOperatorKind ParentBOK;
  9282. const Expr *ParentReductionOp;
  9283. Expr *ParentBOKTD, *ParentReductionOpTD;
  9284. DSAStackTy::DSAVarData ParentBOKDSA =
  9285. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  9286. ParentBOKTD);
  9287. DSAStackTy::DSAVarData ParentReductionOpDSA =
  9288. Stack->getTopMostTaskgroupReductionData(
  9289. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  9290. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  9291. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  9292. if (!IsParentBOK && !IsParentReductionOp) {
  9293. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  9294. continue;
  9295. }
  9296. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  9297. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  9298. IsParentReductionOp) {
  9299. bool EmitError = true;
  9300. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  9301. llvm::FoldingSetNodeID RedId, ParentRedId;
  9302. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  9303. DeclareReductionRef.get()->Profile(RedId, Context,
  9304. /*Canonical=*/true);
  9305. EmitError = RedId != ParentRedId;
  9306. }
  9307. if (EmitError) {
  9308. S.Diag(ReductionId.getLocStart(),
  9309. diag::err_omp_reduction_identifier_mismatch)
  9310. << ReductionIdRange << RefExpr->getSourceRange();
  9311. S.Diag(ParentSR.getBegin(),
  9312. diag::note_omp_previous_reduction_identifier)
  9313. << ParentSR
  9314. << (IsParentBOK ? ParentBOKDSA.RefExpr
  9315. : ParentReductionOpDSA.RefExpr)
  9316. ->getSourceRange();
  9317. continue;
  9318. }
  9319. }
  9320. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  9321. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  9322. }
  9323. DeclRefExpr *Ref = nullptr;
  9324. Expr *VarsExpr = RefExpr->IgnoreParens();
  9325. if (!VD && !S.CurContext->isDependentContext()) {
  9326. if (ASE || OASE) {
  9327. TransformExprToCaptures RebuildToCapture(S, D);
  9328. VarsExpr =
  9329. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  9330. Ref = RebuildToCapture.getCapturedExpr();
  9331. } else {
  9332. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  9333. }
  9334. if (!S.IsOpenMPCapturedDecl(D)) {
  9335. RD.ExprCaptures.emplace_back(Ref->getDecl());
  9336. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9337. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  9338. if (!RefRes.isUsable())
  9339. continue;
  9340. ExprResult PostUpdateRes =
  9341. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9342. RefRes.get());
  9343. if (!PostUpdateRes.isUsable())
  9344. continue;
  9345. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  9346. Stack->getCurrentDirective() == OMPD_taskgroup) {
  9347. S.Diag(RefExpr->getExprLoc(),
  9348. diag::err_omp_reduction_non_addressable_expression)
  9349. << RefExpr->getSourceRange();
  9350. continue;
  9351. }
  9352. RD.ExprPostUpdates.emplace_back(
  9353. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  9354. }
  9355. }
  9356. }
  9357. // All reduction items are still marked as reduction (to do not increase
  9358. // code base size).
  9359. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  9360. if (CurrDir == OMPD_taskgroup) {
  9361. if (DeclareReductionRef.isUsable())
  9362. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  9363. DeclareReductionRef.get());
  9364. else
  9365. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  9366. }
  9367. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  9368. TaskgroupDescriptor);
  9369. }
  9370. return RD.Vars.empty();
  9371. }
  9372. OMPClause *Sema::ActOnOpenMPReductionClause(
  9373. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9374. SourceLocation ColonLoc, SourceLocation EndLoc,
  9375. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9376. ArrayRef<Expr *> UnresolvedReductions) {
  9377. ReductionData RD(VarList.size());
  9378. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  9379. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9380. ReductionIdScopeSpec, ReductionId,
  9381. UnresolvedReductions, RD))
  9382. return nullptr;
  9383. return OMPReductionClause::Create(
  9384. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9385. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9386. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9387. buildPreInits(Context, RD.ExprCaptures),
  9388. buildPostUpdate(*this, RD.ExprPostUpdates));
  9389. }
  9390. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  9391. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9392. SourceLocation ColonLoc, SourceLocation EndLoc,
  9393. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9394. ArrayRef<Expr *> UnresolvedReductions) {
  9395. ReductionData RD(VarList.size());
  9396. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
  9397. VarList, StartLoc, LParenLoc, ColonLoc,
  9398. EndLoc, ReductionIdScopeSpec, ReductionId,
  9399. UnresolvedReductions, RD))
  9400. return nullptr;
  9401. return OMPTaskReductionClause::Create(
  9402. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9403. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9404. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  9405. buildPreInits(Context, RD.ExprCaptures),
  9406. buildPostUpdate(*this, RD.ExprPostUpdates));
  9407. }
  9408. OMPClause *Sema::ActOnOpenMPInReductionClause(
  9409. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  9410. SourceLocation ColonLoc, SourceLocation EndLoc,
  9411. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  9412. ArrayRef<Expr *> UnresolvedReductions) {
  9413. ReductionData RD(VarList.size());
  9414. if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  9415. StartLoc, LParenLoc, ColonLoc, EndLoc,
  9416. ReductionIdScopeSpec, ReductionId,
  9417. UnresolvedReductions, RD))
  9418. return nullptr;
  9419. return OMPInReductionClause::Create(
  9420. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  9421. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  9422. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  9423. buildPreInits(Context, RD.ExprCaptures),
  9424. buildPostUpdate(*this, RD.ExprPostUpdates));
  9425. }
  9426. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  9427. SourceLocation LinLoc) {
  9428. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  9429. LinKind == OMPC_LINEAR_unknown) {
  9430. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  9431. return true;
  9432. }
  9433. return false;
  9434. }
  9435. bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
  9436. OpenMPLinearClauseKind LinKind,
  9437. QualType Type) {
  9438. auto *VD = dyn_cast_or_null<VarDecl>(D);
  9439. // A variable must not have an incomplete type or a reference type.
  9440. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  9441. return true;
  9442. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  9443. !Type->isReferenceType()) {
  9444. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  9445. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  9446. return true;
  9447. }
  9448. Type = Type.getNonReferenceType();
  9449. // A list item must not be const-qualified.
  9450. if (Type.isConstant(Context)) {
  9451. Diag(ELoc, diag::err_omp_const_variable)
  9452. << getOpenMPClauseName(OMPC_linear);
  9453. if (D) {
  9454. bool IsDecl =
  9455. !VD ||
  9456. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9457. Diag(D->getLocation(),
  9458. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9459. << D;
  9460. }
  9461. return true;
  9462. }
  9463. // A list item must be of integral or pointer type.
  9464. Type = Type.getUnqualifiedType().getCanonicalType();
  9465. const auto *Ty = Type.getTypePtrOrNull();
  9466. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  9467. !Ty->isPointerType())) {
  9468. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  9469. if (D) {
  9470. bool IsDecl =
  9471. !VD ||
  9472. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9473. Diag(D->getLocation(),
  9474. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9475. << D;
  9476. }
  9477. return true;
  9478. }
  9479. return false;
  9480. }
  9481. OMPClause *Sema::ActOnOpenMPLinearClause(
  9482. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  9483. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  9484. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  9485. SmallVector<Expr *, 8> Vars;
  9486. SmallVector<Expr *, 8> Privates;
  9487. SmallVector<Expr *, 8> Inits;
  9488. SmallVector<Decl *, 4> ExprCaptures;
  9489. SmallVector<Expr *, 4> ExprPostUpdates;
  9490. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  9491. LinKind = OMPC_LINEAR_val;
  9492. for (auto &RefExpr : VarList) {
  9493. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9494. SourceLocation ELoc;
  9495. SourceRange ERange;
  9496. Expr *SimpleRefExpr = RefExpr;
  9497. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9498. /*AllowArraySection=*/false);
  9499. if (Res.second) {
  9500. // It will be analyzed later.
  9501. Vars.push_back(RefExpr);
  9502. Privates.push_back(nullptr);
  9503. Inits.push_back(nullptr);
  9504. }
  9505. ValueDecl *D = Res.first;
  9506. if (!D)
  9507. continue;
  9508. QualType Type = D->getType();
  9509. auto *VD = dyn_cast<VarDecl>(D);
  9510. // OpenMP [2.14.3.7, linear clause]
  9511. // A list-item cannot appear in more than one linear clause.
  9512. // A list-item that appears in a linear clause cannot appear in any
  9513. // other data-sharing attribute clause.
  9514. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  9515. if (DVar.RefExpr) {
  9516. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9517. << getOpenMPClauseName(OMPC_linear);
  9518. ReportOriginalDSA(*this, DSAStack, D, DVar);
  9519. continue;
  9520. }
  9521. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  9522. continue;
  9523. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  9524. // Build private copy of original var.
  9525. auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
  9526. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9527. auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  9528. // Build var to save initial value.
  9529. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  9530. Expr *InitExpr;
  9531. DeclRefExpr *Ref = nullptr;
  9532. if (!VD && !CurContext->isDependentContext()) {
  9533. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9534. if (!IsOpenMPCapturedDecl(D)) {
  9535. ExprCaptures.push_back(Ref->getDecl());
  9536. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  9537. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9538. if (!RefRes.isUsable())
  9539. continue;
  9540. ExprResult PostUpdateRes =
  9541. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  9542. SimpleRefExpr, RefRes.get());
  9543. if (!PostUpdateRes.isUsable())
  9544. continue;
  9545. ExprPostUpdates.push_back(
  9546. IgnoredValueConversions(PostUpdateRes.get()).get());
  9547. }
  9548. }
  9549. }
  9550. if (LinKind == OMPC_LINEAR_uval)
  9551. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  9552. else
  9553. InitExpr = VD ? SimpleRefExpr : Ref;
  9554. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  9555. /*DirectInit=*/false);
  9556. auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  9557. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  9558. Vars.push_back((VD || CurContext->isDependentContext())
  9559. ? RefExpr->IgnoreParens()
  9560. : Ref);
  9561. Privates.push_back(PrivateRef);
  9562. Inits.push_back(InitRef);
  9563. }
  9564. if (Vars.empty())
  9565. return nullptr;
  9566. Expr *StepExpr = Step;
  9567. Expr *CalcStepExpr = nullptr;
  9568. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  9569. !Step->isInstantiationDependent() &&
  9570. !Step->containsUnexpandedParameterPack()) {
  9571. SourceLocation StepLoc = Step->getLocStart();
  9572. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  9573. if (Val.isInvalid())
  9574. return nullptr;
  9575. StepExpr = Val.get();
  9576. // Build var to save the step value.
  9577. VarDecl *SaveVar =
  9578. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  9579. ExprResult SaveRef =
  9580. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  9581. ExprResult CalcStep =
  9582. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  9583. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  9584. // Warn about zero linear step (it would be probably better specified as
  9585. // making corresponding variables 'const').
  9586. llvm::APSInt Result;
  9587. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  9588. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  9589. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  9590. << (Vars.size() > 1);
  9591. if (!IsConstant && CalcStep.isUsable()) {
  9592. // Calculate the step beforehand instead of doing this on each iteration.
  9593. // (This is not used if the number of iterations may be kfold-ed).
  9594. CalcStepExpr = CalcStep.get();
  9595. }
  9596. }
  9597. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  9598. ColonLoc, EndLoc, Vars, Privates, Inits,
  9599. StepExpr, CalcStepExpr,
  9600. buildPreInits(Context, ExprCaptures),
  9601. buildPostUpdate(*this, ExprPostUpdates));
  9602. }
  9603. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  9604. Expr *NumIterations, Sema &SemaRef,
  9605. Scope *S, DSAStackTy *Stack) {
  9606. // Walk the vars and build update/final expressions for the CodeGen.
  9607. SmallVector<Expr *, 8> Updates;
  9608. SmallVector<Expr *, 8> Finals;
  9609. Expr *Step = Clause.getStep();
  9610. Expr *CalcStep = Clause.getCalcStep();
  9611. // OpenMP [2.14.3.7, linear clause]
  9612. // If linear-step is not specified it is assumed to be 1.
  9613. if (Step == nullptr)
  9614. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  9615. else if (CalcStep) {
  9616. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  9617. }
  9618. bool HasErrors = false;
  9619. auto CurInit = Clause.inits().begin();
  9620. auto CurPrivate = Clause.privates().begin();
  9621. auto LinKind = Clause.getModifier();
  9622. for (auto &RefExpr : Clause.varlists()) {
  9623. SourceLocation ELoc;
  9624. SourceRange ERange;
  9625. Expr *SimpleRefExpr = RefExpr;
  9626. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
  9627. /*AllowArraySection=*/false);
  9628. ValueDecl *D = Res.first;
  9629. if (Res.second || !D) {
  9630. Updates.push_back(nullptr);
  9631. Finals.push_back(nullptr);
  9632. HasErrors = true;
  9633. continue;
  9634. }
  9635. auto &&Info = Stack->isLoopControlVariable(D);
  9636. Expr *InitExpr = *CurInit;
  9637. // Build privatized reference to the current linear var.
  9638. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  9639. Expr *CapturedRef;
  9640. if (LinKind == OMPC_LINEAR_uval)
  9641. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  9642. else
  9643. CapturedRef =
  9644. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  9645. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  9646. /*RefersToCapture=*/true);
  9647. // Build update: Var = InitExpr + IV * Step
  9648. ExprResult Update;
  9649. if (!Info.first) {
  9650. Update =
  9651. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  9652. InitExpr, IV, Step, /* Subtract */ false);
  9653. } else
  9654. Update = *CurPrivate;
  9655. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  9656. /*DiscardedValue=*/true);
  9657. // Build final: Var = InitExpr + NumIterations * Step
  9658. ExprResult Final;
  9659. if (!Info.first) {
  9660. Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  9661. InitExpr, NumIterations, Step,
  9662. /* Subtract */ false);
  9663. } else
  9664. Final = *CurPrivate;
  9665. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  9666. /*DiscardedValue=*/true);
  9667. if (!Update.isUsable() || !Final.isUsable()) {
  9668. Updates.push_back(nullptr);
  9669. Finals.push_back(nullptr);
  9670. HasErrors = true;
  9671. } else {
  9672. Updates.push_back(Update.get());
  9673. Finals.push_back(Final.get());
  9674. }
  9675. ++CurInit;
  9676. ++CurPrivate;
  9677. }
  9678. Clause.setUpdates(Updates);
  9679. Clause.setFinals(Finals);
  9680. return HasErrors;
  9681. }
  9682. OMPClause *Sema::ActOnOpenMPAlignedClause(
  9683. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  9684. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  9685. SmallVector<Expr *, 8> Vars;
  9686. for (auto &RefExpr : VarList) {
  9687. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9688. SourceLocation ELoc;
  9689. SourceRange ERange;
  9690. Expr *SimpleRefExpr = RefExpr;
  9691. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9692. /*AllowArraySection=*/false);
  9693. if (Res.second) {
  9694. // It will be analyzed later.
  9695. Vars.push_back(RefExpr);
  9696. }
  9697. ValueDecl *D = Res.first;
  9698. if (!D)
  9699. continue;
  9700. QualType QType = D->getType();
  9701. auto *VD = dyn_cast<VarDecl>(D);
  9702. // OpenMP [2.8.1, simd construct, Restrictions]
  9703. // The type of list items appearing in the aligned clause must be
  9704. // array, pointer, reference to array, or reference to pointer.
  9705. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  9706. const Type *Ty = QType.getTypePtrOrNull();
  9707. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  9708. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  9709. << QType << getLangOpts().CPlusPlus << ERange;
  9710. bool IsDecl =
  9711. !VD ||
  9712. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9713. Diag(D->getLocation(),
  9714. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9715. << D;
  9716. continue;
  9717. }
  9718. // OpenMP [2.8.1, simd construct, Restrictions]
  9719. // A list-item cannot appear in more than one aligned clause.
  9720. if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  9721. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  9722. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  9723. << getOpenMPClauseName(OMPC_aligned);
  9724. continue;
  9725. }
  9726. DeclRefExpr *Ref = nullptr;
  9727. if (!VD && IsOpenMPCapturedDecl(D))
  9728. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9729. Vars.push_back(DefaultFunctionArrayConversion(
  9730. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  9731. .get());
  9732. }
  9733. // OpenMP [2.8.1, simd construct, Description]
  9734. // The parameter of the aligned clause, alignment, must be a constant
  9735. // positive integer expression.
  9736. // If no optional parameter is specified, implementation-defined default
  9737. // alignments for SIMD instructions on the target platforms are assumed.
  9738. if (Alignment != nullptr) {
  9739. ExprResult AlignResult =
  9740. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  9741. if (AlignResult.isInvalid())
  9742. return nullptr;
  9743. Alignment = AlignResult.get();
  9744. }
  9745. if (Vars.empty())
  9746. return nullptr;
  9747. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  9748. EndLoc, Vars, Alignment);
  9749. }
  9750. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  9751. SourceLocation StartLoc,
  9752. SourceLocation LParenLoc,
  9753. SourceLocation EndLoc) {
  9754. SmallVector<Expr *, 8> Vars;
  9755. SmallVector<Expr *, 8> SrcExprs;
  9756. SmallVector<Expr *, 8> DstExprs;
  9757. SmallVector<Expr *, 8> AssignmentOps;
  9758. for (auto &RefExpr : VarList) {
  9759. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  9760. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  9761. // It will be analyzed later.
  9762. Vars.push_back(RefExpr);
  9763. SrcExprs.push_back(nullptr);
  9764. DstExprs.push_back(nullptr);
  9765. AssignmentOps.push_back(nullptr);
  9766. continue;
  9767. }
  9768. SourceLocation ELoc = RefExpr->getExprLoc();
  9769. // OpenMP [2.1, C/C++]
  9770. // A list item is a variable name.
  9771. // OpenMP [2.14.4.1, Restrictions, p.1]
  9772. // A list item that appears in a copyin clause must be threadprivate.
  9773. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  9774. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  9775. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  9776. << 0 << RefExpr->getSourceRange();
  9777. continue;
  9778. }
  9779. Decl *D = DE->getDecl();
  9780. VarDecl *VD = cast<VarDecl>(D);
  9781. QualType Type = VD->getType();
  9782. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  9783. // It will be analyzed later.
  9784. Vars.push_back(DE);
  9785. SrcExprs.push_back(nullptr);
  9786. DstExprs.push_back(nullptr);
  9787. AssignmentOps.push_back(nullptr);
  9788. continue;
  9789. }
  9790. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  9791. // A list item that appears in a copyin clause must be threadprivate.
  9792. if (!DSAStack->isThreadPrivate(VD)) {
  9793. Diag(ELoc, diag::err_omp_required_access)
  9794. << getOpenMPClauseName(OMPC_copyin)
  9795. << getOpenMPDirectiveName(OMPD_threadprivate);
  9796. continue;
  9797. }
  9798. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  9799. // A variable of class type (or array thereof) that appears in a
  9800. // copyin clause requires an accessible, unambiguous copy assignment
  9801. // operator for the class type.
  9802. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9803. auto *SrcVD =
  9804. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  9805. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  9806. auto *PseudoSrcExpr = buildDeclRefExpr(
  9807. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  9808. auto *DstVD =
  9809. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  9810. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  9811. auto *PseudoDstExpr =
  9812. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  9813. // For arrays generate assignment operation for single element and replace
  9814. // it by the original array element in CodeGen.
  9815. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  9816. PseudoDstExpr, PseudoSrcExpr);
  9817. if (AssignmentOp.isInvalid())
  9818. continue;
  9819. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  9820. /*DiscardedValue=*/true);
  9821. if (AssignmentOp.isInvalid())
  9822. continue;
  9823. DSAStack->addDSA(VD, DE, OMPC_copyin);
  9824. Vars.push_back(DE);
  9825. SrcExprs.push_back(PseudoSrcExpr);
  9826. DstExprs.push_back(PseudoDstExpr);
  9827. AssignmentOps.push_back(AssignmentOp.get());
  9828. }
  9829. if (Vars.empty())
  9830. return nullptr;
  9831. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9832. SrcExprs, DstExprs, AssignmentOps);
  9833. }
  9834. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  9835. SourceLocation StartLoc,
  9836. SourceLocation LParenLoc,
  9837. SourceLocation EndLoc) {
  9838. SmallVector<Expr *, 8> Vars;
  9839. SmallVector<Expr *, 8> SrcExprs;
  9840. SmallVector<Expr *, 8> DstExprs;
  9841. SmallVector<Expr *, 8> AssignmentOps;
  9842. for (auto &RefExpr : VarList) {
  9843. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  9844. SourceLocation ELoc;
  9845. SourceRange ERange;
  9846. Expr *SimpleRefExpr = RefExpr;
  9847. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  9848. /*AllowArraySection=*/false);
  9849. if (Res.second) {
  9850. // It will be analyzed later.
  9851. Vars.push_back(RefExpr);
  9852. SrcExprs.push_back(nullptr);
  9853. DstExprs.push_back(nullptr);
  9854. AssignmentOps.push_back(nullptr);
  9855. }
  9856. ValueDecl *D = Res.first;
  9857. if (!D)
  9858. continue;
  9859. QualType Type = D->getType();
  9860. auto *VD = dyn_cast<VarDecl>(D);
  9861. // OpenMP [2.14.4.2, Restrictions, p.2]
  9862. // A list item that appears in a copyprivate clause may not appear in a
  9863. // private or firstprivate clause on the single construct.
  9864. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  9865. auto DVar = DSAStack->getTopDSA(D, false);
  9866. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  9867. DVar.RefExpr) {
  9868. Diag(ELoc, diag::err_omp_wrong_dsa)
  9869. << getOpenMPClauseName(DVar.CKind)
  9870. << getOpenMPClauseName(OMPC_copyprivate);
  9871. ReportOriginalDSA(*this, DSAStack, D, DVar);
  9872. continue;
  9873. }
  9874. // OpenMP [2.11.4.2, Restrictions, p.1]
  9875. // All list items that appear in a copyprivate clause must be either
  9876. // threadprivate or private in the enclosing context.
  9877. if (DVar.CKind == OMPC_unknown) {
  9878. DVar = DSAStack->getImplicitDSA(D, false);
  9879. if (DVar.CKind == OMPC_shared) {
  9880. Diag(ELoc, diag::err_omp_required_access)
  9881. << getOpenMPClauseName(OMPC_copyprivate)
  9882. << "threadprivate or private in the enclosing context";
  9883. ReportOriginalDSA(*this, DSAStack, D, DVar);
  9884. continue;
  9885. }
  9886. }
  9887. }
  9888. // Variably modified types are not supported.
  9889. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  9890. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9891. << getOpenMPClauseName(OMPC_copyprivate) << Type
  9892. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9893. bool IsDecl =
  9894. !VD ||
  9895. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9896. Diag(D->getLocation(),
  9897. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9898. << D;
  9899. continue;
  9900. }
  9901. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  9902. // A variable of class type (or array thereof) that appears in a
  9903. // copyin clause requires an accessible, unambiguous copy assignment
  9904. // operator for the class type.
  9905. Type = Context.getBaseElementType(Type.getNonReferenceType())
  9906. .getUnqualifiedType();
  9907. auto *SrcVD =
  9908. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
  9909. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9910. auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  9911. auto *DstVD =
  9912. buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
  9913. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9914. auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9915. auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  9916. PseudoDstExpr, PseudoSrcExpr);
  9917. if (AssignmentOp.isInvalid())
  9918. continue;
  9919. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
  9920. /*DiscardedValue=*/true);
  9921. if (AssignmentOp.isInvalid())
  9922. continue;
  9923. // No need to mark vars as copyprivate, they are already threadprivate or
  9924. // implicitly private.
  9925. assert(VD || IsOpenMPCapturedDecl(D));
  9926. Vars.push_back(
  9927. VD ? RefExpr->IgnoreParens()
  9928. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  9929. SrcExprs.push_back(PseudoSrcExpr);
  9930. DstExprs.push_back(PseudoDstExpr);
  9931. AssignmentOps.push_back(AssignmentOp.get());
  9932. }
  9933. if (Vars.empty())
  9934. return nullptr;
  9935. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9936. Vars, SrcExprs, DstExprs, AssignmentOps);
  9937. }
  9938. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  9939. SourceLocation StartLoc,
  9940. SourceLocation LParenLoc,
  9941. SourceLocation EndLoc) {
  9942. if (VarList.empty())
  9943. return nullptr;
  9944. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  9945. }
  9946. OMPClause *
  9947. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  9948. SourceLocation DepLoc, SourceLocation ColonLoc,
  9949. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  9950. SourceLocation LParenLoc, SourceLocation EndLoc) {
  9951. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  9952. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  9953. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  9954. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  9955. return nullptr;
  9956. }
  9957. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  9958. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  9959. DepKind == OMPC_DEPEND_sink)) {
  9960. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  9961. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  9962. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  9963. /*Last=*/OMPC_DEPEND_unknown, Except)
  9964. << getOpenMPClauseName(OMPC_depend);
  9965. return nullptr;
  9966. }
  9967. SmallVector<Expr *, 8> Vars;
  9968. DSAStackTy::OperatorOffsetTy OpsOffs;
  9969. llvm::APSInt DepCounter(/*BitWidth=*/32);
  9970. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  9971. if (DepKind == OMPC_DEPEND_sink) {
  9972. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  9973. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  9974. TotalDepCount.setIsUnsigned(/*Val=*/true);
  9975. }
  9976. }
  9977. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  9978. DSAStack->getParentOrderedRegionParam()) {
  9979. for (auto &RefExpr : VarList) {
  9980. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  9981. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  9982. // It will be analyzed later.
  9983. Vars.push_back(RefExpr);
  9984. continue;
  9985. }
  9986. SourceLocation ELoc = RefExpr->getExprLoc();
  9987. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  9988. if (DepKind == OMPC_DEPEND_sink) {
  9989. if (DepCounter >= TotalDepCount) {
  9990. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  9991. continue;
  9992. }
  9993. ++DepCounter;
  9994. // OpenMP [2.13.9, Summary]
  9995. // depend(dependence-type : vec), where dependence-type is:
  9996. // 'sink' and where vec is the iteration vector, which has the form:
  9997. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  9998. // where n is the value specified by the ordered clause in the loop
  9999. // directive, xi denotes the loop iteration variable of the i-th nested
  10000. // loop associated with the loop directive, and di is a constant
  10001. // non-negative integer.
  10002. if (CurContext->isDependentContext()) {
  10003. // It will be analyzed later.
  10004. Vars.push_back(RefExpr);
  10005. continue;
  10006. }
  10007. SimpleExpr = SimpleExpr->IgnoreImplicit();
  10008. OverloadedOperatorKind OOK = OO_None;
  10009. SourceLocation OOLoc;
  10010. Expr *LHS = SimpleExpr;
  10011. Expr *RHS = nullptr;
  10012. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  10013. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  10014. OOLoc = BO->getOperatorLoc();
  10015. LHS = BO->getLHS()->IgnoreParenImpCasts();
  10016. RHS = BO->getRHS()->IgnoreParenImpCasts();
  10017. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  10018. OOK = OCE->getOperator();
  10019. OOLoc = OCE->getOperatorLoc();
  10020. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10021. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  10022. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  10023. OOK = MCE->getMethodDecl()
  10024. ->getNameInfo()
  10025. .getName()
  10026. .getCXXOverloadedOperator();
  10027. OOLoc = MCE->getCallee()->getExprLoc();
  10028. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  10029. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  10030. }
  10031. SourceLocation ELoc;
  10032. SourceRange ERange;
  10033. auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
  10034. /*AllowArraySection=*/false);
  10035. if (Res.second) {
  10036. // It will be analyzed later.
  10037. Vars.push_back(RefExpr);
  10038. }
  10039. ValueDecl *D = Res.first;
  10040. if (!D)
  10041. continue;
  10042. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  10043. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  10044. continue;
  10045. }
  10046. if (RHS) {
  10047. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  10048. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  10049. if (RHSRes.isInvalid())
  10050. continue;
  10051. }
  10052. if (!CurContext->isDependentContext() &&
  10053. DSAStack->getParentOrderedRegionParam() &&
  10054. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  10055. ValueDecl* VD = DSAStack->getParentLoopControlVariable(
  10056. DepCounter.getZExtValue());
  10057. if (VD) {
  10058. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  10059. << 1 << VD;
  10060. } else {
  10061. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  10062. }
  10063. continue;
  10064. }
  10065. OpsOffs.push_back({RHS, OOK});
  10066. } else {
  10067. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  10068. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  10069. (ASE &&
  10070. !ASE->getBase()
  10071. ->getType()
  10072. .getNonReferenceType()
  10073. ->isPointerType() &&
  10074. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  10075. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10076. << RefExpr->getSourceRange();
  10077. continue;
  10078. }
  10079. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  10080. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  10081. ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  10082. RefExpr->IgnoreParenImpCasts());
  10083. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  10084. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  10085. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  10086. << RefExpr->getSourceRange();
  10087. continue;
  10088. }
  10089. }
  10090. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  10091. }
  10092. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  10093. TotalDepCount > VarList.size() &&
  10094. DSAStack->getParentOrderedRegionParam() &&
  10095. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  10096. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
  10097. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  10098. }
  10099. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  10100. Vars.empty())
  10101. return nullptr;
  10102. }
  10103. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10104. DepKind, DepLoc, ColonLoc, Vars);
  10105. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
  10106. DSAStack->addDoacrossDependClause(C, OpsOffs);
  10107. return C;
  10108. }
  10109. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  10110. SourceLocation LParenLoc,
  10111. SourceLocation EndLoc) {
  10112. Expr *ValExpr = Device;
  10113. Stmt *HelperValStmt = nullptr;
  10114. // OpenMP [2.9.1, Restrictions]
  10115. // The device expression must evaluate to a non-negative integer value.
  10116. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  10117. /*StrictlyPositive=*/false))
  10118. return nullptr;
  10119. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  10120. if (isOpenMPTargetExecutionDirective(DKind) &&
  10121. !CurContext->isDependentContext()) {
  10122. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  10123. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  10124. HelperValStmt = buildPreInits(Context, Captures);
  10125. }
  10126. return new (Context)
  10127. OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
  10128. }
  10129. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  10130. DSAStackTy *Stack, QualType QTy) {
  10131. NamedDecl *ND;
  10132. if (QTy->isIncompleteType(&ND)) {
  10133. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  10134. return false;
  10135. }
  10136. return true;
  10137. }
  10138. /// \brief Return true if it can be proven that the provided array expression
  10139. /// (array section or array subscript) does NOT specify the whole size of the
  10140. /// array whose base type is \a BaseQTy.
  10141. static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  10142. const Expr *E,
  10143. QualType BaseQTy) {
  10144. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10145. // If this is an array subscript, it refers to the whole size if the size of
  10146. // the dimension is constant and equals 1. Also, an array section assumes the
  10147. // format of an array subscript if no colon is used.
  10148. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  10149. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10150. return ATy->getSize().getSExtValue() != 1;
  10151. // Size can't be evaluated statically.
  10152. return false;
  10153. }
  10154. assert(OASE && "Expecting array section if not an array subscript.");
  10155. auto *LowerBound = OASE->getLowerBound();
  10156. auto *Length = OASE->getLength();
  10157. // If there is a lower bound that does not evaluates to zero, we are not
  10158. // covering the whole dimension.
  10159. if (LowerBound) {
  10160. llvm::APSInt ConstLowerBound;
  10161. if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
  10162. return false; // Can't get the integer value as a constant.
  10163. if (ConstLowerBound.getSExtValue())
  10164. return true;
  10165. }
  10166. // If we don't have a length we covering the whole dimension.
  10167. if (!Length)
  10168. return false;
  10169. // If the base is a pointer, we don't have a way to get the size of the
  10170. // pointee.
  10171. if (BaseQTy->isPointerType())
  10172. return false;
  10173. // We can only check if the length is the same as the size of the dimension
  10174. // if we have a constant array.
  10175. auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  10176. if (!CATy)
  10177. return false;
  10178. llvm::APSInt ConstLength;
  10179. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10180. return false; // Can't get the integer value as a constant.
  10181. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  10182. }
  10183. // Return true if it can be proven that the provided array expression (array
  10184. // section or array subscript) does NOT specify a single element of the array
  10185. // whose base type is \a BaseQTy.
  10186. static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  10187. const Expr *E,
  10188. QualType BaseQTy) {
  10189. auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  10190. // An array subscript always refer to a single element. Also, an array section
  10191. // assumes the format of an array subscript if no colon is used.
  10192. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  10193. return false;
  10194. assert(OASE && "Expecting array section if not an array subscript.");
  10195. auto *Length = OASE->getLength();
  10196. // If we don't have a length we have to check if the array has unitary size
  10197. // for this dimension. Also, we should always expect a length if the base type
  10198. // is pointer.
  10199. if (!Length) {
  10200. if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  10201. return ATy->getSize().getSExtValue() != 1;
  10202. // We cannot assume anything.
  10203. return false;
  10204. }
  10205. // Check if the length evaluates to 1.
  10206. llvm::APSInt ConstLength;
  10207. if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
  10208. return false; // Can't get the integer value as a constant.
  10209. return ConstLength.getSExtValue() != 1;
  10210. }
  10211. // Return the expression of the base of the mappable expression or null if it
  10212. // cannot be determined and do all the necessary checks to see if the expression
  10213. // is valid as a standalone mappable expression. In the process, record all the
  10214. // components of the expression.
  10215. static Expr *CheckMapClauseExpressionBase(
  10216. Sema &SemaRef, Expr *E,
  10217. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  10218. OpenMPClauseKind CKind) {
  10219. SourceLocation ELoc = E->getExprLoc();
  10220. SourceRange ERange = E->getSourceRange();
  10221. // The base of elements of list in a map clause have to be either:
  10222. // - a reference to variable or field.
  10223. // - a member expression.
  10224. // - an array expression.
  10225. //
  10226. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  10227. // reference to 'r'.
  10228. //
  10229. // If we have:
  10230. //
  10231. // struct SS {
  10232. // Bla S;
  10233. // foo() {
  10234. // #pragma omp target map (S.Arr[:12]);
  10235. // }
  10236. // }
  10237. //
  10238. // We want to retrieve the member expression 'this->S';
  10239. Expr *RelevantExpr = nullptr;
  10240. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  10241. // If a list item is an array section, it must specify contiguous storage.
  10242. //
  10243. // For this restriction it is sufficient that we make sure only references
  10244. // to variables or fields and array expressions, and that no array sections
  10245. // exist except in the rightmost expression (unless they cover the whole
  10246. // dimension of the array). E.g. these would be invalid:
  10247. //
  10248. // r.ArrS[3:5].Arr[6:7]
  10249. //
  10250. // r.ArrS[3:5].x
  10251. //
  10252. // but these would be valid:
  10253. // r.ArrS[3].Arr[6:7]
  10254. //
  10255. // r.ArrS[3].x
  10256. bool AllowUnitySizeArraySection = true;
  10257. bool AllowWholeSizeArraySection = true;
  10258. while (!RelevantExpr) {
  10259. E = E->IgnoreParenImpCasts();
  10260. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  10261. if (!isa<VarDecl>(CurE->getDecl()))
  10262. break;
  10263. RelevantExpr = CurE;
  10264. // If we got a reference to a declaration, we should not expect any array
  10265. // section before that.
  10266. AllowUnitySizeArraySection = false;
  10267. AllowWholeSizeArraySection = false;
  10268. // Record the component.
  10269. CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
  10270. CurE, CurE->getDecl()));
  10271. continue;
  10272. }
  10273. if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  10274. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  10275. if (isa<CXXThisExpr>(BaseE))
  10276. // We found a base expression: this->Val.
  10277. RelevantExpr = CurE;
  10278. else
  10279. E = BaseE;
  10280. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  10281. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  10282. << CurE->getSourceRange();
  10283. break;
  10284. }
  10285. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  10286. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  10287. // A bit-field cannot appear in a map clause.
  10288. //
  10289. if (FD->isBitField()) {
  10290. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  10291. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  10292. break;
  10293. }
  10294. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10295. // If the type of a list item is a reference to a type T then the type
  10296. // will be considered to be T for all purposes of this clause.
  10297. QualType CurType = BaseE->getType().getNonReferenceType();
  10298. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  10299. // A list item cannot be a variable that is a member of a structure with
  10300. // a union type.
  10301. //
  10302. if (auto *RT = CurType->getAs<RecordType>())
  10303. if (RT->isUnionType()) {
  10304. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  10305. << CurE->getSourceRange();
  10306. break;
  10307. }
  10308. // If we got a member expression, we should not expect any array section
  10309. // before that:
  10310. //
  10311. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  10312. // If a list item is an element of a structure, only the rightmost symbol
  10313. // of the variable reference can be an array section.
  10314. //
  10315. AllowUnitySizeArraySection = false;
  10316. AllowWholeSizeArraySection = false;
  10317. // Record the component.
  10318. CurComponents.push_back(
  10319. OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
  10320. continue;
  10321. }
  10322. if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  10323. E = CurE->getBase()->IgnoreParenImpCasts();
  10324. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  10325. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10326. << 0 << CurE->getSourceRange();
  10327. break;
  10328. }
  10329. // If we got an array subscript that express the whole dimension we
  10330. // can have any array expressions before. If it only expressing part of
  10331. // the dimension, we can only have unitary-size array expressions.
  10332. if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  10333. E->getType()))
  10334. AllowWholeSizeArraySection = false;
  10335. // Record the component - we don't have any declaration associated.
  10336. CurComponents.push_back(
  10337. OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
  10338. continue;
  10339. }
  10340. if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  10341. E = CurE->getBase()->IgnoreParenImpCasts();
  10342. auto CurType =
  10343. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10344. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10345. // If the type of a list item is a reference to a type T then the type
  10346. // will be considered to be T for all purposes of this clause.
  10347. if (CurType->isReferenceType())
  10348. CurType = CurType->getPointeeType();
  10349. bool IsPointer = CurType->isAnyPointerType();
  10350. if (!IsPointer && !CurType->isArrayType()) {
  10351. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  10352. << 0 << CurE->getSourceRange();
  10353. break;
  10354. }
  10355. bool NotWhole =
  10356. CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  10357. bool NotUnity =
  10358. CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  10359. if (AllowWholeSizeArraySection) {
  10360. // Any array section is currently allowed. Allowing a whole size array
  10361. // section implies allowing a unity array section as well.
  10362. //
  10363. // If this array section refers to the whole dimension we can still
  10364. // accept other array sections before this one, except if the base is a
  10365. // pointer. Otherwise, only unitary sections are accepted.
  10366. if (NotWhole || IsPointer)
  10367. AllowWholeSizeArraySection = false;
  10368. } else if (AllowUnitySizeArraySection && NotUnity) {
  10369. // A unity or whole array section is not allowed and that is not
  10370. // compatible with the properties of the current array section.
  10371. SemaRef.Diag(
  10372. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  10373. << CurE->getSourceRange();
  10374. break;
  10375. }
  10376. // Record the component - we don't have any declaration associated.
  10377. CurComponents.push_back(
  10378. OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
  10379. continue;
  10380. }
  10381. // If nothing else worked, this is not a valid map clause expression.
  10382. SemaRef.Diag(ELoc,
  10383. diag::err_omp_expected_named_var_member_or_array_expression)
  10384. << ERange;
  10385. break;
  10386. }
  10387. return RelevantExpr;
  10388. }
  10389. // Return true if expression E associated with value VD has conflicts with other
  10390. // map information.
  10391. static bool CheckMapConflicts(
  10392. Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
  10393. bool CurrentRegionOnly,
  10394. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  10395. OpenMPClauseKind CKind) {
  10396. assert(VD && E);
  10397. SourceLocation ELoc = E->getExprLoc();
  10398. SourceRange ERange = E->getSourceRange();
  10399. // In order to easily check the conflicts we need to match each component of
  10400. // the expression under test with the components of the expressions that are
  10401. // already in the stack.
  10402. assert(!CurComponents.empty() && "Map clause expression with no components!");
  10403. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  10404. "Map clause expression with unexpected base!");
  10405. // Variables to help detecting enclosing problems in data environment nests.
  10406. bool IsEnclosedByDataEnvironmentExpr = false;
  10407. const Expr *EnclosingExpr = nullptr;
  10408. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  10409. VD, CurrentRegionOnly,
  10410. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
  10411. StackComponents,
  10412. OpenMPClauseKind) -> bool {
  10413. assert(!StackComponents.empty() &&
  10414. "Map clause expression with no components!");
  10415. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  10416. "Map clause expression with unexpected base!");
  10417. // The whole expression in the stack.
  10418. auto *RE = StackComponents.front().getAssociatedExpression();
  10419. // Expressions must start from the same base. Here we detect at which
  10420. // point both expressions diverge from each other and see if we can
  10421. // detect if the memory referred to both expressions is contiguous and
  10422. // do not overlap.
  10423. auto CI = CurComponents.rbegin();
  10424. auto CE = CurComponents.rend();
  10425. auto SI = StackComponents.rbegin();
  10426. auto SE = StackComponents.rend();
  10427. for (; CI != CE && SI != SE; ++CI, ++SI) {
  10428. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  10429. // At most one list item can be an array item derived from a given
  10430. // variable in map clauses of the same construct.
  10431. if (CurrentRegionOnly &&
  10432. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  10433. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  10434. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  10435. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  10436. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  10437. diag::err_omp_multiple_array_items_in_map_clause)
  10438. << CI->getAssociatedExpression()->getSourceRange();
  10439. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  10440. diag::note_used_here)
  10441. << SI->getAssociatedExpression()->getSourceRange();
  10442. return true;
  10443. }
  10444. // Do both expressions have the same kind?
  10445. if (CI->getAssociatedExpression()->getStmtClass() !=
  10446. SI->getAssociatedExpression()->getStmtClass())
  10447. break;
  10448. // Are we dealing with different variables/fields?
  10449. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  10450. break;
  10451. }
  10452. // Check if the extra components of the expressions in the enclosing
  10453. // data environment are redundant for the current base declaration.
  10454. // If they are, the maps completely overlap, which is legal.
  10455. for (; SI != SE; ++SI) {
  10456. QualType Type;
  10457. if (auto *ASE =
  10458. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  10459. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  10460. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
  10461. SI->getAssociatedExpression())) {
  10462. auto *E = OASE->getBase()->IgnoreParenImpCasts();
  10463. Type =
  10464. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  10465. }
  10466. if (Type.isNull() || Type->isAnyPointerType() ||
  10467. CheckArrayExpressionDoesNotReferToWholeSize(
  10468. SemaRef, SI->getAssociatedExpression(), Type))
  10469. break;
  10470. }
  10471. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10472. // List items of map clauses in the same construct must not share
  10473. // original storage.
  10474. //
  10475. // If the expressions are exactly the same or one is a subset of the
  10476. // other, it means they are sharing storage.
  10477. if (CI == CE && SI == SE) {
  10478. if (CurrentRegionOnly) {
  10479. if (CKind == OMPC_map)
  10480. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10481. else {
  10482. assert(CKind == OMPC_to || CKind == OMPC_from);
  10483. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  10484. << ERange;
  10485. }
  10486. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  10487. << RE->getSourceRange();
  10488. return true;
  10489. } else {
  10490. // If we find the same expression in the enclosing data environment,
  10491. // that is legal.
  10492. IsEnclosedByDataEnvironmentExpr = true;
  10493. return false;
  10494. }
  10495. }
  10496. QualType DerivedType =
  10497. std::prev(CI)->getAssociatedDeclaration()->getType();
  10498. SourceLocation DerivedLoc =
  10499. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  10500. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10501. // If the type of a list item is a reference to a type T then the type
  10502. // will be considered to be T for all purposes of this clause.
  10503. DerivedType = DerivedType.getNonReferenceType();
  10504. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  10505. // A variable for which the type is pointer and an array section
  10506. // derived from that variable must not appear as list items of map
  10507. // clauses of the same construct.
  10508. //
  10509. // Also, cover one of the cases in:
  10510. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  10511. // If any part of the original storage of a list item has corresponding
  10512. // storage in the device data environment, all of the original storage
  10513. // must have corresponding storage in the device data environment.
  10514. //
  10515. if (DerivedType->isAnyPointerType()) {
  10516. if (CI == CE || SI == SE) {
  10517. SemaRef.Diag(
  10518. DerivedLoc,
  10519. diag::err_omp_pointer_mapped_along_with_derived_section)
  10520. << DerivedLoc;
  10521. } else {
  10522. assert(CI != CE && SI != SE);
  10523. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  10524. << DerivedLoc;
  10525. }
  10526. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  10527. << RE->getSourceRange();
  10528. return true;
  10529. }
  10530. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  10531. // List items of map clauses in the same construct must not share
  10532. // original storage.
  10533. //
  10534. // An expression is a subset of the other.
  10535. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  10536. if (CKind == OMPC_map)
  10537. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  10538. else {
  10539. assert(CKind == OMPC_to || CKind == OMPC_from);
  10540. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  10541. << ERange;
  10542. }
  10543. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  10544. << RE->getSourceRange();
  10545. return true;
  10546. }
  10547. // The current expression uses the same base as other expression in the
  10548. // data environment but does not contain it completely.
  10549. if (!CurrentRegionOnly && SI != SE)
  10550. EnclosingExpr = RE;
  10551. // The current expression is a subset of the expression in the data
  10552. // environment.
  10553. IsEnclosedByDataEnvironmentExpr |=
  10554. (!CurrentRegionOnly && CI != CE && SI == SE);
  10555. return false;
  10556. });
  10557. if (CurrentRegionOnly)
  10558. return FoundError;
  10559. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  10560. // If any part of the original storage of a list item has corresponding
  10561. // storage in the device data environment, all of the original storage must
  10562. // have corresponding storage in the device data environment.
  10563. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  10564. // If a list item is an element of a structure, and a different element of
  10565. // the structure has a corresponding list item in the device data environment
  10566. // prior to a task encountering the construct associated with the map clause,
  10567. // then the list item must also have a corresponding list item in the device
  10568. // data environment prior to the task encountering the construct.
  10569. //
  10570. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  10571. SemaRef.Diag(ELoc,
  10572. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  10573. << ERange;
  10574. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  10575. << EnclosingExpr->getSourceRange();
  10576. return true;
  10577. }
  10578. return FoundError;
  10579. }
  10580. namespace {
  10581. // Utility struct that gathers all the related lists associated with a mappable
  10582. // expression.
  10583. struct MappableVarListInfo final {
  10584. // The list of expressions.
  10585. ArrayRef<Expr *> VarList;
  10586. // The list of processed expressions.
  10587. SmallVector<Expr *, 16> ProcessedVarList;
  10588. // The mappble components for each expression.
  10589. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  10590. // The base declaration of the variable.
  10591. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  10592. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  10593. // We have a list of components and base declarations for each entry in the
  10594. // variable list.
  10595. VarComponents.reserve(VarList.size());
  10596. VarBaseDeclarations.reserve(VarList.size());
  10597. }
  10598. };
  10599. }
  10600. // Check the validity of the provided variable list for the provided clause kind
  10601. // \a CKind. In the check process the valid expressions, and mappable expression
  10602. // components and variables are extracted and used to fill \a Vars,
  10603. // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
  10604. // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
  10605. static void
  10606. checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
  10607. OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
  10608. SourceLocation StartLoc,
  10609. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  10610. bool IsMapTypeImplicit = false) {
  10611. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  10612. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  10613. "Unexpected clause kind with mappable expressions!");
  10614. // Keep track of the mappable components and base declarations in this clause.
  10615. // Each entry in the list is going to have a list of components associated. We
  10616. // record each set of the components so that we can build the clause later on.
  10617. // In the end we should have the same amount of declarations and component
  10618. // lists.
  10619. for (auto &RE : MVLI.VarList) {
  10620. assert(RE && "Null expr in omp to/from/map clause");
  10621. SourceLocation ELoc = RE->getExprLoc();
  10622. auto *VE = RE->IgnoreParenLValueCasts();
  10623. if (VE->isValueDependent() || VE->isTypeDependent() ||
  10624. VE->isInstantiationDependent() ||
  10625. VE->containsUnexpandedParameterPack()) {
  10626. // We can only analyze this information once the missing information is
  10627. // resolved.
  10628. MVLI.ProcessedVarList.push_back(RE);
  10629. continue;
  10630. }
  10631. auto *SimpleExpr = RE->IgnoreParenCasts();
  10632. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  10633. SemaRef.Diag(ELoc,
  10634. diag::err_omp_expected_named_var_member_or_array_expression)
  10635. << RE->getSourceRange();
  10636. continue;
  10637. }
  10638. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  10639. ValueDecl *CurDeclaration = nullptr;
  10640. // Obtain the array or member expression bases if required. Also, fill the
  10641. // components array with all the components identified in the process.
  10642. auto *BE =
  10643. CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
  10644. if (!BE)
  10645. continue;
  10646. assert(!CurComponents.empty() &&
  10647. "Invalid mappable expression information.");
  10648. // For the following checks, we rely on the base declaration which is
  10649. // expected to be associated with the last component. The declaration is
  10650. // expected to be a variable or a field (if 'this' is being mapped).
  10651. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  10652. assert(CurDeclaration && "Null decl on map clause.");
  10653. assert(
  10654. CurDeclaration->isCanonicalDecl() &&
  10655. "Expecting components to have associated only canonical declarations.");
  10656. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  10657. auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  10658. assert((VD || FD) && "Only variables or fields are expected here!");
  10659. (void)FD;
  10660. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  10661. // threadprivate variables cannot appear in a map clause.
  10662. // OpenMP 4.5 [2.10.5, target update Construct]
  10663. // threadprivate variables cannot appear in a from clause.
  10664. if (VD && DSAS->isThreadPrivate(VD)) {
  10665. auto DVar = DSAS->getTopDSA(VD, false);
  10666. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  10667. << getOpenMPClauseName(CKind);
  10668. ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
  10669. continue;
  10670. }
  10671. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  10672. // A list item cannot appear in both a map clause and a data-sharing
  10673. // attribute clause on the same construct.
  10674. // Check conflicts with other map clause expressions. We check the conflicts
  10675. // with the current construct separately from the enclosing data
  10676. // environment, because the restrictions are different. We only have to
  10677. // check conflicts across regions for the map clauses.
  10678. if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  10679. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  10680. break;
  10681. if (CKind == OMPC_map &&
  10682. CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  10683. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  10684. break;
  10685. // OpenMP 4.5 [2.10.5, target update Construct]
  10686. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  10687. // If the type of a list item is a reference to a type T then the type will
  10688. // be considered to be T for all purposes of this clause.
  10689. QualType Type = CurDeclaration->getType().getNonReferenceType();
  10690. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  10691. // A list item in a to or from clause must have a mappable type.
  10692. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  10693. // A list item must have a mappable type.
  10694. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  10695. DSAS, Type))
  10696. continue;
  10697. if (CKind == OMPC_map) {
  10698. // target enter data
  10699. // OpenMP [2.10.2, Restrictions, p. 99]
  10700. // A map-type must be specified in all map clauses and must be either
  10701. // to or alloc.
  10702. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  10703. if (DKind == OMPD_target_enter_data &&
  10704. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  10705. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  10706. << (IsMapTypeImplicit ? 1 : 0)
  10707. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  10708. << getOpenMPDirectiveName(DKind);
  10709. continue;
  10710. }
  10711. // target exit_data
  10712. // OpenMP [2.10.3, Restrictions, p. 102]
  10713. // A map-type must be specified in all map clauses and must be either
  10714. // from, release, or delete.
  10715. if (DKind == OMPD_target_exit_data &&
  10716. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  10717. MapType == OMPC_MAP_delete)) {
  10718. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  10719. << (IsMapTypeImplicit ? 1 : 0)
  10720. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  10721. << getOpenMPDirectiveName(DKind);
  10722. continue;
  10723. }
  10724. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  10725. // A list item cannot appear in both a map clause and a data-sharing
  10726. // attribute clause on the same construct
  10727. if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
  10728. DKind == OMPD_target_teams_distribute ||
  10729. DKind == OMPD_target_teams_distribute_parallel_for ||
  10730. DKind == OMPD_target_teams_distribute_parallel_for_simd ||
  10731. DKind == OMPD_target_teams_distribute_simd) && VD) {
  10732. auto DVar = DSAS->getTopDSA(VD, false);
  10733. if (isOpenMPPrivate(DVar.CKind)) {
  10734. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  10735. << getOpenMPClauseName(DVar.CKind)
  10736. << getOpenMPClauseName(OMPC_map)
  10737. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  10738. ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
  10739. continue;
  10740. }
  10741. }
  10742. }
  10743. // Save the current expression.
  10744. MVLI.ProcessedVarList.push_back(RE);
  10745. // Store the components in the stack so that they can be used to check
  10746. // against other clauses later on.
  10747. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  10748. /*WhereFoundClauseKind=*/OMPC_map);
  10749. // Save the components and declaration to create the clause. For purposes of
  10750. // the clause creation, any component list that has has base 'this' uses
  10751. // null as base declaration.
  10752. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  10753. MVLI.VarComponents.back().append(CurComponents.begin(),
  10754. CurComponents.end());
  10755. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  10756. : CurDeclaration);
  10757. }
  10758. }
  10759. OMPClause *
  10760. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  10761. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  10762. SourceLocation MapLoc, SourceLocation ColonLoc,
  10763. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  10764. SourceLocation LParenLoc, SourceLocation EndLoc) {
  10765. MappableVarListInfo MVLI(VarList);
  10766. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
  10767. MapType, IsMapTypeImplicit);
  10768. // We need to produce a map clause even if we don't have variables so that
  10769. // other diagnostics related with non-existing map clauses are accurate.
  10770. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10771. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  10772. MVLI.VarComponents, MapTypeModifier, MapType,
  10773. IsMapTypeImplicit, MapLoc);
  10774. }
  10775. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  10776. TypeResult ParsedType) {
  10777. assert(ParsedType.isUsable());
  10778. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  10779. if (ReductionType.isNull())
  10780. return QualType();
  10781. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  10782. // A type name in a declare reduction directive cannot be a function type, an
  10783. // array type, a reference type, or a type qualified with const, volatile or
  10784. // restrict.
  10785. if (ReductionType.hasQualifiers()) {
  10786. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  10787. return QualType();
  10788. }
  10789. if (ReductionType->isFunctionType()) {
  10790. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  10791. return QualType();
  10792. }
  10793. if (ReductionType->isReferenceType()) {
  10794. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  10795. return QualType();
  10796. }
  10797. if (ReductionType->isArrayType()) {
  10798. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  10799. return QualType();
  10800. }
  10801. return ReductionType;
  10802. }
  10803. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  10804. Scope *S, DeclContext *DC, DeclarationName Name,
  10805. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  10806. AccessSpecifier AS, Decl *PrevDeclInScope) {
  10807. SmallVector<Decl *, 8> Decls;
  10808. Decls.reserve(ReductionTypes.size());
  10809. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  10810. forRedeclarationInCurContext());
  10811. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  10812. // A reduction-identifier may not be re-declared in the current scope for the
  10813. // same type or for a type that is compatible according to the base language
  10814. // rules.
  10815. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  10816. OMPDeclareReductionDecl *PrevDRD = nullptr;
  10817. bool InCompoundScope = true;
  10818. if (S != nullptr) {
  10819. // Find previous declaration with the same name not referenced in other
  10820. // declarations.
  10821. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  10822. InCompoundScope =
  10823. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  10824. LookupName(Lookup, S);
  10825. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  10826. /*AllowInlineNamespace=*/false);
  10827. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  10828. auto Filter = Lookup.makeFilter();
  10829. while (Filter.hasNext()) {
  10830. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  10831. if (InCompoundScope) {
  10832. auto I = UsedAsPrevious.find(PrevDecl);
  10833. if (I == UsedAsPrevious.end())
  10834. UsedAsPrevious[PrevDecl] = false;
  10835. if (auto *D = PrevDecl->getPrevDeclInScope())
  10836. UsedAsPrevious[D] = true;
  10837. }
  10838. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  10839. PrevDecl->getLocation();
  10840. }
  10841. Filter.done();
  10842. if (InCompoundScope) {
  10843. for (auto &PrevData : UsedAsPrevious) {
  10844. if (!PrevData.second) {
  10845. PrevDRD = PrevData.first;
  10846. break;
  10847. }
  10848. }
  10849. }
  10850. } else if (PrevDeclInScope != nullptr) {
  10851. auto *PrevDRDInScope = PrevDRD =
  10852. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  10853. do {
  10854. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  10855. PrevDRDInScope->getLocation();
  10856. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  10857. } while (PrevDRDInScope != nullptr);
  10858. }
  10859. for (auto &TyData : ReductionTypes) {
  10860. auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  10861. bool Invalid = false;
  10862. if (I != PreviousRedeclTypes.end()) {
  10863. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  10864. << TyData.first;
  10865. Diag(I->second, diag::note_previous_definition);
  10866. Invalid = true;
  10867. }
  10868. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  10869. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  10870. Name, TyData.first, PrevDRD);
  10871. DC->addDecl(DRD);
  10872. DRD->setAccess(AS);
  10873. Decls.push_back(DRD);
  10874. if (Invalid)
  10875. DRD->setInvalidDecl();
  10876. else
  10877. PrevDRD = DRD;
  10878. }
  10879. return DeclGroupPtrTy::make(
  10880. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  10881. }
  10882. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  10883. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  10884. // Enter new function scope.
  10885. PushFunctionScope();
  10886. getCurFunction()->setHasBranchProtectedScope();
  10887. getCurFunction()->setHasOMPDeclareReductionCombiner();
  10888. if (S != nullptr)
  10889. PushDeclContext(S, DRD);
  10890. else
  10891. CurContext = DRD;
  10892. PushExpressionEvaluationContext(
  10893. ExpressionEvaluationContext::PotentiallyEvaluated);
  10894. QualType ReductionType = DRD->getType();
  10895. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  10896. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  10897. // uses semantics of argument handles by value, but it should be passed by
  10898. // reference. C lang does not support references, so pass all parameters as
  10899. // pointers.
  10900. // Create 'T omp_in;' variable.
  10901. auto *OmpInParm =
  10902. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  10903. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  10904. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  10905. // uses semantics of argument handles by value, but it should be passed by
  10906. // reference. C lang does not support references, so pass all parameters as
  10907. // pointers.
  10908. // Create 'T omp_out;' variable.
  10909. auto *OmpOutParm =
  10910. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  10911. if (S != nullptr) {
  10912. PushOnScopeChains(OmpInParm, S);
  10913. PushOnScopeChains(OmpOutParm, S);
  10914. } else {
  10915. DRD->addDecl(OmpInParm);
  10916. DRD->addDecl(OmpOutParm);
  10917. }
  10918. }
  10919. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  10920. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  10921. DiscardCleanupsInEvaluationContext();
  10922. PopExpressionEvaluationContext();
  10923. PopDeclContext();
  10924. PopFunctionScopeInfo();
  10925. if (Combiner != nullptr)
  10926. DRD->setCombiner(Combiner);
  10927. else
  10928. DRD->setInvalidDecl();
  10929. }
  10930. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  10931. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  10932. // Enter new function scope.
  10933. PushFunctionScope();
  10934. getCurFunction()->setHasBranchProtectedScope();
  10935. if (S != nullptr)
  10936. PushDeclContext(S, DRD);
  10937. else
  10938. CurContext = DRD;
  10939. PushExpressionEvaluationContext(
  10940. ExpressionEvaluationContext::PotentiallyEvaluated);
  10941. QualType ReductionType = DRD->getType();
  10942. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  10943. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  10944. // uses semantics of argument handles by value, but it should be passed by
  10945. // reference. C lang does not support references, so pass all parameters as
  10946. // pointers.
  10947. // Create 'T omp_priv;' variable.
  10948. auto *OmpPrivParm =
  10949. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  10950. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  10951. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  10952. // uses semantics of argument handles by value, but it should be passed by
  10953. // reference. C lang does not support references, so pass all parameters as
  10954. // pointers.
  10955. // Create 'T omp_orig;' variable.
  10956. auto *OmpOrigParm =
  10957. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  10958. if (S != nullptr) {
  10959. PushOnScopeChains(OmpPrivParm, S);
  10960. PushOnScopeChains(OmpOrigParm, S);
  10961. } else {
  10962. DRD->addDecl(OmpPrivParm);
  10963. DRD->addDecl(OmpOrigParm);
  10964. }
  10965. return OmpPrivParm;
  10966. }
  10967. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  10968. VarDecl *OmpPrivParm) {
  10969. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  10970. DiscardCleanupsInEvaluationContext();
  10971. PopExpressionEvaluationContext();
  10972. PopDeclContext();
  10973. PopFunctionScopeInfo();
  10974. if (Initializer != nullptr) {
  10975. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  10976. } else if (OmpPrivParm->hasInit()) {
  10977. DRD->setInitializer(OmpPrivParm->getInit(),
  10978. OmpPrivParm->isDirectInit()
  10979. ? OMPDeclareReductionDecl::DirectInit
  10980. : OMPDeclareReductionDecl::CopyInit);
  10981. } else {
  10982. DRD->setInvalidDecl();
  10983. }
  10984. }
  10985. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  10986. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  10987. for (auto *D : DeclReductions.get()) {
  10988. if (IsValid) {
  10989. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  10990. if (S != nullptr)
  10991. PushOnScopeChains(DRD, S, /*AddToContext=*/false);
  10992. } else
  10993. D->setInvalidDecl();
  10994. }
  10995. return DeclReductions;
  10996. }
  10997. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  10998. SourceLocation StartLoc,
  10999. SourceLocation LParenLoc,
  11000. SourceLocation EndLoc) {
  11001. Expr *ValExpr = NumTeams;
  11002. Stmt *HelperValStmt = nullptr;
  11003. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  11004. // OpenMP [teams Constrcut, Restrictions]
  11005. // The num_teams expression must evaluate to a positive integer value.
  11006. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  11007. /*StrictlyPositive=*/true))
  11008. return nullptr;
  11009. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11010. CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  11011. if (CaptureRegion != OMPD_unknown) {
  11012. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11013. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11014. HelperValStmt = buildPreInits(Context, Captures);
  11015. }
  11016. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  11017. StartLoc, LParenLoc, EndLoc);
  11018. }
  11019. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  11020. SourceLocation StartLoc,
  11021. SourceLocation LParenLoc,
  11022. SourceLocation EndLoc) {
  11023. Expr *ValExpr = ThreadLimit;
  11024. Stmt *HelperValStmt = nullptr;
  11025. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  11026. // OpenMP [teams Constrcut, Restrictions]
  11027. // The thread_limit expression must evaluate to a positive integer value.
  11028. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  11029. /*StrictlyPositive=*/true))
  11030. return nullptr;
  11031. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11032. CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  11033. if (CaptureRegion != OMPD_unknown) {
  11034. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11035. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11036. HelperValStmt = buildPreInits(Context, Captures);
  11037. }
  11038. return new (Context) OMPThreadLimitClause(
  11039. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  11040. }
  11041. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  11042. SourceLocation StartLoc,
  11043. SourceLocation LParenLoc,
  11044. SourceLocation EndLoc) {
  11045. Expr *ValExpr = Priority;
  11046. // OpenMP [2.9.1, task Constrcut]
  11047. // The priority-value is a non-negative numerical scalar expression.
  11048. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  11049. /*StrictlyPositive=*/false))
  11050. return nullptr;
  11051. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11052. }
  11053. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  11054. SourceLocation StartLoc,
  11055. SourceLocation LParenLoc,
  11056. SourceLocation EndLoc) {
  11057. Expr *ValExpr = Grainsize;
  11058. // OpenMP [2.9.2, taskloop Constrcut]
  11059. // The parameter of the grainsize clause must be a positive integer
  11060. // expression.
  11061. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  11062. /*StrictlyPositive=*/true))
  11063. return nullptr;
  11064. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11065. }
  11066. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  11067. SourceLocation StartLoc,
  11068. SourceLocation LParenLoc,
  11069. SourceLocation EndLoc) {
  11070. Expr *ValExpr = NumTasks;
  11071. // OpenMP [2.9.2, taskloop Constrcut]
  11072. // The parameter of the num_tasks clause must be a positive integer
  11073. // expression.
  11074. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  11075. /*StrictlyPositive=*/true))
  11076. return nullptr;
  11077. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  11078. }
  11079. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  11080. SourceLocation LParenLoc,
  11081. SourceLocation EndLoc) {
  11082. // OpenMP [2.13.2, critical construct, Description]
  11083. // ... where hint-expression is an integer constant expression that evaluates
  11084. // to a valid lock hint.
  11085. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  11086. if (HintExpr.isInvalid())
  11087. return nullptr;
  11088. return new (Context)
  11089. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  11090. }
  11091. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  11092. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  11093. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  11094. SourceLocation EndLoc) {
  11095. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  11096. std::string Values;
  11097. Values += "'";
  11098. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  11099. Values += "'";
  11100. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  11101. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  11102. return nullptr;
  11103. }
  11104. Expr *ValExpr = ChunkSize;
  11105. Stmt *HelperValStmt = nullptr;
  11106. if (ChunkSize) {
  11107. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  11108. !ChunkSize->isInstantiationDependent() &&
  11109. !ChunkSize->containsUnexpandedParameterPack()) {
  11110. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  11111. ExprResult Val =
  11112. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  11113. if (Val.isInvalid())
  11114. return nullptr;
  11115. ValExpr = Val.get();
  11116. // OpenMP [2.7.1, Restrictions]
  11117. // chunk_size must be a loop invariant integer expression with a positive
  11118. // value.
  11119. llvm::APSInt Result;
  11120. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  11121. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  11122. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  11123. << "dist_schedule" << ChunkSize->getSourceRange();
  11124. return nullptr;
  11125. }
  11126. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  11127. !CurContext->isDependentContext()) {
  11128. llvm::MapVector<Expr *, DeclRefExpr *> Captures;
  11129. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11130. HelperValStmt = buildPreInits(Context, Captures);
  11131. }
  11132. }
  11133. }
  11134. return new (Context)
  11135. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  11136. Kind, ValExpr, HelperValStmt);
  11137. }
  11138. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  11139. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  11140. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  11141. SourceLocation KindLoc, SourceLocation EndLoc) {
  11142. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  11143. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  11144. std::string Value;
  11145. SourceLocation Loc;
  11146. Value += "'";
  11147. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  11148. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11149. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  11150. Loc = MLoc;
  11151. } else {
  11152. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  11153. OMPC_DEFAULTMAP_scalar);
  11154. Loc = KindLoc;
  11155. }
  11156. Value += "'";
  11157. Diag(Loc, diag::err_omp_unexpected_clause_value)
  11158. << Value << getOpenMPClauseName(OMPC_defaultmap);
  11159. return nullptr;
  11160. }
  11161. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  11162. return new (Context)
  11163. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  11164. }
  11165. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  11166. DeclContext *CurLexicalContext = getCurLexicalContext();
  11167. if (!CurLexicalContext->isFileContext() &&
  11168. !CurLexicalContext->isExternCContext() &&
  11169. !CurLexicalContext->isExternCXXContext() &&
  11170. !isa<CXXRecordDecl>(CurLexicalContext) &&
  11171. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  11172. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  11173. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  11174. Diag(Loc, diag::err_omp_region_not_file_context);
  11175. return false;
  11176. }
  11177. if (IsInOpenMPDeclareTargetContext) {
  11178. Diag(Loc, diag::err_omp_enclosed_declare_target);
  11179. return false;
  11180. }
  11181. IsInOpenMPDeclareTargetContext = true;
  11182. return true;
  11183. }
  11184. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  11185. assert(IsInOpenMPDeclareTargetContext &&
  11186. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  11187. IsInOpenMPDeclareTargetContext = false;
  11188. }
  11189. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  11190. CXXScopeSpec &ScopeSpec,
  11191. const DeclarationNameInfo &Id,
  11192. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  11193. NamedDeclSetType &SameDirectiveDecls) {
  11194. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  11195. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  11196. if (Lookup.isAmbiguous())
  11197. return;
  11198. Lookup.suppressDiagnostics();
  11199. if (!Lookup.isSingleResult()) {
  11200. if (TypoCorrection Corrected =
  11201. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  11202. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  11203. CTK_ErrorRecovery)) {
  11204. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  11205. << Id.getName());
  11206. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  11207. return;
  11208. }
  11209. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  11210. return;
  11211. }
  11212. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  11213. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
  11214. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  11215. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  11216. if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
  11217. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  11218. ND->addAttr(A);
  11219. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11220. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  11221. checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
  11222. } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
  11223. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  11224. << Id.getName();
  11225. }
  11226. } else
  11227. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  11228. }
  11229. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  11230. Sema &SemaRef, Decl *D) {
  11231. if (!D)
  11232. return;
  11233. Decl *LD = nullptr;
  11234. if (isa<TagDecl>(D)) {
  11235. LD = cast<TagDecl>(D)->getDefinition();
  11236. } else if (isa<VarDecl>(D)) {
  11237. LD = cast<VarDecl>(D)->getDefinition();
  11238. // If this is an implicit variable that is legal and we do not need to do
  11239. // anything.
  11240. if (cast<VarDecl>(D)->isImplicit()) {
  11241. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11242. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11243. D->addAttr(A);
  11244. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11245. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11246. return;
  11247. }
  11248. } else if (isa<FunctionDecl>(D)) {
  11249. const FunctionDecl *FD = nullptr;
  11250. if (cast<FunctionDecl>(D)->hasBody(FD))
  11251. LD = const_cast<FunctionDecl *>(FD);
  11252. // If the definition is associated with the current declaration in the
  11253. // target region (it can be e.g. a lambda) that is legal and we do not need
  11254. // to do anything else.
  11255. if (LD == D) {
  11256. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11257. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11258. D->addAttr(A);
  11259. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11260. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11261. return;
  11262. }
  11263. }
  11264. if (!LD)
  11265. LD = D;
  11266. if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11267. (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
  11268. // Outlined declaration is not declared target.
  11269. if (LD->isOutOfLine()) {
  11270. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11271. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11272. } else {
  11273. DeclContext *DC = LD->getDeclContext();
  11274. while (DC) {
  11275. if (isa<FunctionDecl>(DC) &&
  11276. cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
  11277. break;
  11278. DC = DC->getParent();
  11279. }
  11280. if (DC)
  11281. return;
  11282. // Is not declared in target context.
  11283. SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
  11284. SemaRef.Diag(SL, diag::note_used_here) << SR;
  11285. }
  11286. // Mark decl as declared target to prevent further diagnostic.
  11287. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11288. SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
  11289. D->addAttr(A);
  11290. if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
  11291. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11292. }
  11293. }
  11294. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  11295. Sema &SemaRef, DSAStackTy *Stack,
  11296. ValueDecl *VD) {
  11297. if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
  11298. return true;
  11299. if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
  11300. return false;
  11301. return true;
  11302. }
  11303. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
  11304. if (!D || D->isInvalidDecl())
  11305. return;
  11306. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  11307. SourceLocation SL = E ? E->getLocStart() : D->getLocation();
  11308. // 2.10.6: threadprivate variable cannot appear in a declare target directive.
  11309. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  11310. if (DSAStack->isThreadPrivate(VD)) {
  11311. Diag(SL, diag::err_omp_threadprivate_in_target);
  11312. ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  11313. return;
  11314. }
  11315. }
  11316. if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  11317. // Problem if any with var declared with incomplete type will be reported
  11318. // as normal, so no need to check it here.
  11319. if ((E || !VD->getType()->isIncompleteType()) &&
  11320. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
  11321. // Mark decl as declared target to prevent further diagnostic.
  11322. if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
  11323. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11324. Context, OMPDeclareTargetDeclAttr::MT_To);
  11325. VD->addAttr(A);
  11326. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11327. ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
  11328. }
  11329. return;
  11330. }
  11331. }
  11332. if (!E) {
  11333. // Checking declaration inside declare target region.
  11334. if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
  11335. (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
  11336. Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  11337. Context, OMPDeclareTargetDeclAttr::MT_To);
  11338. D->addAttr(A);
  11339. if (ASTMutationListener *ML = Context.getASTMutationListener())
  11340. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  11341. }
  11342. return;
  11343. }
  11344. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  11345. }
  11346. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  11347. SourceLocation StartLoc,
  11348. SourceLocation LParenLoc,
  11349. SourceLocation EndLoc) {
  11350. MappableVarListInfo MVLI(VarList);
  11351. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
  11352. if (MVLI.ProcessedVarList.empty())
  11353. return nullptr;
  11354. return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11355. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11356. MVLI.VarComponents);
  11357. }
  11358. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  11359. SourceLocation StartLoc,
  11360. SourceLocation LParenLoc,
  11361. SourceLocation EndLoc) {
  11362. MappableVarListInfo MVLI(VarList);
  11363. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
  11364. if (MVLI.ProcessedVarList.empty())
  11365. return nullptr;
  11366. return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11367. MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  11368. MVLI.VarComponents);
  11369. }
  11370. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  11371. SourceLocation StartLoc,
  11372. SourceLocation LParenLoc,
  11373. SourceLocation EndLoc) {
  11374. MappableVarListInfo MVLI(VarList);
  11375. SmallVector<Expr *, 8> PrivateCopies;
  11376. SmallVector<Expr *, 8> Inits;
  11377. for (auto &RefExpr : VarList) {
  11378. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  11379. SourceLocation ELoc;
  11380. SourceRange ERange;
  11381. Expr *SimpleRefExpr = RefExpr;
  11382. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11383. if (Res.second) {
  11384. // It will be analyzed later.
  11385. MVLI.ProcessedVarList.push_back(RefExpr);
  11386. PrivateCopies.push_back(nullptr);
  11387. Inits.push_back(nullptr);
  11388. }
  11389. ValueDecl *D = Res.first;
  11390. if (!D)
  11391. continue;
  11392. QualType Type = D->getType();
  11393. Type = Type.getNonReferenceType().getUnqualifiedType();
  11394. auto *VD = dyn_cast<VarDecl>(D);
  11395. // Item should be a pointer or reference to pointer.
  11396. if (!Type->isPointerType()) {
  11397. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  11398. << 0 << RefExpr->getSourceRange();
  11399. continue;
  11400. }
  11401. // Build the private variable and the expression that refers to it.
  11402. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  11403. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11404. if (VDPrivate->isInvalidDecl())
  11405. continue;
  11406. CurContext->addDecl(VDPrivate);
  11407. auto VDPrivateRefExpr = buildDeclRefExpr(
  11408. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  11409. // Add temporary variable to initialize the private copy of the pointer.
  11410. auto *VDInit =
  11411. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  11412. auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  11413. RefExpr->getExprLoc());
  11414. AddInitializerToDecl(VDPrivate,
  11415. DefaultLvalueConversion(VDInitRefExpr).get(),
  11416. /*DirectInit=*/false);
  11417. // If required, build a capture to implement the privatization initialized
  11418. // with the current list item value.
  11419. DeclRefExpr *Ref = nullptr;
  11420. if (!VD)
  11421. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11422. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  11423. PrivateCopies.push_back(VDPrivateRefExpr);
  11424. Inits.push_back(VDInitRefExpr);
  11425. // We need to add a data sharing attribute for this variable to make sure it
  11426. // is correctly captured. A variable that shows up in a use_device_ptr has
  11427. // similar properties of a first private variable.
  11428. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  11429. // Create a mappable component for the list item. List items in this clause
  11430. // only need a component.
  11431. MVLI.VarBaseDeclarations.push_back(D);
  11432. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11433. MVLI.VarComponents.back().push_back(
  11434. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  11435. }
  11436. if (MVLI.ProcessedVarList.empty())
  11437. return nullptr;
  11438. return OMPUseDevicePtrClause::Create(
  11439. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11440. PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11441. }
  11442. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  11443. SourceLocation StartLoc,
  11444. SourceLocation LParenLoc,
  11445. SourceLocation EndLoc) {
  11446. MappableVarListInfo MVLI(VarList);
  11447. for (auto &RefExpr : VarList) {
  11448. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  11449. SourceLocation ELoc;
  11450. SourceRange ERange;
  11451. Expr *SimpleRefExpr = RefExpr;
  11452. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11453. if (Res.second) {
  11454. // It will be analyzed later.
  11455. MVLI.ProcessedVarList.push_back(RefExpr);
  11456. }
  11457. ValueDecl *D = Res.first;
  11458. if (!D)
  11459. continue;
  11460. QualType Type = D->getType();
  11461. // item should be a pointer or array or reference to pointer or array
  11462. if (!Type.getNonReferenceType()->isPointerType() &&
  11463. !Type.getNonReferenceType()->isArrayType()) {
  11464. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  11465. << 0 << RefExpr->getSourceRange();
  11466. continue;
  11467. }
  11468. // Check if the declaration in the clause does not show up in any data
  11469. // sharing attribute.
  11470. auto DVar = DSAStack->getTopDSA(D, false);
  11471. if (isOpenMPPrivate(DVar.CKind)) {
  11472. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  11473. << getOpenMPClauseName(DVar.CKind)
  11474. << getOpenMPClauseName(OMPC_is_device_ptr)
  11475. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11476. ReportOriginalDSA(*this, DSAStack, D, DVar);
  11477. continue;
  11478. }
  11479. Expr *ConflictExpr;
  11480. if (DSAStack->checkMappableExprComponentListsForDecl(
  11481. D, /*CurrentRegionOnly=*/true,
  11482. [&ConflictExpr](
  11483. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  11484. OpenMPClauseKind) -> bool {
  11485. ConflictExpr = R.front().getAssociatedExpression();
  11486. return true;
  11487. })) {
  11488. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  11489. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  11490. << ConflictExpr->getSourceRange();
  11491. continue;
  11492. }
  11493. // Store the components in the stack so that they can be used to check
  11494. // against other clauses later on.
  11495. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  11496. DSAStack->addMappableExpressionComponents(
  11497. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  11498. // Record the expression we've just processed.
  11499. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  11500. // Create a mappable component for the list item. List items in this clause
  11501. // only need a component. We use a null declaration to signal fields in
  11502. // 'this'.
  11503. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  11504. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  11505. "Unexpected device pointer expression!");
  11506. MVLI.VarBaseDeclarations.push_back(
  11507. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  11508. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  11509. MVLI.VarComponents.back().push_back(MC);
  11510. }
  11511. if (MVLI.ProcessedVarList.empty())
  11512. return nullptr;
  11513. return OMPIsDevicePtrClause::Create(
  11514. Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
  11515. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  11516. }