cmGeneratorTarget.cxx 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmGeneratorTarget.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstddef>
  9. #include <cstdio>
  10. #include <cstring>
  11. #include <sstream>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/string_view>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include "cmAlgorithms.h"
  20. #include "cmComputeLinkInformation.h" // IWYU pragma: keep
  21. #include "cmCryptoHash.h"
  22. #include "cmCxxModuleUsageEffects.h"
  23. #include "cmExperimental.h"
  24. #include "cmFileSet.h"
  25. #include "cmFileTimes.h"
  26. #include "cmGenExContext.h"
  27. #include "cmGeneratedFileStream.h"
  28. #include "cmGeneratorExpression.h"
  29. #include "cmGeneratorExpressionDAGChecker.h"
  30. #include "cmGeneratorOptions.h"
  31. #include "cmGlobalGenerator.h"
  32. #include "cmList.h"
  33. #include "cmLocalGenerator.h"
  34. #include "cmMakefile.h"
  35. #include "cmMessageType.h"
  36. #include "cmOutputConverter.h"
  37. #include "cmPropertyMap.h"
  38. #include "cmRulePlaceholderExpander.h"
  39. #include "cmSourceFile.h"
  40. #include "cmSourceFileLocation.h"
  41. #include "cmSourceFileLocationKind.h"
  42. #include "cmStandardLevel.h"
  43. #include "cmStandardLevelResolver.h"
  44. #include "cmState.h"
  45. #include "cmStateTypes.h"
  46. #include "cmStringAlgorithms.h"
  47. #include "cmSyntheticTargetCache.h"
  48. #include "cmSystemTools.h"
  49. #include "cmTarget.h"
  50. #include "cmTargetLinkLibraryType.h"
  51. #include "cmTargetPropertyComputer.h"
  52. #include "cmTargetTraceDependencies.h"
  53. #include "cmake.h"
  54. namespace {
  55. using UseTo = cmGeneratorTarget::UseTo;
  56. }
  57. template <>
  58. cmValue cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
  59. cmGeneratorTarget const* tgt)
  60. {
  61. return tgt->GetSourcesProperty();
  62. }
  63. template <>
  64. std::string const&
  65. cmTargetPropertyComputer::ImportedLocation<cmGeneratorTarget>(
  66. cmGeneratorTarget const* tgt, std::string const& config)
  67. {
  68. return tgt->GetLocation(config);
  69. }
  70. static void CreatePropertyGeneratorExpressions(
  71. cmake& cmakeInstance, cmBTStringRange entries,
  72. std::vector<std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>>& items,
  73. bool evaluateForBuildsystem = false)
  74. {
  75. for (auto const& entry : entries) {
  76. items.emplace_back(cmGeneratorTarget::TargetPropertyEntry::Create(
  77. cmakeInstance, entry, evaluateForBuildsystem));
  78. }
  79. }
  80. cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
  81. : Target(t)
  82. {
  83. this->Makefile = this->Target->GetMakefile();
  84. this->LocalGenerator = lg;
  85. this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
  86. this->GlobalGenerator->ComputeTargetObjectDirectory(this);
  87. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  88. t->GetIncludeDirectoriesEntries(),
  89. this->IncludeDirectoriesEntries);
  90. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  91. t->GetCompileOptionsEntries(),
  92. this->CompileOptionsEntries);
  93. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  94. t->GetCompileFeaturesEntries(),
  95. this->CompileFeaturesEntries);
  96. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  97. t->GetCompileDefinitionsEntries(),
  98. this->CompileDefinitionsEntries);
  99. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  100. t->GetLinkOptionsEntries(),
  101. this->LinkOptionsEntries);
  102. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  103. t->GetLinkDirectoriesEntries(),
  104. this->LinkDirectoriesEntries);
  105. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  106. t->GetPrecompileHeadersEntries(),
  107. this->PrecompileHeadersEntries);
  108. CreatePropertyGeneratorExpressions(
  109. *lg->GetCMakeInstance(), t->GetSourceEntries(), this->SourceEntries, true);
  110. this->PolicyMap = t->GetPolicyMap();
  111. // Get hard-coded linker language
  112. if (this->Target->GetProperty("HAS_CXX")) {
  113. this->LinkerLanguage = "CXX";
  114. } else {
  115. this->LinkerLanguage = this->Target->GetSafeProperty("LINKER_LANGUAGE");
  116. }
  117. auto configs =
  118. this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  119. std::string build_db_languages[] = { "CXX" };
  120. for (auto const& language : build_db_languages) {
  121. for (auto const& config : configs) {
  122. auto bdb_path = this->BuildDatabasePath(language, config);
  123. if (!bdb_path.empty()) {
  124. this->Makefile->GetOrCreateGeneratedSource(bdb_path);
  125. this->GetGlobalGenerator()->AddBuildDatabaseFile(language, config,
  126. bdb_path);
  127. }
  128. }
  129. }
  130. }
  131. cmGeneratorTarget::~cmGeneratorTarget() = default;
  132. cmValue cmGeneratorTarget::GetSourcesProperty() const
  133. {
  134. std::vector<std::string> values;
  135. for (auto const& se : this->SourceEntries) {
  136. values.push_back(se->GetInput());
  137. }
  138. static std::string value;
  139. value = cmList::to_string(values);
  140. return cmValue(value);
  141. }
  142. cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
  143. {
  144. return this->GetLocalGenerator()->GetGlobalGenerator();
  145. }
  146. cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
  147. {
  148. return this->LocalGenerator;
  149. }
  150. cmStateEnums::TargetType cmGeneratorTarget::GetType() const
  151. {
  152. return this->Target->GetType();
  153. }
  154. std::string const& cmGeneratorTarget::GetName() const
  155. {
  156. return this->Target->GetName();
  157. }
  158. std::string cmGeneratorTarget::GetFamilyName() const
  159. {
  160. if (!this->IsImported() && !this->IsSynthetic()) {
  161. return this->Target->GetTemplateName();
  162. }
  163. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  164. constexpr size_t HASH_TRUNCATION = 12;
  165. auto dirhash =
  166. hasher.HashString(this->GetLocalGenerator()->GetCurrentBinaryDirectory());
  167. auto targetIdent = hasher.HashString(cmStrCat("@d_", dirhash));
  168. return cmStrCat(this->Target->GetTemplateName(), '@',
  169. targetIdent.substr(0, HASH_TRUNCATION));
  170. }
  171. std::string cmGeneratorTarget::GetExportName() const
  172. {
  173. cmValue exportName = this->GetProperty("EXPORT_NAME");
  174. if (cmNonempty(exportName)) {
  175. if (!cmGeneratorExpression::IsValidTargetName(*exportName)) {
  176. std::ostringstream e;
  177. e << "EXPORT_NAME property \"" << *exportName << "\" for \""
  178. << this->GetName() << "\": is not valid.";
  179. cmSystemTools::Error(e.str());
  180. return "";
  181. }
  182. return *exportName;
  183. }
  184. return this->GetName();
  185. }
  186. std::string cmGeneratorTarget::GetFilesystemExportName() const
  187. {
  188. auto fs_safe = this->GetExportName();
  189. // First escape any `_` characters to avoid collisions.
  190. cmSystemTools::ReplaceString(fs_safe, "_", "__");
  191. // Escape other characters that are not generally filesystem-safe.
  192. cmSystemTools::ReplaceString(fs_safe, ":", "_c");
  193. return fs_safe;
  194. }
  195. cmValue cmGeneratorTarget::GetProperty(std::string const& prop) const
  196. {
  197. if (cmValue result =
  198. cmTargetPropertyComputer::GetProperty(this, prop, *this->Makefile)) {
  199. return result;
  200. }
  201. if (cmSystemTools::GetFatalErrorOccurred()) {
  202. return nullptr;
  203. }
  204. return this->Target->GetProperty(prop);
  205. }
  206. std::string const& cmGeneratorTarget::GetSafeProperty(
  207. std::string const& prop) const
  208. {
  209. return this->GetProperty(prop);
  210. }
  211. char const* cmGeneratorTarget::GetOutputTargetType(
  212. cmStateEnums::ArtifactType artifact) const
  213. {
  214. if (this->IsFrameworkOnApple() || this->GetGlobalGenerator()->IsXcode()) {
  215. // import file (i.e. .tbd file) is always in same location as library
  216. artifact = cmStateEnums::RuntimeBinaryArtifact;
  217. }
  218. switch (this->GetType()) {
  219. case cmStateEnums::SHARED_LIBRARY:
  220. if (this->IsDLLPlatform()) {
  221. switch (artifact) {
  222. case cmStateEnums::RuntimeBinaryArtifact:
  223. // A DLL shared library is treated as a runtime target.
  224. return "RUNTIME";
  225. case cmStateEnums::ImportLibraryArtifact:
  226. // A DLL import library is treated as an archive target.
  227. return "ARCHIVE";
  228. }
  229. } else {
  230. switch (artifact) {
  231. case cmStateEnums::RuntimeBinaryArtifact:
  232. // For non-DLL platforms shared libraries are treated as
  233. // library targets.
  234. return "LIBRARY";
  235. case cmStateEnums::ImportLibraryArtifact:
  236. // Library import libraries are treated as archive targets.
  237. return "ARCHIVE";
  238. }
  239. }
  240. break;
  241. case cmStateEnums::STATIC_LIBRARY:
  242. // Static libraries are always treated as archive targets.
  243. return "ARCHIVE";
  244. case cmStateEnums::MODULE_LIBRARY:
  245. switch (artifact) {
  246. case cmStateEnums::RuntimeBinaryArtifact:
  247. // Module libraries are always treated as library targets.
  248. return "LIBRARY";
  249. case cmStateEnums::ImportLibraryArtifact:
  250. // Module import libraries are treated as archive targets.
  251. return "ARCHIVE";
  252. }
  253. break;
  254. case cmStateEnums::OBJECT_LIBRARY:
  255. // Object libraries are always treated as object targets.
  256. return "OBJECT";
  257. case cmStateEnums::EXECUTABLE:
  258. switch (artifact) {
  259. case cmStateEnums::RuntimeBinaryArtifact:
  260. // Executables are always treated as runtime targets.
  261. return "RUNTIME";
  262. case cmStateEnums::ImportLibraryArtifact:
  263. // Executable import libraries are treated as archive targets.
  264. return "ARCHIVE";
  265. }
  266. break;
  267. default:
  268. break;
  269. }
  270. return "";
  271. }
  272. std::string cmGeneratorTarget::GetOutputName(
  273. std::string const& config, cmStateEnums::ArtifactType artifact) const
  274. {
  275. // Lookup/compute/cache the output name for this configuration.
  276. OutputNameKey key(config, artifact);
  277. auto i = this->OutputNameMap.find(key);
  278. if (i == this->OutputNameMap.end()) {
  279. // Add empty name in map to detect potential recursion.
  280. OutputNameMapType::value_type entry(key, "");
  281. i = this->OutputNameMap.insert(entry).first;
  282. // Compute output name.
  283. std::vector<std::string> props;
  284. std::string type = this->GetOutputTargetType(artifact);
  285. std::string configUpper = cmSystemTools::UpperCase(config);
  286. if (!type.empty() && !configUpper.empty()) {
  287. // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME_<CONFIG>
  288. props.push_back(type + "_OUTPUT_NAME_" + configUpper);
  289. }
  290. if (!type.empty()) {
  291. // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME
  292. props.push_back(type + "_OUTPUT_NAME");
  293. }
  294. if (!configUpper.empty()) {
  295. // OUTPUT_NAME_<CONFIG>
  296. props.push_back("OUTPUT_NAME_" + configUpper);
  297. // <CONFIG>_OUTPUT_NAME
  298. props.push_back(configUpper + "_OUTPUT_NAME");
  299. }
  300. // OUTPUT_NAME
  301. props.emplace_back("OUTPUT_NAME");
  302. std::string outName;
  303. for (std::string const& p : props) {
  304. if (cmValue outNameProp = this->GetProperty(p)) {
  305. outName = *outNameProp;
  306. break;
  307. }
  308. }
  309. if (outName.empty()) {
  310. outName = this->GetName();
  311. }
  312. // Now evaluate genex and update the previously-prepared map entry.
  313. i->second =
  314. cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
  315. } else if (i->second.empty()) {
  316. // An empty map entry indicates we have been called recursively
  317. // from the above block.
  318. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  319. MessageType::FATAL_ERROR,
  320. "Target '" + this->GetName() + "' OUTPUT_NAME depends on itself.",
  321. this->GetBacktrace());
  322. }
  323. return i->second;
  324. }
  325. std::string cmGeneratorTarget::GetFilePrefix(
  326. std::string const& config, cmStateEnums::ArtifactType artifact) const
  327. {
  328. if (this->IsImported()) {
  329. cmValue prefix = this->GetFilePrefixInternal(config, artifact);
  330. return prefix ? *prefix : std::string();
  331. }
  332. return this->GetFullNameInternalComponents(config, artifact).prefix;
  333. }
  334. std::string cmGeneratorTarget::GetFileSuffix(
  335. std::string const& config, cmStateEnums::ArtifactType artifact) const
  336. {
  337. if (this->IsImported()) {
  338. cmValue suffix = this->GetFileSuffixInternal(config, artifact);
  339. return suffix ? *suffix : std::string();
  340. }
  341. return this->GetFullNameInternalComponents(config, artifact).suffix;
  342. }
  343. std::string cmGeneratorTarget::GetFilePostfix(std::string const& config) const
  344. {
  345. cmValue postfix = nullptr;
  346. std::string frameworkPostfix;
  347. if (!config.empty()) {
  348. std::string configProp =
  349. cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
  350. postfix = this->GetProperty(configProp);
  351. // Mac application bundles and frameworks have no regular postfix like
  352. // libraries do.
  353. if (!this->IsImported() && postfix &&
  354. (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
  355. postfix = nullptr;
  356. }
  357. // Frameworks created by multi config generators can have a special
  358. // framework postfix.
  359. frameworkPostfix = this->GetFrameworkMultiConfigPostfix(config);
  360. if (!frameworkPostfix.empty()) {
  361. postfix = cmValue(frameworkPostfix);
  362. }
  363. }
  364. return postfix ? *postfix : std::string();
  365. }
  366. std::string cmGeneratorTarget::GetFrameworkMultiConfigPostfix(
  367. std::string const& config) const
  368. {
  369. cmValue postfix = nullptr;
  370. if (!config.empty()) {
  371. std::string configProp = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_",
  372. cmSystemTools::UpperCase(config));
  373. postfix = this->GetProperty(configProp);
  374. if (!this->IsImported() && postfix &&
  375. (this->IsFrameworkOnApple() &&
  376. !this->GetGlobalGenerator()->IsMultiConfig())) {
  377. postfix = nullptr;
  378. }
  379. }
  380. return postfix ? *postfix : std::string();
  381. }
  382. cmValue cmGeneratorTarget::GetFilePrefixInternal(
  383. std::string const& config, cmStateEnums::ArtifactType artifact,
  384. std::string const& language) const
  385. {
  386. // no prefix for non-main target types.
  387. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  388. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  389. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  390. this->GetType() != cmStateEnums::EXECUTABLE) {
  391. return nullptr;
  392. }
  393. bool const isImportedLibraryArtifact =
  394. (artifact == cmStateEnums::ImportLibraryArtifact);
  395. // Return an empty prefix for the import library if this platform
  396. // does not support import libraries.
  397. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  398. return nullptr;
  399. }
  400. // The implib option is only allowed for shared libraries, module
  401. // libraries, and executables.
  402. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  403. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  404. this->GetType() != cmStateEnums::EXECUTABLE) {
  405. artifact = cmStateEnums::RuntimeBinaryArtifact;
  406. }
  407. // Compute prefix value.
  408. cmValue targetPrefix =
  409. (isImportedLibraryArtifact ? this->GetProperty("IMPORT_PREFIX")
  410. : this->GetProperty("PREFIX"));
  411. if (!targetPrefix) {
  412. char const* prefixVar = this->Target->GetPrefixVariableInternal(artifact);
  413. if (!language.empty() && cmNonempty(prefixVar)) {
  414. std::string langPrefix = cmStrCat(prefixVar, '_', language);
  415. targetPrefix = this->Makefile->GetDefinition(langPrefix);
  416. }
  417. // if there is no prefix on the target nor specific language
  418. // use the cmake definition.
  419. if (!targetPrefix && prefixVar) {
  420. targetPrefix = this->Makefile->GetDefinition(prefixVar);
  421. }
  422. }
  423. return targetPrefix;
  424. }
  425. cmValue cmGeneratorTarget::GetFileSuffixInternal(
  426. std::string const& config, cmStateEnums::ArtifactType artifact,
  427. std::string const& language) const
  428. {
  429. // no suffix for non-main target types.
  430. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  431. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  432. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  433. this->GetType() != cmStateEnums::EXECUTABLE) {
  434. return nullptr;
  435. }
  436. bool const isImportedLibraryArtifact =
  437. (artifact == cmStateEnums::ImportLibraryArtifact);
  438. // Return an empty suffix for the import library if this platform
  439. // does not support import libraries.
  440. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  441. return nullptr;
  442. }
  443. // The implib option is only allowed for shared libraries, module
  444. // libraries, and executables.
  445. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  446. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  447. this->GetType() != cmStateEnums::EXECUTABLE) {
  448. artifact = cmStateEnums::RuntimeBinaryArtifact;
  449. }
  450. // Compute suffix value.
  451. cmValue targetSuffix =
  452. (isImportedLibraryArtifact ? this->GetProperty("IMPORT_SUFFIX")
  453. : this->GetProperty("SUFFIX"));
  454. if (!targetSuffix) {
  455. char const* suffixVar = this->Target->GetSuffixVariableInternal(artifact);
  456. if (!language.empty() && cmNonempty(suffixVar)) {
  457. std::string langSuffix = cmStrCat(suffixVar, '_', language);
  458. targetSuffix = this->Makefile->GetDefinition(langSuffix);
  459. }
  460. // if there is no suffix on the target nor specific language
  461. // use the cmake definition.
  462. if (!targetSuffix && suffixVar) {
  463. targetSuffix = this->Makefile->GetDefinition(suffixVar);
  464. }
  465. }
  466. return targetSuffix;
  467. }
  468. void cmGeneratorTarget::ClearSourcesCache()
  469. {
  470. this->AllConfigSources.clear();
  471. this->KindedSourcesMap.clear();
  472. this->SourcesAreContextDependent = Tribool::Indeterminate;
  473. this->Objects.clear();
  474. this->VisitedConfigsForObjects.clear();
  475. this->LinkImplClosureForLinkMap.clear();
  476. this->LinkImplClosureForUsageMap.clear();
  477. this->LinkImplMap.clear();
  478. this->LinkImplUsageRequirementsOnlyMap.clear();
  479. this->IncludeDirectoriesCache.clear();
  480. this->CompileOptionsCache.clear();
  481. this->CompileDefinitionsCache.clear();
  482. this->CustomTransitiveBuildPropertiesMap.clear();
  483. this->CustomTransitiveInterfacePropertiesMap.clear();
  484. this->PrecompileHeadersCache.clear();
  485. this->LinkOptionsCache.clear();
  486. this->LinkDirectoriesCache.clear();
  487. this->RuntimeBinaryFullNameCache.clear();
  488. this->ImportLibraryFullNameCache.clear();
  489. }
  490. void cmGeneratorTarget::ClearLinkInterfaceCache()
  491. {
  492. this->LinkInterfaceMap.clear();
  493. this->LinkInterfaceUsageRequirementsOnlyMap.clear();
  494. }
  495. void cmGeneratorTarget::AddSourceCommon(std::string const& src, bool before)
  496. {
  497. this->SourceEntries.insert(
  498. before ? this->SourceEntries.begin() : this->SourceEntries.end(),
  499. TargetPropertyEntry::Create(
  500. *this->LocalGenerator->GetCMakeInstance(),
  501. BT<std::string>(src, this->Makefile->GetBacktrace()), true));
  502. this->ClearSourcesCache();
  503. }
  504. cmSourceFile* cmGeneratorTarget::AddSource(std::string const& src, bool before)
  505. {
  506. auto* sf = this->Target->AddSource(src, before);
  507. this->AddSourceCommon(src, before);
  508. return sf;
  509. }
  510. void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
  511. {
  512. this->Target->AddTracedSources(srcs);
  513. if (!srcs.empty()) {
  514. this->AddSourceCommon(cmJoin(srcs, ";"));
  515. }
  516. }
  517. void cmGeneratorTarget::AddIncludeDirectory(std::string const& src,
  518. bool before)
  519. {
  520. this->Target->InsertInclude(
  521. BT<std::string>(src, this->Makefile->GetBacktrace()), before);
  522. this->IncludeDirectoriesEntries.insert(
  523. before ? this->IncludeDirectoriesEntries.begin()
  524. : this->IncludeDirectoriesEntries.end(),
  525. TargetPropertyEntry::Create(
  526. *this->Makefile->GetCMakeInstance(),
  527. BT<std::string>(src, this->Makefile->GetBacktrace()), true));
  528. }
  529. void cmGeneratorTarget::AddSystemIncludeDirectory(std::string const& inc,
  530. std::string const& lang)
  531. {
  532. std::string config_upper;
  533. auto const& configs =
  534. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  535. for (auto const& config : configs) {
  536. std::string inc_with_config = inc;
  537. if (!config.empty()) {
  538. cmSystemTools::ReplaceString(inc_with_config, "$<CONFIG>", config);
  539. config_upper = cmSystemTools::UpperCase(config);
  540. }
  541. auto const& key = cmStrCat(config_upper, '/', lang);
  542. this->Target->AddSystemIncludeDirectories({ inc_with_config });
  543. if (this->SystemIncludesCache.find(key) ==
  544. this->SystemIncludesCache.end()) {
  545. this->AddSystemIncludeCacheKey(key, config, lang);
  546. }
  547. this->SystemIncludesCache[key].emplace_back(inc_with_config);
  548. // SystemIncludesCache should be sorted so that binary search can be used
  549. std::sort(this->SystemIncludesCache[key].begin(),
  550. this->SystemIncludesCache[key].end());
  551. }
  552. }
  553. std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
  554. cmSourceFile const* sf) const
  555. {
  556. auto i = this->SourceDepends.find(sf);
  557. if (i != this->SourceDepends.end()) {
  558. return &i->second.Depends;
  559. }
  560. return nullptr;
  561. }
  562. namespace {
  563. void handleSystemIncludesDep(cmLocalGenerator const* lg,
  564. cmGeneratorTarget const* depTgt,
  565. std::string const& config,
  566. cmGeneratorTarget const* headTarget,
  567. cmGeneratorExpressionDAGChecker* dagChecker,
  568. cmList& result, bool excludeImported,
  569. std::string const& language)
  570. {
  571. if (cmValue dirs =
  572. depTgt->GetProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES")) {
  573. result.append(cmGeneratorExpression::Evaluate(
  574. *dirs, lg, config, headTarget, dagChecker, depTgt, language));
  575. }
  576. if (!depTgt->GetPropertyAsBool("SYSTEM")) {
  577. return;
  578. }
  579. if (depTgt->IsImported()) {
  580. if (excludeImported) {
  581. return;
  582. }
  583. if (depTgt->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
  584. return;
  585. }
  586. }
  587. if (cmValue dirs = depTgt->GetProperty("INTERFACE_INCLUDE_DIRECTORIES")) {
  588. result.append(cmGeneratorExpression::Evaluate(
  589. *dirs, lg, config, headTarget, dagChecker, depTgt, language));
  590. }
  591. if (depTgt->Target->IsFrameworkOnApple() ||
  592. depTgt->IsImportedFrameworkFolderOnApple(config)) {
  593. if (auto fwDescriptor = depTgt->GetGlobalGenerator()->SplitFrameworkPath(
  594. depTgt->GetLocation(config))) {
  595. result.push_back(fwDescriptor->Directory);
  596. result.push_back(fwDescriptor->GetFrameworkPath());
  597. }
  598. }
  599. }
  600. }
  601. /* clang-format off */
  602. #define IMPLEMENT_VISIT(KIND) \
  603. do { \
  604. KindedSources const& kinded = this->GetKindedSources(config); \
  605. for (SourceAndKind const& s : kinded.Sources) { \
  606. if (s.Kind == KIND) { \
  607. data.push_back(s.Source.Value); \
  608. } \
  609. } \
  610. } while (false)
  611. /* clang-format on */
  612. void cmGeneratorTarget::GetObjectSources(
  613. std::vector<cmSourceFile const*>& data, std::string const& config) const
  614. {
  615. IMPLEMENT_VISIT(SourceKindObjectSource);
  616. if (this->VisitedConfigsForObjects.count(config)) {
  617. return;
  618. }
  619. for (cmSourceFile const* it : data) {
  620. this->Objects[it];
  621. }
  622. this->LocalGenerator->ComputeObjectFilenames(this->Objects, config, this);
  623. this->VisitedConfigsForObjects.insert(config);
  624. }
  625. void cmGeneratorTarget::ComputeObjectMapping()
  626. {
  627. auto const& configs =
  628. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  629. std::set<std::string> configSet(configs.begin(), configs.end());
  630. if (configSet == this->VisitedConfigsForObjects) {
  631. return;
  632. }
  633. for (std::string const& c : configs) {
  634. std::vector<cmSourceFile const*> sourceFiles;
  635. this->GetObjectSources(sourceFiles, c);
  636. }
  637. }
  638. cmValue cmGeneratorTarget::GetFeature(std::string const& feature,
  639. std::string const& config) const
  640. {
  641. if (!config.empty()) {
  642. std::string featureConfig =
  643. cmStrCat(feature, '_', cmSystemTools::UpperCase(config));
  644. if (cmValue value = this->GetProperty(featureConfig)) {
  645. return value;
  646. }
  647. }
  648. if (cmValue value = this->GetProperty(feature)) {
  649. return value;
  650. }
  651. return this->LocalGenerator->GetFeature(feature, config);
  652. }
  653. std::string cmGeneratorTarget::GetLinkerTypeProperty(
  654. std::string const& lang, std::string const& config) const
  655. {
  656. std::string propName{ "LINKER_TYPE" };
  657. auto linkerType = this->GetProperty(propName);
  658. if (!linkerType.IsEmpty()) {
  659. cm::GenEx::Context context(this->LocalGenerator, config, lang);
  660. cmGeneratorExpressionDAGChecker dagChecker{
  661. this, propName, nullptr, nullptr, context,
  662. };
  663. auto ltype = cmGeneratorExpression::Evaluate(
  664. *linkerType, context.LG, context.Config, this, &dagChecker, this,
  665. context.Language);
  666. if (this->IsDeviceLink()) {
  667. cmList list{ ltype };
  668. auto const DL_BEGIN = "<DEVICE_LINK>"_s;
  669. auto const DL_END = "</DEVICE_LINK>"_s;
  670. cm::erase_if(list, [&](std::string const& item) {
  671. return item == DL_BEGIN || item == DL_END;
  672. });
  673. return list.to_string();
  674. }
  675. return ltype;
  676. }
  677. return std::string{};
  678. }
  679. char const* cmGeneratorTarget::GetLinkPIEProperty(
  680. std::string const& config) const
  681. {
  682. static std::string PICValue;
  683. PICValue = this->GetLinkInterfaceDependentStringAsBoolProperty(
  684. "POSITION_INDEPENDENT_CODE", config);
  685. if (PICValue == "(unset)") {
  686. // POSITION_INDEPENDENT_CODE is not set
  687. return nullptr;
  688. }
  689. auto status = this->GetPolicyStatusCMP0083();
  690. return (status != cmPolicies::WARN && status != cmPolicies::OLD)
  691. ? PICValue.c_str()
  692. : nullptr;
  693. }
  694. bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang,
  695. std::string const& config) const
  696. {
  697. cmValue feature = this->GetFeature("INTERPROCEDURAL_OPTIMIZATION", config);
  698. if (!feature.IsOn()) {
  699. // 'INTERPROCEDURAL_OPTIMIZATION' is off, no need to check policies
  700. return false;
  701. }
  702. if (lang != "C" && lang != "CXX" && lang != "CUDA" && lang != "Fortran") {
  703. // We do not define IPO behavior for other languages.
  704. return false;
  705. }
  706. if (lang == "CUDA") {
  707. // CUDA IPO requires both CUDA_ARCHITECTURES and CUDA_SEPARABLE_COMPILATION
  708. if (cmIsOff(this->GetSafeProperty("CUDA_ARCHITECTURES")) ||
  709. cmIsOff(this->GetSafeProperty("CUDA_SEPARABLE_COMPILATION"))) {
  710. return false;
  711. }
  712. }
  713. cmPolicies::PolicyStatus cmp0069 = this->GetPolicyStatusCMP0069();
  714. if (cmp0069 == cmPolicies::OLD || cmp0069 == cmPolicies::WARN) {
  715. if (this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_LEGACY_BEHAVIOR")) {
  716. return true;
  717. }
  718. if (this->PolicyReportedCMP0069) {
  719. // problem is already reported, no need to issue a message
  720. return false;
  721. }
  722. bool const in_try_compile =
  723. this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile();
  724. if (cmp0069 == cmPolicies::WARN && !in_try_compile) {
  725. std::ostringstream w;
  726. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0069) << "\n";
  727. w << "INTERPROCEDURAL_OPTIMIZATION property will be ignored for target "
  728. << "'" << this->GetName() << "'.";
  729. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  730. MessageType::AUTHOR_WARNING, w.str(), this->GetBacktrace());
  731. this->PolicyReportedCMP0069 = true;
  732. }
  733. return false;
  734. }
  735. // Note: check consistency with messages from CheckIPOSupported
  736. char const* message = nullptr;
  737. if (!this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_SUPPORTED_BY_CMAKE")) {
  738. message = "CMake doesn't support IPO for current compiler";
  739. } else if (!this->Makefile->IsOn("_CMAKE_" + lang +
  740. "_IPO_MAY_BE_SUPPORTED_BY_COMPILER")) {
  741. message = "Compiler doesn't support IPO";
  742. } else if (!this->GlobalGenerator->IsIPOSupported()) {
  743. message = "CMake doesn't support IPO for current generator";
  744. }
  745. if (!message) {
  746. // No error/warning messages
  747. return true;
  748. }
  749. if (this->PolicyReportedCMP0069) {
  750. // problem is already reported, no need to issue a message
  751. return false;
  752. }
  753. this->PolicyReportedCMP0069 = true;
  754. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  755. MessageType::FATAL_ERROR, message, this->GetBacktrace());
  756. return false;
  757. }
  758. std::string const& cmGeneratorTarget::GetObjectName(cmSourceFile const* file)
  759. {
  760. this->ComputeObjectMapping();
  761. auto const useShortPaths = this->GetUseShortObjectNames()
  762. ? cmObjectLocations::UseShortPath::Yes
  763. : cmObjectLocations::UseShortPath::No;
  764. return this->Objects[file].GetPath(useShortPaths);
  765. }
  766. char const* cmGeneratorTarget::GetCustomObjectExtension() const
  767. {
  768. struct compiler_mode
  769. {
  770. std::string variable;
  771. std::string extension;
  772. };
  773. static std::array<compiler_mode, 4> const modes{
  774. { { "CUDA_PTX_COMPILATION", ".ptx" },
  775. { "CUDA_CUBIN_COMPILATION", ".cubin" },
  776. { "CUDA_FATBIN_COMPILATION", ".fatbin" },
  777. { "CUDA_OPTIX_COMPILATION", ".optixir" } }
  778. };
  779. std::string const& compiler =
  780. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  781. if (!compiler.empty()) {
  782. for (auto const& m : modes) {
  783. bool const has_extension = this->GetPropertyAsBool(m.variable);
  784. if (has_extension) {
  785. return m.extension.c_str();
  786. }
  787. }
  788. }
  789. return nullptr;
  790. }
  791. void cmGeneratorTarget::AddExplicitObjectName(cmSourceFile const* sf)
  792. {
  793. this->ExplicitObjectName.insert(sf);
  794. }
  795. bool cmGeneratorTarget::HasExplicitObjectName(cmSourceFile const* file) const
  796. {
  797. const_cast<cmGeneratorTarget*>(this)->ComputeObjectMapping();
  798. auto it = this->ExplicitObjectName.find(file);
  799. return it != this->ExplicitObjectName.end();
  800. }
  801. BTs<std::string> const* cmGeneratorTarget::GetLanguageStandardProperty(
  802. std::string const& lang, std::string const& config) const
  803. {
  804. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  805. auto langStandardIter = this->LanguageStandardMap.find(key);
  806. if (langStandardIter != this->LanguageStandardMap.end()) {
  807. return &langStandardIter->second;
  808. }
  809. return this->Target->GetLanguageStandardProperty(
  810. cmStrCat(lang, "_STANDARD"));
  811. }
  812. cmValue cmGeneratorTarget::GetLanguageStandard(std::string const& lang,
  813. std::string const& config) const
  814. {
  815. BTs<std::string> const* languageStandard =
  816. this->GetLanguageStandardProperty(lang, config);
  817. if (languageStandard) {
  818. return cmValue(languageStandard->Value);
  819. }
  820. return nullptr;
  821. }
  822. cmValue cmGeneratorTarget::GetPropertyWithPairedLanguageSupport(
  823. std::string const& lang, char const* suffix) const
  824. {
  825. cmValue propertyValue = this->Target->GetProperty(cmStrCat(lang, suffix));
  826. if (!propertyValue) {
  827. // Check if we should use the value set by another language.
  828. if (lang == "OBJC") {
  829. propertyValue = this->GetPropertyWithPairedLanguageSupport("C", suffix);
  830. } else if (lang == "OBJCXX" || lang == "CUDA" || lang == "HIP") {
  831. propertyValue =
  832. this->GetPropertyWithPairedLanguageSupport("CXX", suffix);
  833. }
  834. }
  835. return propertyValue;
  836. }
  837. cmValue cmGeneratorTarget::GetLanguageExtensions(std::string const& lang) const
  838. {
  839. return this->GetPropertyWithPairedLanguageSupport(lang, "_EXTENSIONS");
  840. }
  841. bool cmGeneratorTarget::GetLanguageStandardRequired(
  842. std::string const& lang) const
  843. {
  844. return this->GetPropertyWithPairedLanguageSupport(lang, "_STANDARD_REQUIRED")
  845. .IsOn();
  846. }
  847. void cmGeneratorTarget::GetModuleDefinitionSources(
  848. std::vector<cmSourceFile const*>& data, std::string const& config) const
  849. {
  850. IMPLEMENT_VISIT(SourceKindModuleDefinition);
  851. }
  852. void cmGeneratorTarget::GetHeaderSources(
  853. std::vector<cmSourceFile const*>& data, std::string const& config) const
  854. {
  855. IMPLEMENT_VISIT(SourceKindHeader);
  856. }
  857. void cmGeneratorTarget::GetCxxModuleSources(
  858. std::vector<cmSourceFile const*>& data, std::string const& config) const
  859. {
  860. IMPLEMENT_VISIT(SourceKindCxxModuleSource);
  861. }
  862. void cmGeneratorTarget::GetExtraSources(std::vector<cmSourceFile const*>& data,
  863. std::string const& config) const
  864. {
  865. IMPLEMENT_VISIT(SourceKindExtra);
  866. }
  867. void cmGeneratorTarget::GetCustomCommands(
  868. std::vector<cmSourceFile const*>& data, std::string const& config) const
  869. {
  870. IMPLEMENT_VISIT(SourceKindCustomCommand);
  871. }
  872. void cmGeneratorTarget::GetExternalObjects(
  873. std::vector<cmSourceFile const*>& data, std::string const& config) const
  874. {
  875. IMPLEMENT_VISIT(SourceKindExternalObject);
  876. }
  877. void cmGeneratorTarget::GetManifests(std::vector<cmSourceFile const*>& data,
  878. std::string const& config) const
  879. {
  880. IMPLEMENT_VISIT(SourceKindManifest);
  881. }
  882. std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const
  883. {
  884. if (!this->UtilityItemsDone) {
  885. this->UtilityItemsDone = true;
  886. std::set<BT<std::pair<std::string, bool>>> const& utilities =
  887. this->GetUtilities();
  888. for (BT<std::pair<std::string, bool>> const& i : utilities) {
  889. if (cmGeneratorTarget* gt =
  890. this->LocalGenerator->FindGeneratorTargetToUse(i.Value.first)) {
  891. this->UtilityItems.insert(cmLinkItem(gt, i.Value.second, i.Backtrace));
  892. } else {
  893. this->UtilityItems.insert(
  894. cmLinkItem(i.Value.first, i.Value.second, i.Backtrace));
  895. }
  896. }
  897. if (cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget()) {
  898. this->UtilityItems.insert(
  899. cmLinkItem(reuseTarget, false, cmListFileBacktrace()));
  900. }
  901. }
  902. return this->UtilityItems;
  903. }
  904. std::string const& cmGeneratorTarget::GetLocation(
  905. std::string const& config) const
  906. {
  907. static std::string location;
  908. if (this->IsImported()) {
  909. location = this->Target->ImportedGetFullPath(
  910. config, cmStateEnums::RuntimeBinaryArtifact);
  911. } else {
  912. location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  913. }
  914. return location;
  915. }
  916. cm::optional<std::string> cmGeneratorTarget::MaybeGetLocation(
  917. std::string const& config) const
  918. {
  919. cm::optional<std::string> location;
  920. if (cmGeneratorTarget::ImportInfo const* imp = this->GetImportInfo(config)) {
  921. if (!imp->Location.empty()) {
  922. location = imp->Location;
  923. }
  924. } else {
  925. location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  926. }
  927. return location;
  928. }
  929. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreBuildCommands()
  930. const
  931. {
  932. return this->Target->GetPreBuildCommands();
  933. }
  934. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreLinkCommands()
  935. const
  936. {
  937. return this->Target->GetPreLinkCommands();
  938. }
  939. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPostBuildCommands()
  940. const
  941. {
  942. return this->Target->GetPostBuildCommands();
  943. }
  944. void cmGeneratorTarget::AppendCustomCommandSideEffects(
  945. std::set<cmGeneratorTarget const*>& sideEffects) const
  946. {
  947. if (!this->GetPreBuildCommands().empty() ||
  948. !this->GetPreLinkCommands().empty() ||
  949. !this->GetPostBuildCommands().empty()) {
  950. sideEffects.insert(this);
  951. } else {
  952. for (auto const& source : this->GetAllConfigSources()) {
  953. if (source.Source->GetCustomCommand()) {
  954. sideEffects.insert(this);
  955. break;
  956. }
  957. }
  958. }
  959. }
  960. void cmGeneratorTarget::AppendLanguageSideEffects(
  961. std::map<std::string, std::set<cmGeneratorTarget const*>>& sideEffects) const
  962. {
  963. static std::set<cm::string_view> const LANGS_WITH_NO_SIDE_EFFECTS = {
  964. "C"_s, "CXX"_s, "OBJC"_s, "OBJCXX"_s, "ASM"_s, "CUDA"_s, "HIP"_s
  965. };
  966. for (auto const& lang : this->GetAllConfigCompileLanguages()) {
  967. if (!LANGS_WITH_NO_SIDE_EFFECTS.count(lang)) {
  968. sideEffects[lang].insert(this);
  969. }
  970. }
  971. }
  972. bool cmGeneratorTarget::IsInBuildSystem() const
  973. {
  974. if (this->IsImported()) {
  975. return false;
  976. }
  977. switch (this->Target->GetType()) {
  978. case cmStateEnums::EXECUTABLE:
  979. case cmStateEnums::STATIC_LIBRARY:
  980. case cmStateEnums::SHARED_LIBRARY:
  981. case cmStateEnums::MODULE_LIBRARY:
  982. case cmStateEnums::OBJECT_LIBRARY:
  983. case cmStateEnums::UTILITY:
  984. case cmStateEnums::GLOBAL_TARGET:
  985. return true;
  986. case cmStateEnums::INTERFACE_LIBRARY:
  987. // An INTERFACE library is in the build system if it has SOURCES
  988. // or C++ module filesets.
  989. if (!this->SourceEntries.empty() ||
  990. !this->Target->GetHeaderSetsEntries().empty() ||
  991. !this->Target->GetCxxModuleSetsEntries().empty()) {
  992. return true;
  993. }
  994. break;
  995. case cmStateEnums::UNKNOWN_LIBRARY:
  996. break;
  997. }
  998. return false;
  999. }
  1000. bool cmGeneratorTarget::IsNormal() const
  1001. {
  1002. return this->Target->IsNormal();
  1003. }
  1004. bool cmGeneratorTarget::IsRuntimeBinary() const
  1005. {
  1006. return this->Target->IsRuntimeBinary();
  1007. }
  1008. bool cmGeneratorTarget::IsSynthetic() const
  1009. {
  1010. return this->Target->IsSynthetic();
  1011. }
  1012. bool cmGeneratorTarget::IsImported() const
  1013. {
  1014. return this->Target->IsImported();
  1015. }
  1016. bool cmGeneratorTarget::IsImportedGloballyVisible() const
  1017. {
  1018. return this->Target->IsImportedGloballyVisible();
  1019. }
  1020. bool cmGeneratorTarget::IsSymbolic() const
  1021. {
  1022. return this->Target->IsSymbolic();
  1023. }
  1024. bool cmGeneratorTarget::IsForeign() const
  1025. {
  1026. return this->Target->IsForeign();
  1027. }
  1028. bool cmGeneratorTarget::CanCompileSources() const
  1029. {
  1030. return this->Target->CanCompileSources();
  1031. }
  1032. bool cmGeneratorTarget::HasKnownRuntimeArtifactLocation(
  1033. std::string const& config) const
  1034. {
  1035. if (!this->IsRuntimeBinary()) {
  1036. return false;
  1037. }
  1038. if (!this->IsImported()) {
  1039. return true;
  1040. }
  1041. ImportInfo const* info = this->GetImportInfo(config);
  1042. return info && !info->Location.empty();
  1043. }
  1044. std::string const& cmGeneratorTarget::GetLocationForBuild() const
  1045. {
  1046. static std::string location;
  1047. if (this->IsImported()) {
  1048. location = this->Target->ImportedGetFullPath(
  1049. "", cmStateEnums::RuntimeBinaryArtifact);
  1050. return location;
  1051. }
  1052. // Now handle the deprecated build-time configuration location.
  1053. std::string const noConfig;
  1054. location = this->GetDirectory(noConfig);
  1055. cmValue cfgid = this->Makefile->GetDefinition("CMAKE_CFG_INTDIR");
  1056. if (cfgid && (*cfgid != ".")) {
  1057. location += "/";
  1058. location += *cfgid;
  1059. }
  1060. if (this->IsAppBundleOnApple()) {
  1061. std::string macdir = this->BuildBundleDirectory("", "", FullLevel);
  1062. if (!macdir.empty()) {
  1063. location += "/";
  1064. location += macdir;
  1065. }
  1066. }
  1067. location += "/";
  1068. location += this->GetFullName("", cmStateEnums::RuntimeBinaryArtifact);
  1069. return location;
  1070. }
  1071. void cmGeneratorTarget::AddSystemIncludeCacheKey(
  1072. std::string const& key, std::string const& config,
  1073. std::string const& language) const
  1074. {
  1075. cm::GenEx::Context context(this->LocalGenerator, config, language);
  1076. cmGeneratorExpressionDAGChecker dagChecker{
  1077. this, "SYSTEM_INCLUDE_DIRECTORIES", nullptr, nullptr, context,
  1078. };
  1079. bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
  1080. cmList result;
  1081. for (std::string const& it : this->Target->GetSystemIncludeDirectories()) {
  1082. result.append(
  1083. cmGeneratorExpression::Evaluate(it, context.LG, context.Config, this,
  1084. &dagChecker, nullptr, context.Language));
  1085. }
  1086. std::vector<cmGeneratorTarget const*> const& deps =
  1087. this->GetLinkImplementationClosure(config, UseTo::Compile);
  1088. for (cmGeneratorTarget const* dep : deps) {
  1089. handleSystemIncludesDep(context.LG, dep, context.Config, this, &dagChecker,
  1090. result, excludeImported, context.Language);
  1091. }
  1092. cmLinkImplementation const* impl =
  1093. this->GetLinkImplementation(config, UseTo::Compile);
  1094. if (impl) {
  1095. auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
  1096. if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
  1097. for (auto const& lib : runtimeEntries->second) {
  1098. if (lib.Target) {
  1099. handleSystemIncludesDep(context.LG, lib.Target, context.Config, this,
  1100. &dagChecker, result, excludeImported,
  1101. context.Language);
  1102. }
  1103. }
  1104. }
  1105. }
  1106. std::for_each(result.begin(), result.end(),
  1107. cmSystemTools::ConvertToUnixSlashes);
  1108. std::sort(result.begin(), result.end());
  1109. result.erase(std::unique(result.begin(), result.end()), result.end());
  1110. SystemIncludesCache.emplace(key, result);
  1111. }
  1112. bool cmGeneratorTarget::IsSystemIncludeDirectory(
  1113. std::string const& dir, std::string const& config,
  1114. std::string const& language) const
  1115. {
  1116. std::string config_upper;
  1117. if (!config.empty()) {
  1118. config_upper = cmSystemTools::UpperCase(config);
  1119. }
  1120. std::string key = cmStrCat(config_upper, '/', language);
  1121. auto iter = this->SystemIncludesCache.find(key);
  1122. if (iter == this->SystemIncludesCache.end()) {
  1123. this->AddSystemIncludeCacheKey(key, config, language);
  1124. iter = this->SystemIncludesCache.find(key);
  1125. }
  1126. return std::binary_search(iter->second.begin(), iter->second.end(), dir);
  1127. }
  1128. bool cmGeneratorTarget::GetPropertyAsBool(std::string const& prop) const
  1129. {
  1130. return this->Target->GetPropertyAsBool(prop);
  1131. }
  1132. std::string cmGeneratorTarget::GetCompilePDBName(
  1133. std::string const& config) const
  1134. {
  1135. if (cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget()) {
  1136. if (reuseTarget != this) {
  1137. return reuseTarget->GetCompilePDBName(config);
  1138. }
  1139. }
  1140. // Check for a per-configuration output directory target property.
  1141. std::string configUpper = cmSystemTools::UpperCase(config);
  1142. std::string configProp = cmStrCat("COMPILE_PDB_NAME_", configUpper);
  1143. cmValue config_name = this->GetProperty(configProp);
  1144. if (cmNonempty(config_name)) {
  1145. std::string pdbName = cmGeneratorExpression::Evaluate(
  1146. *config_name, this->LocalGenerator, config, this);
  1147. NameComponents const& components = GetFullNameInternalComponents(
  1148. config, cmStateEnums::RuntimeBinaryArtifact);
  1149. return components.prefix + pdbName + ".pdb";
  1150. }
  1151. cmValue name = this->GetProperty("COMPILE_PDB_NAME");
  1152. if (cmNonempty(name)) {
  1153. std::string pdbName = cmGeneratorExpression::Evaluate(
  1154. *name, this->LocalGenerator, config, this);
  1155. NameComponents const& components = GetFullNameInternalComponents(
  1156. config, cmStateEnums::RuntimeBinaryArtifact);
  1157. return components.prefix + pdbName + ".pdb";
  1158. }
  1159. // If the target is PCH-reused, we need a stable name for the PDB file so
  1160. // that reusing targets can construct a stable name for it.
  1161. if (this->PchReused) {
  1162. NameComponents const& components = GetFullNameInternalComponents(
  1163. config, cmStateEnums::RuntimeBinaryArtifact);
  1164. return cmStrCat(components.prefix, this->GetName(), ".pdb");
  1165. }
  1166. return "";
  1167. }
  1168. std::string cmGeneratorTarget::GetCompilePDBPath(
  1169. std::string const& config) const
  1170. {
  1171. std::string dir = this->GetCompilePDBDirectory(config);
  1172. std::string name = this->GetCompilePDBName(config);
  1173. if (dir.empty() && !name.empty() && this->HaveWellDefinedOutputFiles()) {
  1174. dir = this->GetPDBDirectory(config);
  1175. }
  1176. if (!dir.empty()) {
  1177. dir += "/";
  1178. }
  1179. return dir + name;
  1180. }
  1181. bool cmGeneratorTarget::HasSOName(std::string const& config) const
  1182. {
  1183. // soname is supported only for shared libraries and modules,
  1184. // and then only when the platform supports an soname flag.
  1185. return ((this->GetType() == cmStateEnums::SHARED_LIBRARY) &&
  1186. !this->GetPropertyAsBool("NO_SONAME") &&
  1187. (this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)) ||
  1188. this->IsArchivedAIXSharedLibrary()));
  1189. }
  1190. bool cmGeneratorTarget::NeedRelinkBeforeInstall(
  1191. std::string const& config) const
  1192. {
  1193. // Only executables and shared libraries can have an rpath and may
  1194. // need relinking.
  1195. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  1196. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1197. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1198. return false;
  1199. }
  1200. // If there is no install location this target will not be installed
  1201. // and therefore does not need relinking.
  1202. if (!this->Target->GetHaveInstallRule()) {
  1203. return false;
  1204. }
  1205. // If skipping all rpaths completely then no relinking is needed.
  1206. if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
  1207. return false;
  1208. }
  1209. // If building with the install-tree rpath no relinking is needed.
  1210. if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
  1211. return false;
  1212. }
  1213. // If chrpath is going to be used no relinking is needed.
  1214. if (this->IsChrpathUsed(config)) {
  1215. return false;
  1216. }
  1217. // Check for rpath support on this platform.
  1218. std::string ll = this->GetLinkerLanguage(config);
  1219. if (!ll.empty()) {
  1220. std::string flagVar =
  1221. cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG");
  1222. if (!this->Makefile->IsSet(flagVar)) {
  1223. // There is no rpath support on this platform so nothing needs
  1224. // relinking.
  1225. return false;
  1226. }
  1227. } else {
  1228. // No linker language is known. This error will be reported by
  1229. // other code.
  1230. return false;
  1231. }
  1232. // If either a build or install tree rpath is set then the rpath
  1233. // will likely change between the build tree and install tree and
  1234. // this target must be relinked.
  1235. bool have_rpath =
  1236. this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH(config);
  1237. bool is_ninja = this->LocalGenerator->GetGlobalGenerator()->IsNinja();
  1238. if (have_rpath && is_ninja) {
  1239. std::ostringstream w;
  1240. /* clang-format off */
  1241. w <<
  1242. "The install of the " << this->GetName() << " target requires changing "
  1243. "an RPATH from the build tree, but this is not supported with the Ninja "
  1244. "generator unless on an ELF-based or XCOFF-based platform. "
  1245. "The CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this "
  1246. "relinking step."
  1247. ;
  1248. /* clang-format on */
  1249. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  1250. cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
  1251. }
  1252. return have_rpath;
  1253. }
  1254. bool cmGeneratorTarget::IsChrpathUsed(std::string const& config) const
  1255. {
  1256. // Only certain target types have an rpath.
  1257. if (!(this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1258. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1259. this->GetType() == cmStateEnums::EXECUTABLE)) {
  1260. return false;
  1261. }
  1262. // If the target will not be installed we do not need to change its
  1263. // rpath.
  1264. if (!this->Target->GetHaveInstallRule()) {
  1265. return false;
  1266. }
  1267. // Skip chrpath if skipping rpath altogether.
  1268. if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
  1269. return false;
  1270. }
  1271. // Skip chrpath if it does not need to be changed at install time.
  1272. if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
  1273. return false;
  1274. }
  1275. // Allow the user to disable builtin chrpath explicitly.
  1276. if (this->Makefile->IsOn("CMAKE_NO_BUILTIN_CHRPATH")) {
  1277. return false;
  1278. }
  1279. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1280. return true;
  1281. }
  1282. // Enable if the rpath flag uses a separator and the target uses
  1283. // binaries we know how to edit.
  1284. std::string ll = this->GetLinkerLanguage(config);
  1285. if (!ll.empty()) {
  1286. std::string sepVar =
  1287. cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP");
  1288. cmValue sep = this->Makefile->GetDefinition(sepVar);
  1289. if (cmNonempty(sep)) {
  1290. // TODO: Add binary format check to ABI detection and get rid of
  1291. // CMAKE_EXECUTABLE_FORMAT.
  1292. if (cmValue fmt =
  1293. this->Makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT")) {
  1294. if (*fmt == "ELF") {
  1295. return true;
  1296. }
  1297. #if defined(CMake_USE_XCOFF_PARSER)
  1298. if (*fmt == "XCOFF") {
  1299. return true;
  1300. }
  1301. #endif
  1302. }
  1303. }
  1304. }
  1305. return false;
  1306. }
  1307. bool cmGeneratorTarget::IsImportedSharedLibWithoutSOName(
  1308. std::string const& config) const
  1309. {
  1310. if (this->IsImported() && this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  1311. if (cmGeneratorTarget::ImportInfo const* info =
  1312. this->GetImportInfo(config)) {
  1313. return info->NoSOName;
  1314. }
  1315. }
  1316. return false;
  1317. }
  1318. bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
  1319. std::string const& config) const
  1320. {
  1321. TargetPtrToBoolMap& cache = this->MacOSXRpathInstallNameDirCache[config];
  1322. auto const lookup = cache.find(this->Target);
  1323. if (lookup != cache.cend()) {
  1324. return lookup->second;
  1325. }
  1326. bool const result = this->DetermineHasMacOSXRpathInstallNameDir(config);
  1327. cache[this->Target] = result;
  1328. return result;
  1329. }
  1330. bool cmGeneratorTarget::DetermineHasMacOSXRpathInstallNameDir(
  1331. std::string const& config) const
  1332. {
  1333. bool install_name_is_rpath = false;
  1334. bool macosx_rpath = false;
  1335. if (!this->IsImported()) {
  1336. if (this->GetType() != cmStateEnums::SHARED_LIBRARY) {
  1337. return false;
  1338. }
  1339. cmValue install_name = this->GetProperty("INSTALL_NAME_DIR");
  1340. bool use_install_name = this->MacOSXUseInstallNameDir();
  1341. if (install_name && use_install_name && *install_name == "@rpath") {
  1342. install_name_is_rpath = true;
  1343. } else if (install_name && use_install_name) {
  1344. return false;
  1345. }
  1346. if (!install_name_is_rpath) {
  1347. macosx_rpath = this->MacOSXRpathInstallNameDirDefault();
  1348. }
  1349. } else {
  1350. // Lookup the imported soname.
  1351. if (cmGeneratorTarget::ImportInfo const* info =
  1352. this->GetImportInfo(config)) {
  1353. if (!info->NoSOName && !info->SOName.empty()) {
  1354. if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
  1355. install_name_is_rpath = true;
  1356. }
  1357. } else {
  1358. std::string install_name;
  1359. cmSystemTools::GuessLibraryInstallName(info->Location, install_name);
  1360. if (install_name.find("@rpath") != std::string::npos) {
  1361. install_name_is_rpath = true;
  1362. }
  1363. }
  1364. }
  1365. }
  1366. if (!install_name_is_rpath && !macosx_rpath) {
  1367. return false;
  1368. }
  1369. if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
  1370. std::ostringstream w;
  1371. w << "Attempting to use ";
  1372. if (macosx_rpath) {
  1373. w << "MACOSX_RPATH";
  1374. } else {
  1375. w << "@rpath";
  1376. }
  1377. w << " without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set.";
  1378. w << " This could be because you are using a Mac OS X version";
  1379. w << " less than 10.5 or because CMake's platform configuration is";
  1380. w << " corrupt.";
  1381. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  1382. cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
  1383. }
  1384. return true;
  1385. }
  1386. bool cmGeneratorTarget::MacOSXRpathInstallNameDirDefault() const
  1387. {
  1388. // we can't do rpaths when unsupported
  1389. if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
  1390. return false;
  1391. }
  1392. cmValue macosx_rpath_str = this->GetProperty("MACOSX_RPATH");
  1393. if (macosx_rpath_str) {
  1394. return this->GetPropertyAsBool("MACOSX_RPATH");
  1395. }
  1396. return true;
  1397. }
  1398. bool cmGeneratorTarget::MacOSXUseInstallNameDir() const
  1399. {
  1400. cmValue build_with_install_name =
  1401. this->GetProperty("BUILD_WITH_INSTALL_NAME_DIR");
  1402. if (build_with_install_name) {
  1403. return build_with_install_name.IsOn();
  1404. }
  1405. cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
  1406. if (cmp0068 == cmPolicies::NEW) {
  1407. return false;
  1408. }
  1409. bool use_install_name = this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH");
  1410. if (use_install_name && cmp0068 == cmPolicies::WARN) {
  1411. this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
  1412. this->GetName());
  1413. }
  1414. return use_install_name;
  1415. }
  1416. bool cmGeneratorTarget::CanGenerateInstallNameDir(
  1417. InstallNameType name_type) const
  1418. {
  1419. cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
  1420. if (cmp0068 == cmPolicies::NEW) {
  1421. return true;
  1422. }
  1423. bool skip = this->Makefile->IsOn("CMAKE_SKIP_RPATH");
  1424. if (name_type == INSTALL_NAME_FOR_INSTALL) {
  1425. skip |= this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  1426. } else {
  1427. skip |= this->GetPropertyAsBool("SKIP_BUILD_RPATH");
  1428. }
  1429. if (skip && cmp0068 == cmPolicies::WARN) {
  1430. this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
  1431. this->GetName());
  1432. }
  1433. return !skip;
  1434. }
  1435. std::string cmGeneratorTarget::GetSOName(
  1436. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1437. {
  1438. if (this->IsImported()) {
  1439. // Lookup the imported soname.
  1440. if (cmGeneratorTarget::ImportInfo const* info =
  1441. this->GetImportInfo(config)) {
  1442. if (info->NoSOName) {
  1443. // The imported library has no builtin soname so the name
  1444. // searched at runtime will be just the filename.
  1445. return cmSystemTools::GetFilenameName(info->Location);
  1446. }
  1447. // Use the soname given if any.
  1448. if (this->IsFrameworkOnApple()) {
  1449. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  1450. info->SOName, cmGlobalGenerator::FrameworkFormat::Strict);
  1451. if (fwDescriptor) {
  1452. return fwDescriptor->GetVersionedName();
  1453. }
  1454. }
  1455. if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
  1456. return info->SOName.substr(cmStrLen("@rpath/"));
  1457. }
  1458. return info->SOName;
  1459. }
  1460. return "";
  1461. }
  1462. // Compute the soname that will be built.
  1463. return artifact == cmStateEnums::RuntimeBinaryArtifact
  1464. ? this->GetLibraryNames(config).SharedObject
  1465. : this->GetLibraryNames(config).ImportLibrary;
  1466. }
  1467. namespace {
  1468. bool shouldAddFullLevel(cmGeneratorTarget::BundleDirectoryLevel level)
  1469. {
  1470. return level == cmGeneratorTarget::FullLevel;
  1471. }
  1472. bool shouldAddContentLevel(cmGeneratorTarget::BundleDirectoryLevel level)
  1473. {
  1474. return level == cmGeneratorTarget::ContentLevel || shouldAddFullLevel(level);
  1475. }
  1476. }
  1477. std::string cmGeneratorTarget::GetAppBundleDirectory(
  1478. std::string const& config, BundleDirectoryLevel level) const
  1479. {
  1480. std::string fpath = cmStrCat(
  1481. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  1482. cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
  1483. fpath += (ext ? *ext : "app");
  1484. if (shouldAddContentLevel(level) &&
  1485. !this->Makefile->PlatformIsAppleEmbedded()) {
  1486. fpath += "/Contents";
  1487. if (shouldAddFullLevel(level)) {
  1488. fpath += "/MacOS";
  1489. }
  1490. }
  1491. return fpath;
  1492. }
  1493. bool cmGeneratorTarget::IsBundleOnApple() const
  1494. {
  1495. return this->IsFrameworkOnApple() || this->IsAppBundleOnApple() ||
  1496. this->IsCFBundleOnApple();
  1497. }
  1498. bool cmGeneratorTarget::IsWin32Executable(std::string const& config) const
  1499. {
  1500. return cmIsOn(cmGeneratorExpression::Evaluate(
  1501. this->GetSafeProperty("WIN32_EXECUTABLE"), this->LocalGenerator, config));
  1502. }
  1503. std::string cmGeneratorTarget::GetCFBundleDirectory(
  1504. std::string const& config, BundleDirectoryLevel level) const
  1505. {
  1506. std::string fpath = cmStrCat(
  1507. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  1508. std::string ext;
  1509. if (cmValue p = this->GetProperty("BUNDLE_EXTENSION")) {
  1510. ext = *p;
  1511. } else {
  1512. if (this->IsXCTestOnApple()) {
  1513. ext = "xctest";
  1514. } else {
  1515. ext = "bundle";
  1516. }
  1517. }
  1518. fpath += ext;
  1519. if (shouldAddContentLevel(level) &&
  1520. !this->Makefile->PlatformIsAppleEmbedded()) {
  1521. fpath += "/Contents";
  1522. if (shouldAddFullLevel(level)) {
  1523. fpath += "/MacOS";
  1524. }
  1525. }
  1526. return fpath;
  1527. }
  1528. std::string cmGeneratorTarget::GetFrameworkDirectory(
  1529. std::string const& config, BundleDirectoryLevel level) const
  1530. {
  1531. std::string fpath = cmStrCat(
  1532. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  1533. cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
  1534. fpath += (ext ? *ext : "framework");
  1535. if (shouldAddFullLevel(level) &&
  1536. !this->Makefile->PlatformIsAppleEmbedded()) {
  1537. fpath += "/Versions/";
  1538. fpath += this->GetFrameworkVersion();
  1539. }
  1540. return fpath;
  1541. }
  1542. std::string cmGeneratorTarget::GetFullName(
  1543. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1544. {
  1545. if (this->IsImported()) {
  1546. return this->GetFullNameImported(config, artifact);
  1547. }
  1548. return this->GetFullNameInternal(config, artifact);
  1549. }
  1550. std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
  1551. std::string const& config) const
  1552. {
  1553. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1554. // If building directly for installation then the build tree install_name
  1555. // is the same as the install tree.
  1556. if (this->MacOSXUseInstallNameDir()) {
  1557. std::string installPrefix =
  1558. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
  1559. return this->GetInstallNameDirForInstallTree(config, installPrefix);
  1560. }
  1561. // Use the build tree directory for the target.
  1562. if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_BUILD)) {
  1563. std::string dir;
  1564. if (this->MacOSXRpathInstallNameDirDefault()) {
  1565. dir = "@rpath";
  1566. } else {
  1567. dir = this->GetDirectory(config);
  1568. }
  1569. dir += "/";
  1570. return dir;
  1571. }
  1572. }
  1573. return "";
  1574. }
  1575. std::string cmGeneratorTarget::GetInstallNameDirForInstallTree(
  1576. std::string const& config, std::string const& installPrefix) const
  1577. {
  1578. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1579. std::string dir;
  1580. cmValue install_name_dir = this->GetProperty("INSTALL_NAME_DIR");
  1581. if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_INSTALL)) {
  1582. if (cmNonempty(install_name_dir)) {
  1583. dir = *install_name_dir;
  1584. cmGeneratorExpression::ReplaceInstallPrefix(dir, installPrefix);
  1585. dir =
  1586. cmGeneratorExpression::Evaluate(dir, this->LocalGenerator, config);
  1587. if (!dir.empty()) {
  1588. dir = cmStrCat(dir, '/');
  1589. }
  1590. }
  1591. }
  1592. if (!install_name_dir) {
  1593. if (this->MacOSXRpathInstallNameDirDefault()) {
  1594. dir = "@rpath/";
  1595. }
  1596. }
  1597. return dir;
  1598. }
  1599. return "";
  1600. }
  1601. cmListFileBacktrace cmGeneratorTarget::GetBacktrace() const
  1602. {
  1603. return this->Target->GetBacktrace();
  1604. }
  1605. std::set<BT<std::pair<std::string, bool>>> const&
  1606. cmGeneratorTarget::GetUtilities() const
  1607. {
  1608. return this->Target->GetUtilities();
  1609. }
  1610. bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const
  1611. {
  1612. return this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  1613. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1614. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1615. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  1616. this->GetType() == cmStateEnums::EXECUTABLE;
  1617. }
  1618. std::string const* cmGeneratorTarget::GetExportMacro() const
  1619. {
  1620. // Define the symbol for targets that export symbols.
  1621. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1622. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1623. this->IsExecutableWithExports()) {
  1624. if (cmValue custom_export_name = this->GetProperty("DEFINE_SYMBOL")) {
  1625. this->ExportMacro = *custom_export_name;
  1626. } else {
  1627. std::string in = cmStrCat(this->GetName(), "_EXPORTS");
  1628. this->ExportMacro = cmSystemTools::MakeCidentifier(in);
  1629. }
  1630. return &this->ExportMacro;
  1631. }
  1632. return nullptr;
  1633. }
  1634. cmList const& cmGeneratorTarget::GetSharedLibraryCompileDefs(
  1635. std::string const& config) const
  1636. {
  1637. {
  1638. auto it = this->SharedLibraryCompileDefs.find(config);
  1639. if (it != this->SharedLibraryCompileDefs.end()) {
  1640. return it->second;
  1641. }
  1642. }
  1643. auto emplaceResult =
  1644. this->SharedLibraryCompileDefs.emplace(config, cmList{});
  1645. auto& defs = emplaceResult.first->second;
  1646. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1647. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1648. return defs;
  1649. }
  1650. if (this->GetPolicyStatusCMP0203() != cmPolicies::NEW) {
  1651. return defs;
  1652. }
  1653. auto linkerLang = this->GetLinkerLanguage(config);
  1654. auto definitionVar =
  1655. cmStrCat("CMAKE_", linkerLang, "_SHARED_LIBRARY_COMPILE_DEFINITIONS");
  1656. defs = this->Makefile->GetSafeDefinition(definitionVar);
  1657. return defs;
  1658. }
  1659. cmGeneratorTarget::NameComponents const&
  1660. cmGeneratorTarget::GetFullNameComponents(
  1661. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1662. {
  1663. return this->GetFullNameInternalComponents(config, artifact);
  1664. }
  1665. std::string cmGeneratorTarget::BuildBundleDirectory(
  1666. std::string const& base, std::string const& config,
  1667. BundleDirectoryLevel level) const
  1668. {
  1669. std::string fpath = base;
  1670. if (this->IsAppBundleOnApple()) {
  1671. fpath += this->GetAppBundleDirectory(config, level);
  1672. }
  1673. if (this->IsFrameworkOnApple()) {
  1674. fpath += this->GetFrameworkDirectory(config, level);
  1675. }
  1676. if (this->IsCFBundleOnApple()) {
  1677. fpath += this->GetCFBundleDirectory(config, level);
  1678. }
  1679. return fpath;
  1680. }
  1681. std::string cmGeneratorTarget::GetMacContentDirectory(
  1682. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1683. {
  1684. // Start with the output directory for the target.
  1685. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  1686. BundleDirectoryLevel level = ContentLevel;
  1687. if (this->IsFrameworkOnApple()) {
  1688. // additional files with a framework go into the version specific
  1689. // directory
  1690. level = FullLevel;
  1691. }
  1692. fpath = this->BuildBundleDirectory(fpath, config, level);
  1693. return fpath;
  1694. }
  1695. std::string cmGeneratorTarget::GetEffectiveFolderName() const
  1696. {
  1697. std::string effectiveFolder;
  1698. if (!this->GlobalGenerator->UseFolderProperty()) {
  1699. return effectiveFolder;
  1700. }
  1701. cmValue targetFolder = this->GetProperty("FOLDER");
  1702. if (targetFolder) {
  1703. effectiveFolder += *targetFolder;
  1704. }
  1705. return effectiveFolder;
  1706. }
  1707. cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
  1708. std::string const& config) const
  1709. {
  1710. // There is no compile information for imported targets.
  1711. if (this->IsImported()) {
  1712. return nullptr;
  1713. }
  1714. if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  1715. std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ",
  1716. this->GetName(), " which has type ",
  1717. cmState::GetTargetTypeName(this->GetType()));
  1718. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  1719. return nullptr;
  1720. }
  1721. // Lookup/compute/cache the compile information for this configuration.
  1722. std::string config_upper;
  1723. if (!config.empty()) {
  1724. config_upper = cmSystemTools::UpperCase(config);
  1725. }
  1726. auto i = this->CompileInfoMap.find(config_upper);
  1727. if (i == this->CompileInfoMap.end()) {
  1728. CompileInfo info;
  1729. this->ComputePDBOutputDir("COMPILE_PDB", config, info.CompilePdbDir);
  1730. CompileInfoMapType::value_type entry(config_upper, info);
  1731. i = this->CompileInfoMap.insert(entry).first;
  1732. }
  1733. return &i->second;
  1734. }
  1735. cmGeneratorTarget::ModuleDefinitionInfo const*
  1736. cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
  1737. {
  1738. // A module definition file only makes sense on certain target types.
  1739. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1740. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1741. !this->IsExecutableWithExports()) {
  1742. return nullptr;
  1743. }
  1744. // Lookup/compute/cache the compile information for this configuration.
  1745. std::string config_upper;
  1746. if (!config.empty()) {
  1747. config_upper = cmSystemTools::UpperCase(config);
  1748. }
  1749. auto i = this->ModuleDefinitionInfoMap.find(config_upper);
  1750. if (i == this->ModuleDefinitionInfoMap.end()) {
  1751. ModuleDefinitionInfo info;
  1752. this->ComputeModuleDefinitionInfo(config, info);
  1753. ModuleDefinitionInfoMapType::value_type entry(config_upper, info);
  1754. i = this->ModuleDefinitionInfoMap.insert(entry).first;
  1755. }
  1756. return &i->second;
  1757. }
  1758. void cmGeneratorTarget::ComputeModuleDefinitionInfo(
  1759. std::string const& config, ModuleDefinitionInfo& info) const
  1760. {
  1761. this->GetModuleDefinitionSources(info.Sources, config);
  1762. info.WindowsExportAllSymbols =
  1763. this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  1764. this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS");
  1765. #if !defined(CMAKE_BOOTSTRAP)
  1766. info.DefFileGenerated =
  1767. info.WindowsExportAllSymbols || info.Sources.size() > 1;
  1768. #else
  1769. // Our __create_def helper is not available during CMake bootstrap.
  1770. info.DefFileGenerated = false;
  1771. #endif
  1772. if (info.DefFileGenerated) {
  1773. info.DefFile =
  1774. this->GetObjectDirectory(config) /* has slash */ + "exports.def";
  1775. } else if (!info.Sources.empty()) {
  1776. info.DefFile = info.Sources.front()->GetFullPath();
  1777. }
  1778. }
  1779. bool cmGeneratorTarget::IsAIX() const
  1780. {
  1781. return this->Target->IsAIX();
  1782. }
  1783. bool cmGeneratorTarget::IsApple() const
  1784. {
  1785. return this->Target->IsApple();
  1786. }
  1787. bool cmGeneratorTarget::IsDLLPlatform() const
  1788. {
  1789. return this->Target->IsDLLPlatform();
  1790. }
  1791. void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
  1792. std::string const& config) const
  1793. {
  1794. char const* prop =
  1795. this->GetLinkInterfaceDependentStringProperty("AUTOUIC_OPTIONS", config);
  1796. if (!prop) {
  1797. return;
  1798. }
  1799. cm::GenEx::Context context(this->LocalGenerator, config);
  1800. cmGeneratorExpressionDAGChecker dagChecker{
  1801. this, "AUTOUIC_OPTIONS", nullptr, nullptr, context,
  1802. };
  1803. cmExpandList(cmGeneratorExpression::Evaluate(
  1804. prop, context.LG, context.Config, this, &dagChecker),
  1805. result);
  1806. }
  1807. void cmGeneratorTarget::TraceDependencies()
  1808. {
  1809. // CMake-generated targets have no dependencies to trace. Normally tracing
  1810. // would find nothing anyway, but when building CMake itself the "install"
  1811. // target command ends up referencing the "cmake" target but we do not
  1812. // really want the dependency because "install" depend on "all" anyway.
  1813. if (this->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1814. return;
  1815. }
  1816. // Use a helper object to trace the dependencies.
  1817. cmTargetTraceDependencies tracer(this);
  1818. tracer.Trace();
  1819. }
  1820. std::string cmGeneratorTarget::GetCompilePDBDirectory(
  1821. std::string const& config) const
  1822. {
  1823. if (CompileInfo const* info = this->GetCompileInfo(config)) {
  1824. return info->CompilePdbDir;
  1825. }
  1826. return "";
  1827. }
  1828. std::vector<std::string> cmGeneratorTarget::GetAppleArchs(
  1829. std::string const& config, cm::optional<std::string> lang) const
  1830. {
  1831. cmList archList;
  1832. if (!this->IsApple()) {
  1833. return std::move(archList.data());
  1834. }
  1835. cmValue archs = nullptr;
  1836. if (!config.empty()) {
  1837. std::string defVarName =
  1838. cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config));
  1839. archs = this->GetProperty(defVarName);
  1840. }
  1841. if (!archs) {
  1842. archs = this->GetProperty("OSX_ARCHITECTURES");
  1843. }
  1844. if (archs) {
  1845. archList.assign(*archs);
  1846. }
  1847. if (archList.empty() &&
  1848. // Fall back to a default architecture if no compiler target is set.
  1849. (!lang ||
  1850. this->Makefile
  1851. ->GetDefinition(cmStrCat("CMAKE_", *lang, "_COMPILER_TARGET"))
  1852. .IsEmpty())) {
  1853. archList.assign(
  1854. this->Makefile->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  1855. }
  1856. return std::move(archList.data());
  1857. }
  1858. namespace {
  1859. bool IsSupportedClassifiedFlagsLanguage(std::string const& lang)
  1860. {
  1861. return lang == "CXX"_s;
  1862. }
  1863. bool CanUseCompilerLauncher(std::string const& lang)
  1864. {
  1865. // Also found in `cmCommonTargetGenerator::GetCompilerLauncher`.
  1866. return lang == "C"_s || lang == "CXX"_s || lang == "Fortran"_s ||
  1867. lang == "CUDA"_s || lang == "HIP"_s || lang == "ISPC"_s ||
  1868. lang == "OBJC"_s || lang == "OBJCXX"_s;
  1869. }
  1870. // FIXME: return a vector of `cm::string_view` instead to avoid lots of tiny
  1871. // allocations.
  1872. std::vector<std::string> SplitFlags(std::string const& flags)
  1873. {
  1874. std::vector<std::string> options;
  1875. #ifdef _WIN32
  1876. cmSystemTools::ParseWindowsCommandLine(flags.c_str(), options);
  1877. #else
  1878. cmSystemTools::ParseUnixCommandLine(flags.c_str(), options);
  1879. #endif
  1880. return options;
  1881. }
  1882. }
  1883. cmGeneratorTarget::ClassifiedFlags
  1884. cmGeneratorTarget::GetClassifiedFlagsForSource(cmSourceFile const* sf,
  1885. std::string const& config)
  1886. {
  1887. auto& sourceFlagsCache = this->Configs[config].SourceFlags;
  1888. auto cacheEntry = sourceFlagsCache.lower_bound(sf);
  1889. if (cacheEntry != sourceFlagsCache.end() && cacheEntry->first == sf) {
  1890. return cacheEntry->second;
  1891. }
  1892. ClassifiedFlags flags;
  1893. std::string const& lang = sf->GetLanguage();
  1894. if (!IsSupportedClassifiedFlagsLanguage(lang)) {
  1895. return flags;
  1896. }
  1897. auto* const lg = this->GetLocalGenerator();
  1898. auto const* const mf = this->Makefile;
  1899. // Compute the compiler launcher flags.
  1900. if (CanUseCompilerLauncher(lang)) {
  1901. // Compiler launchers are all execution flags and should not be relevant to
  1902. // the actual compilation.
  1903. FlagClassification cls = FlagClassification::ExecutionFlag;
  1904. FlagKind kind = FlagKind::NotAFlag;
  1905. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  1906. cmValue clauncher = this->GetProperty(clauncher_prop);
  1907. std::string const evaluatedClauncher = cmGeneratorExpression::Evaluate(
  1908. *clauncher, lg, config, this, nullptr, this, lang);
  1909. for (auto const& flag : SplitFlags(evaluatedClauncher)) {
  1910. flags.emplace_back(cls, kind, flag);
  1911. }
  1912. }
  1913. ClassifiedFlags define_flags;
  1914. ClassifiedFlags include_flags;
  1915. ClassifiedFlags compile_flags;
  1916. SourceVariables sfVars = this->GetSourceVariables(sf, config);
  1917. // Compute language flags.
  1918. {
  1919. FlagClassification cls = FlagClassification::BaselineFlag;
  1920. FlagKind kind = FlagKind::Compile;
  1921. std::string mfFlags;
  1922. // Explicitly add the explicit language flag before any other flag
  1923. // so user flags can override it.
  1924. this->AddExplicitLanguageFlags(mfFlags, *sf);
  1925. for (auto const& flag : SplitFlags(mfFlags)) {
  1926. flags.emplace_back(cls, kind, flag);
  1927. }
  1928. }
  1929. std::unordered_map<std::string, std::string> pchSources;
  1930. std::string filterArch;
  1931. {
  1932. std::vector<std::string> pchArchs = this->GetPchArchs(config, lang);
  1933. for (std::string const& arch : pchArchs) {
  1934. std::string const pchSource = this->GetPchSource(config, lang, arch);
  1935. if (pchSource == sf->GetFullPath()) {
  1936. filterArch = arch;
  1937. }
  1938. if (!pchSource.empty()) {
  1939. pchSources.insert(std::make_pair(pchSource, arch));
  1940. }
  1941. }
  1942. }
  1943. // Compute target-wide flags.
  1944. {
  1945. FlagClassification cls = FlagClassification::BaselineFlag;
  1946. // Compile flags
  1947. {
  1948. FlagKind kind = FlagKind::Compile;
  1949. std::string targetFlags;
  1950. lg->GetTargetCompileFlags(this, config, lang, targetFlags, filterArch);
  1951. for (auto&& flag : SplitFlags(targetFlags)) {
  1952. compile_flags.emplace_back(cls, kind, std::move(flag));
  1953. }
  1954. }
  1955. // Define flags
  1956. {
  1957. FlagKind kind = FlagKind::Definition;
  1958. std::set<std::string> defines;
  1959. lg->GetTargetDefines(this, config, lang, defines);
  1960. std::string defineFlags;
  1961. lg->JoinDefines(defines, defineFlags, lang);
  1962. for (auto&& flag : SplitFlags(defineFlags)) {
  1963. define_flags.emplace_back(cls, kind, std::move(flag));
  1964. }
  1965. }
  1966. // Include flags
  1967. {
  1968. FlagKind kind = FlagKind::Include;
  1969. std::vector<std::string> includes;
  1970. lg->GetIncludeDirectories(includes, this, lang, config);
  1971. auto includeFlags =
  1972. lg->GetIncludeFlags(includes, this, lang, config, false);
  1973. for (auto&& flag : SplitFlags(includeFlags)) {
  1974. include_flags.emplace_back(cls, kind, std::move(flag));
  1975. }
  1976. }
  1977. }
  1978. std::string const COMPILE_FLAGS("COMPILE_FLAGS");
  1979. std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
  1980. cmGeneratorExpressionInterpreter genexInterpreter(lg, config, this, lang);
  1981. // Source-specific flags.
  1982. {
  1983. FlagClassification cls = FlagClassification::PrivateFlag;
  1984. FlagKind kind = FlagKind::Compile;
  1985. std::string sourceFlags;
  1986. if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
  1987. lg->AppendFlags(sourceFlags,
  1988. genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  1989. }
  1990. if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  1991. lg->AppendCompileOptions(
  1992. sourceFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  1993. }
  1994. for (auto&& flag : SplitFlags(sourceFlags)) {
  1995. compile_flags.emplace_back(cls, kind, std::move(flag));
  1996. }
  1997. // Dependency tracking flags.
  1998. {
  1999. if (!sfVars.DependencyFlags.empty()) {
  2000. cmRulePlaceholderExpander::RuleVariables vars;
  2001. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2002. vars.DependencyFile = sfVars.DependencyFile.c_str();
  2003. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  2004. std::string depfileFlags = sfVars.DependencyFlags;
  2005. rulePlaceholderExpander->ExpandRuleVariables(lg, depfileFlags, vars);
  2006. for (auto&& flag : SplitFlags(depfileFlags)) {
  2007. compile_flags.emplace_back(FlagClassification::LocationFlag,
  2008. FlagKind::BuildSystem, std::move(flag));
  2009. }
  2010. }
  2011. }
  2012. }
  2013. // Precompiled headers.
  2014. {
  2015. FlagClassification cls = FlagClassification::PrivateFlag;
  2016. FlagKind kind = FlagKind::Compile;
  2017. std::string pchFlags;
  2018. // Add precompile headers compile options.
  2019. if (!sf->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2020. if (!pchSources.empty()) {
  2021. std::string pchOptions;
  2022. auto pchIt = pchSources.find(sf->GetFullPath());
  2023. if (pchIt != pchSources.end()) {
  2024. pchOptions =
  2025. this->GetPchCreateCompileOptions(config, lang, pchIt->second);
  2026. } else {
  2027. pchOptions = this->GetPchUseCompileOptions(config, lang);
  2028. }
  2029. this->LocalGenerator->AppendCompileOptions(
  2030. pchFlags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  2031. }
  2032. }
  2033. for (auto&& flag : SplitFlags(pchFlags)) {
  2034. compile_flags.emplace_back(cls, kind, std::move(flag));
  2035. }
  2036. }
  2037. // C++ module flags.
  2038. if (lang == "CXX"_s) {
  2039. FlagClassification cls = FlagClassification::LocationFlag;
  2040. FlagKind kind = FlagKind::BuildSystem;
  2041. std::string bmiFlags;
  2042. auto const* fs = this->GetFileSetForSource(config, sf);
  2043. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2044. if (lang != "CXX"_s) {
  2045. mf->IssueMessage(
  2046. MessageType::FATAL_ERROR,
  2047. cmStrCat(
  2048. "Target \"", this->Target->GetName(), "\" contains the source\n ",
  2049. sf->GetFullPath(), "\nin a file set of type \"", fs->GetType(),
  2050. R"(" but the source is not classified as a "CXX" source.)"));
  2051. }
  2052. if (!this->Target->IsNormal()) {
  2053. auto flag = mf->GetSafeDefinition("CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  2054. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2055. compileObjectVars.Object = sfVars.ObjectFileDir.c_str();
  2056. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2057. rulePlaceholderExpander->ExpandRuleVariables(lg, flag,
  2058. compileObjectVars);
  2059. lg->AppendCompileOptions(bmiFlags, flag);
  2060. }
  2061. }
  2062. for (auto&& flag : SplitFlags(bmiFlags)) {
  2063. compile_flags.emplace_back(cls, kind, std::move(flag));
  2064. }
  2065. }
  2066. cmRulePlaceholderExpander::RuleVariables vars;
  2067. vars.CMTargetName = this->GetName().c_str();
  2068. vars.CMTargetType = cmState::GetTargetTypeName(this->GetType()).c_str();
  2069. vars.Language = lang.c_str();
  2070. auto const sfPath = this->LocalGenerator->ConvertToOutputFormat(
  2071. sf->GetFullPath(), cmOutputConverter::SHELL);
  2072. // Compute the base compiler command line. We'll find placeholders and
  2073. // replace them with arguments later in this function.
  2074. {
  2075. FlagClassification cls = FlagClassification::ExecutionFlag;
  2076. FlagKind kind = FlagKind::NotAFlag;
  2077. std::string const cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  2078. std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
  2079. cmList compileCmds(compileCmd); // FIXME: which command to use?
  2080. std::string& cmd = compileCmds[0];
  2081. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2082. static std::string const PlaceholderDefines = "__CMAKE_DEFINES";
  2083. static std::string const PlaceholderIncludes = "__CMAKE_INCLUDES";
  2084. static std::string const PlaceholderFlags = "__CMAKE_FLAGS";
  2085. static std::string const PlaceholderSource = "__CMAKE_SOURCE";
  2086. vars.Defines = PlaceholderDefines.c_str();
  2087. vars.Includes = PlaceholderIncludes.c_str();
  2088. vars.TargetPDB = sfVars.TargetPDB.c_str();
  2089. vars.TargetCompilePDB = sfVars.TargetCompilePDB.c_str();
  2090. vars.Object = sfVars.ObjectFileDir.c_str();
  2091. vars.ObjectDir = sfVars.ObjectDir.c_str();
  2092. vars.ObjectFileDir = sfVars.ObjectFileDir.c_str();
  2093. vars.TargetSupportDir = sfVars.TargetSupportDir.c_str();
  2094. vars.Flags = PlaceholderFlags.c_str();
  2095. vars.DependencyFile = sfVars.DependencyFile.c_str();
  2096. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  2097. vars.Source = PlaceholderSource.c_str();
  2098. rulePlaceholderExpander->ExpandRuleVariables(lg, cmd, vars);
  2099. for (auto&& flag : SplitFlags(cmd)) {
  2100. if (flag == PlaceholderDefines) {
  2101. flags.insert(flags.end(), define_flags.begin(), define_flags.end());
  2102. } else if (flag == PlaceholderIncludes) {
  2103. flags.insert(flags.end(), include_flags.begin(), include_flags.end());
  2104. } else if (flag == PlaceholderFlags) {
  2105. flags.insert(flags.end(), compile_flags.begin(), compile_flags.end());
  2106. } else if (flag == PlaceholderSource) {
  2107. flags.emplace_back(FlagClassification::LocationFlag,
  2108. FlagKind::BuildSystem, sfPath);
  2109. } else {
  2110. flags.emplace_back(cls, kind, std::move(flag));
  2111. // All remaining flags here are build system flags.
  2112. kind = FlagKind::BuildSystem;
  2113. }
  2114. }
  2115. }
  2116. cacheEntry = sourceFlagsCache.emplace_hint(cacheEntry, sf, std::move(flags));
  2117. return cacheEntry->second;
  2118. }
  2119. cmGeneratorTarget::SourceVariables cmGeneratorTarget::GetSourceVariables(
  2120. cmSourceFile const* sf, std::string const& config)
  2121. {
  2122. SourceVariables vars;
  2123. auto const language = sf->GetLanguage();
  2124. auto const targetType = this->GetType();
  2125. auto const* const lg = this->GetLocalGenerator();
  2126. auto const* const gg = this->GetGlobalGenerator();
  2127. auto const* const mf = this->Makefile;
  2128. // PDB settings.
  2129. {
  2130. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  2131. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  2132. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  2133. std::string pdbPath;
  2134. std::string compilePdbPath;
  2135. if (targetType <= cmStateEnums::OBJECT_LIBRARY) {
  2136. compilePdbPath = this->GetCompilePDBPath(config);
  2137. if (compilePdbPath.empty()) {
  2138. // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
  2139. // A trailing slash tells the toolchain to add its default file name.
  2140. compilePdbPath = this->GetSupportDirectory();
  2141. if (gg->IsMultiConfig()) {
  2142. compilePdbPath = cmStrCat(compilePdbPath, '/', config);
  2143. }
  2144. compilePdbPath += '/';
  2145. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  2146. // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
  2147. compilePdbPath = cmStrCat(compilePdbPath, this->GetName(), ".pdb");
  2148. }
  2149. }
  2150. }
  2151. if (targetType == cmStateEnums::EXECUTABLE ||
  2152. targetType == cmStateEnums::STATIC_LIBRARY ||
  2153. targetType == cmStateEnums::SHARED_LIBRARY ||
  2154. targetType == cmStateEnums::MODULE_LIBRARY) {
  2155. pdbPath = cmStrCat(this->GetPDBDirectory(config), '/',
  2156. this->GetPDBName(config));
  2157. }
  2158. vars.TargetPDB = lg->ConvertToOutputFormat(
  2159. gg->ConvertToOutputPath(std::move(pdbPath)), cmOutputConverter::SHELL);
  2160. vars.TargetCompilePDB = lg->ConvertToOutputFormat(
  2161. gg->ConvertToOutputPath(std::move(compilePdbPath)),
  2162. cmOutputConverter::SHELL);
  2163. }
  2164. }
  2165. // Object settings.
  2166. {
  2167. std::string const targetSupportDir = lg->MaybeRelativeToTopBinDir(
  2168. gg->ConvertToOutputPath(this->GetCMFSupportDirectory()));
  2169. std::string const objectDir = gg->ConvertToOutputPath(
  2170. cmStrCat(this->GetSupportDirectory(), gg->GetConfigDirectory(config)));
  2171. std::string const objectFileName = this->GetObjectName(sf);
  2172. std::string const objectFilePath =
  2173. cmStrCat(objectDir, '/', objectFileName);
  2174. vars.TargetSupportDir =
  2175. lg->ConvertToOutputFormat(targetSupportDir, cmOutputConverter::SHELL);
  2176. vars.ObjectDir =
  2177. lg->ConvertToOutputFormat(objectDir, cmOutputConverter::SHELL);
  2178. vars.ObjectFileDir =
  2179. lg->ConvertToOutputFormat(objectFilePath, cmOutputConverter::SHELL);
  2180. // Dependency settings.
  2181. {
  2182. std::string const depfileFormatName =
  2183. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT");
  2184. std::string const depfileFormat =
  2185. mf->GetSafeDefinition(depfileFormatName);
  2186. if (depfileFormat != "msvc"_s) {
  2187. std::string const flagsName =
  2188. cmStrCat("CMAKE_DEPFILE_FLAGS_", language);
  2189. std::string const depfileFlags = mf->GetSafeDefinition(flagsName);
  2190. if (!depfileFlags.empty()) {
  2191. bool replaceExt = false;
  2192. if (!language.empty()) {
  2193. std::string const repVar =
  2194. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  2195. replaceExt = mf->IsOn(repVar);
  2196. }
  2197. std::string const depfilePath = cmStrCat(
  2198. objectDir, '/',
  2199. replaceExt
  2200. ? cmSystemTools::GetFilenameWithoutLastExtension(objectFileName)
  2201. : objectFileName,
  2202. ".d");
  2203. vars.DependencyFlags = depfileFlags;
  2204. vars.DependencyTarget = vars.ObjectFileDir;
  2205. vars.DependencyFile =
  2206. lg->ConvertToOutputFormat(depfilePath, cmOutputConverter::SHELL);
  2207. }
  2208. }
  2209. }
  2210. }
  2211. return vars;
  2212. }
  2213. void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
  2214. cmSourceFile const& sf) const
  2215. {
  2216. cmValue lang = sf.GetProperty("LANGUAGE");
  2217. if (!lang) {
  2218. return;
  2219. }
  2220. switch (this->GetPolicyStatusCMP0119()) {
  2221. case cmPolicies::WARN:
  2222. CM_FALLTHROUGH;
  2223. case cmPolicies::OLD:
  2224. // The OLD behavior is to not add explicit language flags.
  2225. return;
  2226. case cmPolicies::NEW:
  2227. // The NEW behavior is to add explicit language flags.
  2228. break;
  2229. }
  2230. this->LocalGenerator->AppendFeatureOptions(flags, *lang,
  2231. "EXPLICIT_LANGUAGE");
  2232. }
  2233. void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
  2234. std::string const& config,
  2235. std::string& flags) const
  2236. {
  2237. std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
  2238. if (arch.empty()) {
  2239. switch (this->GetPolicyStatusCMP0104()) {
  2240. case cmPolicies::WARN:
  2241. if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
  2242. this->Makefile->IssueMessage(
  2243. MessageType::AUTHOR_WARNING,
  2244. cmPolicies::GetPolicyWarning(cmPolicies::CMP0104) +
  2245. "\nCUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2246. "\".");
  2247. }
  2248. CM_FALLTHROUGH;
  2249. case cmPolicies::OLD:
  2250. break;
  2251. default:
  2252. this->Makefile->IssueMessage(
  2253. MessageType::FATAL_ERROR,
  2254. "CUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2255. "\".");
  2256. }
  2257. }
  2258. // If CUDA_ARCHITECTURES is false we don't add any architectures.
  2259. if (cmIsOff(arch)) {
  2260. return;
  2261. }
  2262. this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
  2263. std::move(arch), flags);
  2264. }
  2265. void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
  2266. std::string const& config,
  2267. std::string const& lang,
  2268. std::string arch,
  2269. std::string& flags) const
  2270. {
  2271. std::string const& compiler = this->Makefile->GetSafeDefinition(
  2272. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2273. bool const ipoEnabled = this->IsIPOEnabled(lang, config);
  2274. // Check for special modes: `all`, `all-major`.
  2275. if (arch == "all" || arch == "all-major") {
  2276. if (compiler == "NVIDIA" &&
  2277. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2278. this->Makefile->GetDefinition(cmStrCat(
  2279. "CMAKE_", lang, "_COMPILER_VERSION")),
  2280. "11.5")) {
  2281. flags = cmStrCat(flags, " -arch=", arch);
  2282. return;
  2283. }
  2284. if (arch == "all") {
  2285. arch = *this->Makefile->GetDefinition(
  2286. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
  2287. } else if (arch == "all-major") {
  2288. arch = *this->Makefile->GetDefinition(
  2289. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
  2290. }
  2291. } else if (arch == "native") {
  2292. cmValue native = this->Makefile->GetDefinition(
  2293. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
  2294. if (native.IsEmpty()) {
  2295. this->Makefile->IssueMessage(
  2296. MessageType::FATAL_ERROR,
  2297. cmStrCat(lang,
  2298. "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
  2299. "detected."));
  2300. }
  2301. if (compiler == "NVIDIA" &&
  2302. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2303. this->Makefile->GetDefinition(cmStrCat(
  2304. "CMAKE_", lang, "_COMPILER_VERSION")),
  2305. "11.6")) {
  2306. flags = cmStrCat(flags, " -arch=", arch);
  2307. return;
  2308. }
  2309. arch = *native;
  2310. }
  2311. struct CudaArchitecture
  2312. {
  2313. std::string name;
  2314. bool real{ true };
  2315. bool virtual_{ true };
  2316. };
  2317. std::vector<CudaArchitecture> architectures;
  2318. {
  2319. cmList options(arch);
  2320. for (auto& option : options) {
  2321. CudaArchitecture architecture;
  2322. // Architecture name is up to the first specifier.
  2323. std::size_t pos = option.find_first_of('-');
  2324. architecture.name = option.substr(0, pos);
  2325. if (pos != std::string::npos) {
  2326. cm::string_view specifier{ option.c_str() + pos + 1,
  2327. option.length() - pos - 1 };
  2328. if (specifier == "real") {
  2329. architecture.real = true;
  2330. architecture.virtual_ = false;
  2331. } else if (specifier == "virtual") {
  2332. architecture.real = false;
  2333. architecture.virtual_ = true;
  2334. } else {
  2335. this->Makefile->IssueMessage(
  2336. MessageType::FATAL_ERROR,
  2337. "Unknown CUDA architecture specifier \"" + std::string(specifier) +
  2338. "\".");
  2339. }
  2340. }
  2341. architectures.emplace_back(architecture);
  2342. }
  2343. }
  2344. if (compiler == "NVIDIA") {
  2345. if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
  2346. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  2347. cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
  2348. flags += *cudaIPOFlags;
  2349. }
  2350. }
  2351. for (CudaArchitecture& architecture : architectures) {
  2352. flags +=
  2353. " \"--generate-code=arch=compute_" + architecture.name + ",code=[";
  2354. if (architecture.virtual_) {
  2355. flags += "compute_" + architecture.name;
  2356. if (ipoEnabled || architecture.real) {
  2357. flags += ",";
  2358. }
  2359. }
  2360. if (ipoEnabled) {
  2361. if (compileOrLink == cmBuildStep::Compile) {
  2362. flags += "lto_" + architecture.name;
  2363. } else if (compileOrLink == cmBuildStep::Link) {
  2364. flags += "sm_" + architecture.name;
  2365. }
  2366. } else if (architecture.real) {
  2367. flags += "sm_" + architecture.name;
  2368. }
  2369. flags += "]\"";
  2370. }
  2371. } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
  2372. for (CudaArchitecture& architecture : architectures) {
  2373. flags += " --cuda-gpu-arch=sm_" + architecture.name;
  2374. if (!architecture.real) {
  2375. this->Makefile->IssueMessage(
  2376. MessageType::WARNING,
  2377. "Clang doesn't support disabling CUDA real code generation.");
  2378. }
  2379. if (!architecture.virtual_) {
  2380. flags += " --no-cuda-include-ptx=sm_" + architecture.name;
  2381. }
  2382. }
  2383. }
  2384. }
  2385. void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
  2386. {
  2387. std::string const& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  2388. // If ISPC_TARGET is false we don't add any architectures.
  2389. if (cmIsOff(arch)) {
  2390. return;
  2391. }
  2392. std::string const& compiler =
  2393. this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
  2394. if (compiler == "Intel") {
  2395. cmList targets(arch);
  2396. if (!targets.empty()) {
  2397. flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
  2398. }
  2399. }
  2400. }
  2401. void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
  2402. std::string const& config,
  2403. std::string& flags) const
  2404. {
  2405. std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
  2406. if (arch.empty()) {
  2407. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  2408. "HIP_ARCHITECTURES is empty for target \"" +
  2409. this->GetName() + "\".");
  2410. }
  2411. // If HIP_ARCHITECTURES is false we don't add any architectures.
  2412. if (cmIsOff(arch)) {
  2413. return;
  2414. }
  2415. if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
  2416. this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
  2417. std::move(arch), flags);
  2418. return;
  2419. }
  2420. cmList options(arch);
  2421. for (std::string& option : options) {
  2422. flags += " --offload-arch=" + option;
  2423. }
  2424. }
  2425. void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
  2426. {
  2427. std::string const& compiler =
  2428. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  2429. if (compiler == "Clang") {
  2430. // Pass CUDA toolkit explicitly to Clang.
  2431. // Clang's searching for the system CUDA toolkit isn't very good and it's
  2432. // expected the user will explicitly pass the toolkit path.
  2433. // This also avoids Clang having to search for the toolkit on every
  2434. // invocation.
  2435. std::string toolkitRoot =
  2436. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
  2437. if (!toolkitRoot.empty()) {
  2438. flags += " --cuda-path=" +
  2439. this->LocalGenerator->ConvertToOutputFormat(toolkitRoot,
  2440. cmOutputConverter::SHELL);
  2441. }
  2442. }
  2443. }
  2444. //----------------------------------------------------------------------------
  2445. std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
  2446. std::string const& var, std::string const& lang,
  2447. std::string const& config) const
  2448. {
  2449. if (this->IsIPOEnabled(lang, config)) {
  2450. std::string varIPO = var + "_IPO";
  2451. if (this->Makefile->IsDefinitionSet(varIPO)) {
  2452. return varIPO;
  2453. }
  2454. }
  2455. return var;
  2456. }
  2457. //----------------------------------------------------------------------------
  2458. std::string cmGeneratorTarget::GetCreateRuleVariable(
  2459. std::string const& lang, std::string const& config) const
  2460. {
  2461. switch (this->GetType()) {
  2462. case cmStateEnums::STATIC_LIBRARY: {
  2463. std::string var = "CMAKE_" + lang + "_CREATE_STATIC_LIBRARY";
  2464. return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
  2465. }
  2466. case cmStateEnums::SHARED_LIBRARY:
  2467. if (this->IsArchivedAIXSharedLibrary()) {
  2468. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY_ARCHIVE";
  2469. }
  2470. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY";
  2471. case cmStateEnums::MODULE_LIBRARY:
  2472. return "CMAKE_" + lang + "_CREATE_SHARED_MODULE";
  2473. case cmStateEnums::EXECUTABLE:
  2474. if (this->IsExecutableWithExports()) {
  2475. std::string linkExeWithExports =
  2476. "CMAKE_" + lang + "_LINK_EXECUTABLE_WITH_EXPORTS";
  2477. if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
  2478. return linkExeWithExports;
  2479. }
  2480. }
  2481. return "CMAKE_" + lang + "_LINK_EXECUTABLE";
  2482. default:
  2483. break;
  2484. }
  2485. return "";
  2486. }
  2487. //----------------------------------------------------------------------------
  2488. std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
  2489. std::string const& lang) const
  2490. {
  2491. cmValue val =
  2492. this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
  2493. if (!cmNonempty(val)) {
  2494. return {};
  2495. }
  2496. std::string path = *val;
  2497. if (!cmSystemTools::FileIsFullPath(path)) {
  2498. path =
  2499. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
  2500. }
  2501. return cmSystemTools::CollapseFullPath(path);
  2502. }
  2503. struct CycleWatcher
  2504. {
  2505. CycleWatcher(bool& flag)
  2506. : Flag(flag)
  2507. {
  2508. this->Flag = true;
  2509. }
  2510. ~CycleWatcher() { this->Flag = false; }
  2511. bool& Flag;
  2512. };
  2513. cmGeneratorTarget const* cmGeneratorTarget::GetPchReuseTarget() const
  2514. {
  2515. if (this->ComputingPchReuse) {
  2516. // TODO: Get the full cycle.
  2517. if (!this->PchReuseCycleDetected) {
  2518. this->Makefile->IssueMessage(
  2519. MessageType::FATAL_ERROR,
  2520. cmStrCat("Circular PCH reuse target involving '", this->GetName(),
  2521. '\''));
  2522. }
  2523. this->PchReuseCycleDetected = true;
  2524. return nullptr;
  2525. }
  2526. CycleWatcher watch(this->ComputingPchReuse);
  2527. (void)watch;
  2528. cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2529. if (!pchReuseFrom) {
  2530. return nullptr;
  2531. }
  2532. cmGeneratorTarget const* generatorTarget =
  2533. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2534. if (!generatorTarget) {
  2535. this->Makefile->IssueMessage(
  2536. MessageType::FATAL_ERROR,
  2537. cmStrCat(
  2538. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2539. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
  2540. }
  2541. if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
  2542. this->Makefile->IssueMessage(
  2543. MessageType::FATAL_ERROR,
  2544. cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
  2545. this->GetName(), "\")\n"));
  2546. }
  2547. if (generatorTarget) {
  2548. if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2549. this->Makefile->IssueMessage(
  2550. MessageType::WARNING,
  2551. cmStrCat(
  2552. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2553. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS"; ignoring.)"));
  2554. return nullptr;
  2555. }
  2556. if (auto const* recurseReuseTarget =
  2557. generatorTarget->GetPchReuseTarget()) {
  2558. return recurseReuseTarget;
  2559. }
  2560. }
  2561. return generatorTarget;
  2562. }
  2563. cmGeneratorTarget* cmGeneratorTarget::GetPchReuseTarget()
  2564. {
  2565. if (this->ComputingPchReuse) {
  2566. // TODO: Get the full cycle.
  2567. if (!this->PchReuseCycleDetected) {
  2568. this->Makefile->IssueMessage(
  2569. MessageType::FATAL_ERROR,
  2570. cmStrCat("Circular PCH reuse target involving '", this->GetName(),
  2571. '\''));
  2572. }
  2573. this->PchReuseCycleDetected = true;
  2574. return nullptr;
  2575. }
  2576. CycleWatcher watch(this->ComputingPchReuse);
  2577. (void)watch;
  2578. cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2579. if (!pchReuseFrom) {
  2580. return nullptr;
  2581. }
  2582. cmGeneratorTarget* generatorTarget =
  2583. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2584. if (!generatorTarget) {
  2585. this->Makefile->IssueMessage(
  2586. MessageType::FATAL_ERROR,
  2587. cmStrCat(
  2588. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2589. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
  2590. }
  2591. if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
  2592. this->Makefile->IssueMessage(
  2593. MessageType::FATAL_ERROR,
  2594. cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
  2595. this->GetName(), "\")\n"));
  2596. }
  2597. if (generatorTarget) {
  2598. if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2599. this->Makefile->IssueMessage(
  2600. MessageType::WARNING,
  2601. cmStrCat(
  2602. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2603. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS"; ignoring.)"));
  2604. return nullptr;
  2605. }
  2606. if (auto* recurseReuseTarget = generatorTarget->GetPchReuseTarget()) {
  2607. return recurseReuseTarget;
  2608. }
  2609. }
  2610. return generatorTarget;
  2611. }
  2612. std::vector<std::string> cmGeneratorTarget::GetPchArchs(
  2613. std::string const& config, std::string const& lang) const
  2614. {
  2615. std::vector<std::string> pchArchs;
  2616. if (!this->GetGlobalGenerator()->IsXcode()) {
  2617. pchArchs = this->GetAppleArchs(config, lang);
  2618. }
  2619. if (pchArchs.size() < 2) {
  2620. // We do not need per-arch PCH files when building for one architecture.
  2621. pchArchs = { {} };
  2622. }
  2623. return pchArchs;
  2624. }
  2625. std::string cmGeneratorTarget::GetPchHeader(std::string const& config,
  2626. std::string const& language,
  2627. std::string const& arch) const
  2628. {
  2629. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2630. language != "OBJCXX") {
  2631. return std::string();
  2632. }
  2633. if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2634. return std::string();
  2635. }
  2636. cmGeneratorTarget const* generatorTarget = this;
  2637. cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
  2638. bool const haveReuseTarget = reuseTarget && reuseTarget != this;
  2639. if (reuseTarget) {
  2640. generatorTarget = reuseTarget;
  2641. }
  2642. auto const inserted =
  2643. this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
  2644. if (inserted.second) {
  2645. std::vector<BT<std::string>> const headers =
  2646. this->GetPrecompileHeaders(config, language);
  2647. if (headers.empty() && !haveReuseTarget) {
  2648. return std::string();
  2649. }
  2650. std::string& filename = inserted.first->second;
  2651. std::map<std::string, std::string> const languageToExtension = {
  2652. { "C", ".h" },
  2653. { "CXX", ".hxx" },
  2654. { "OBJC", ".objc.h" },
  2655. { "OBJCXX", ".objcxx.hxx" }
  2656. };
  2657. filename = generatorTarget->GetCMFSupportDirectory();
  2658. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2659. filename = cmStrCat(filename, '/', config);
  2660. }
  2661. // This is acceptable as its the source file, won't have a rename/hash
  2662. filename =
  2663. cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat('_', arch),
  2664. languageToExtension.at(language));
  2665. std::string const filename_tmp = cmStrCat(filename, ".tmp");
  2666. if (!haveReuseTarget) {
  2667. cmValue pchPrologue =
  2668. this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
  2669. cmValue pchEpilogue =
  2670. this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
  2671. std::string firstHeaderOnDisk;
  2672. {
  2673. cmGeneratedFileStream file(
  2674. filename_tmp, false,
  2675. this->GetGlobalGenerator()->GetMakefileEncoding());
  2676. file << "/* generated by CMake */\n\n";
  2677. if (pchPrologue) {
  2678. file << *pchPrologue << "\n";
  2679. }
  2680. if (this->GetGlobalGenerator()->IsXcode()) {
  2681. file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2682. }
  2683. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2684. file << "#ifdef __cplusplus\n";
  2685. }
  2686. for (auto const& header_bt : headers) {
  2687. if (header_bt.Value.empty()) {
  2688. continue;
  2689. }
  2690. if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
  2691. file << "#include " << header_bt.Value << "\n";
  2692. } else {
  2693. file << "#include \"" << header_bt.Value << "\"\n";
  2694. }
  2695. if (cmSystemTools::FileExists(header_bt.Value) &&
  2696. firstHeaderOnDisk.empty()) {
  2697. firstHeaderOnDisk = header_bt.Value;
  2698. }
  2699. }
  2700. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2701. file << "#endif // __cplusplus\n";
  2702. }
  2703. if (this->GetGlobalGenerator()->IsXcode()) {
  2704. file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2705. }
  2706. if (pchEpilogue) {
  2707. file << *pchEpilogue << "\n";
  2708. }
  2709. }
  2710. if (!firstHeaderOnDisk.empty()) {
  2711. cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
  2712. }
  2713. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2714. }
  2715. }
  2716. return inserted.first->second;
  2717. }
  2718. std::string cmGeneratorTarget::GetPchSource(std::string const& config,
  2719. std::string const& language,
  2720. std::string const& arch) const
  2721. {
  2722. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2723. language != "OBJCXX") {
  2724. return std::string();
  2725. }
  2726. auto const inserted =
  2727. this->PchSources.insert(std::make_pair(language + config + arch, ""));
  2728. if (inserted.second) {
  2729. std::string const pchHeader = this->GetPchHeader(config, language, arch);
  2730. if (pchHeader.empty()) {
  2731. return std::string();
  2732. }
  2733. std::string& filename = inserted.first->second;
  2734. cmGeneratorTarget const* generatorTarget = this;
  2735. cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
  2736. bool const haveReuseTarget = reuseTarget && reuseTarget != this;
  2737. if (reuseTarget) {
  2738. generatorTarget = reuseTarget;
  2739. }
  2740. filename =
  2741. cmStrCat(generatorTarget->GetCMFSupportDirectory(), "/cmake_pch");
  2742. // For GCC the source extension will be transformed into .h[xx].gch
  2743. if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2744. std::map<std::string, std::string> const languageToExtension = {
  2745. { "C", ".h.c" },
  2746. { "CXX", ".hxx.cxx" },
  2747. { "OBJC", ".objc.h.m" },
  2748. { "OBJCXX", ".objcxx.hxx.mm" }
  2749. };
  2750. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
  2751. languageToExtension.at(language));
  2752. } else {
  2753. std::map<std::string, std::string> const languageToExtension = {
  2754. { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
  2755. };
  2756. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
  2757. languageToExtension.at(language));
  2758. }
  2759. std::string const filename_tmp = cmStrCat(filename, ".tmp");
  2760. if (!haveReuseTarget) {
  2761. {
  2762. cmGeneratedFileStream file(filename_tmp);
  2763. file << "/* generated by CMake */\n";
  2764. }
  2765. cmFileTimes::Copy(pchHeader, filename_tmp);
  2766. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2767. }
  2768. }
  2769. return inserted.first->second;
  2770. }
  2771. std::string cmGeneratorTarget::GetPchFileObject(std::string const& config,
  2772. std::string const& language,
  2773. std::string const& arch)
  2774. {
  2775. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2776. language != "OBJCXX") {
  2777. return std::string();
  2778. }
  2779. auto const inserted =
  2780. this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
  2781. if (inserted.second) {
  2782. std::string const pchSource = this->GetPchSource(config, language, arch);
  2783. if (pchSource.empty()) {
  2784. return std::string();
  2785. }
  2786. std::string& filename = inserted.first->second;
  2787. auto* pchSf = this->Makefile->GetOrCreateSource(
  2788. pchSource, false, cmSourceFileLocationKind::Known);
  2789. pchSf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::PchSource);
  2790. pchSf->ResolveFullPath();
  2791. filename = cmStrCat(this->GetObjectDirectory(config), '/',
  2792. this->GetObjectName(pchSf));
  2793. }
  2794. return inserted.first->second;
  2795. }
  2796. std::string cmGeneratorTarget::GetPchFile(std::string const& config,
  2797. std::string const& language,
  2798. std::string const& arch)
  2799. {
  2800. auto const inserted =
  2801. this->PchFiles.insert(std::make_pair(language + config + arch, ""));
  2802. if (inserted.second) {
  2803. std::string& pchFile = inserted.first->second;
  2804. std::string const pchExtension =
  2805. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2806. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2807. auto replaceExtension = [](std::string const& str,
  2808. std::string const& ext) -> std::string {
  2809. auto dot_pos = str.rfind('.');
  2810. std::string result;
  2811. if (dot_pos != std::string::npos) {
  2812. result = str.substr(0, dot_pos);
  2813. }
  2814. result += ext;
  2815. return result;
  2816. };
  2817. cmGeneratorTarget* generatorTarget = this;
  2818. cmGeneratorTarget* reuseTarget = this->GetPchReuseTarget();
  2819. if (reuseTarget) {
  2820. generatorTarget = reuseTarget;
  2821. }
  2822. std::string const pchFileObject =
  2823. generatorTarget->GetPchFileObject(config, language, arch);
  2824. if (!pchExtension.empty()) {
  2825. pchFile = replaceExtension(pchFileObject, pchExtension);
  2826. }
  2827. } else {
  2828. if (this->GetUseShortObjectNames() && !pchExtension.empty()) {
  2829. auto pchSource = this->GetPchSource(config, language, arch);
  2830. auto* pchSf = this->Makefile->GetOrCreateSource(
  2831. pchSource, false, cmSourceFileLocationKind::Known);
  2832. pchSf->SetSpecialSourceType(
  2833. cmSourceFile::SpecialSourceType::PchSource);
  2834. pchSf->ResolveFullPath();
  2835. std::string cfgSubdir;
  2836. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2837. cfgSubdir = cmStrCat(config, '/');
  2838. }
  2839. pchFile = cmStrCat(
  2840. this->GetSupportDirectory(), '/', cfgSubdir,
  2841. this->LocalGenerator->GetShortObjectFileName(*pchSf), pchExtension);
  2842. } else {
  2843. pchFile =
  2844. cmStrCat(this->GetPchHeader(config, language, arch), pchExtension);
  2845. }
  2846. }
  2847. }
  2848. return inserted.first->second;
  2849. }
  2850. std::string cmGeneratorTarget::GetPchCreateCompileOptions(
  2851. std::string const& config, std::string const& language,
  2852. std::string const& arch)
  2853. {
  2854. auto const inserted = this->PchCreateCompileOptions.insert(
  2855. std::make_pair(language + config + arch, ""));
  2856. if (inserted.second) {
  2857. std::string& createOptionList = inserted.first->second;
  2858. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2859. createOptionList = this->Makefile->GetSafeDefinition(
  2860. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2861. }
  2862. if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
  2863. std::string varName = cmStrCat(
  2864. "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
  2865. std::string instantiateOption =
  2866. this->Makefile->GetSafeDefinition(varName);
  2867. if (!instantiateOption.empty()) {
  2868. createOptionList = cmStrCat(createOptionList, ';', instantiateOption);
  2869. }
  2870. }
  2871. std::string const createOptVar =
  2872. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
  2873. createOptionList = cmStrCat(
  2874. createOptionList, ';', this->Makefile->GetSafeDefinition(createOptVar));
  2875. std::string const pchHeader = this->GetPchHeader(config, language, arch);
  2876. std::string const pchFile = this->GetPchFile(config, language, arch);
  2877. if (GlobalGenerator->IsFastbuild()) {
  2878. // Account for potential spaces in a shell-friendly way.
  2879. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
  2880. '"' + pchHeader + '"');
  2881. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>",
  2882. '"' + pchFile + '"');
  2883. } else {
  2884. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
  2885. pchHeader);
  2886. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
  2887. }
  2888. }
  2889. return inserted.first->second;
  2890. }
  2891. std::string cmGeneratorTarget::GetPchUseCompileOptions(
  2892. std::string const& config, std::string const& language,
  2893. std::string const& arch)
  2894. {
  2895. auto const inserted = this->PchUseCompileOptions.insert(
  2896. std::make_pair(language + config + arch, ""));
  2897. if (inserted.second) {
  2898. std::string& useOptionList = inserted.first->second;
  2899. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2900. useOptionList = this->Makefile->GetSafeDefinition(
  2901. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2902. }
  2903. std::string const useOptVar =
  2904. cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
  2905. std::string const& useOptionListProperty =
  2906. this->GetSafeProperty(useOptVar);
  2907. useOptionList = cmStrCat(
  2908. useOptionList, ';',
  2909. useOptionListProperty.empty()
  2910. ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
  2911. : useOptionListProperty);
  2912. std::string const pchHeader = this->GetPchHeader(config, language, arch);
  2913. std::string const pchFile = this->GetPchFile(config, language, arch);
  2914. if (GlobalGenerator->IsFastbuild()) {
  2915. // Account for potential spaces in a shell-friendly way.
  2916. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>",
  2917. '"' + pchHeader + '"');
  2918. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>",
  2919. '"' + pchFile + '"');
  2920. } else {
  2921. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
  2922. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
  2923. }
  2924. }
  2925. return inserted.first->second;
  2926. }
  2927. void cmGeneratorTarget::AddSourceFileToUnityBatch(
  2928. std::string const& sourceFilename)
  2929. {
  2930. this->UnityBatchedSourceFiles.insert(sourceFilename);
  2931. }
  2932. bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
  2933. std::string const& sourceFilename) const
  2934. {
  2935. if (!this->GetPropertyAsBool("UNITY_BUILD")) {
  2936. return false;
  2937. }
  2938. return this->UnityBatchedSourceFiles.find(sourceFilename) !=
  2939. this->UnityBatchedSourceFiles.end();
  2940. }
  2941. void cmGeneratorTarget::ComputeTargetManifest(std::string const& config) const
  2942. {
  2943. if (this->IsImported()) {
  2944. return;
  2945. }
  2946. cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
  2947. // Get the names.
  2948. cmGeneratorTarget::Names targetNames;
  2949. if (this->GetType() == cmStateEnums::EXECUTABLE) {
  2950. targetNames = this->GetExecutableNames(config);
  2951. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2952. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2953. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2954. targetNames = this->GetLibraryNames(config);
  2955. } else {
  2956. return;
  2957. }
  2958. // Get the directory.
  2959. std::string dir =
  2960. this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
  2961. // Add each name.
  2962. std::string f;
  2963. if (!targetNames.Output.empty()) {
  2964. f = cmStrCat(dir, '/', targetNames.Output);
  2965. gg->AddToManifest(f);
  2966. }
  2967. if (!targetNames.SharedObject.empty()) {
  2968. f = cmStrCat(dir, '/', targetNames.SharedObject);
  2969. gg->AddToManifest(f);
  2970. }
  2971. if (!targetNames.Real.empty()) {
  2972. f = cmStrCat(dir, '/', targetNames.Real);
  2973. gg->AddToManifest(f);
  2974. }
  2975. if (!targetNames.PDB.empty()) {
  2976. f = cmStrCat(dir, '/', targetNames.PDB);
  2977. gg->AddToManifest(f);
  2978. }
  2979. dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
  2980. if (!targetNames.ImportOutput.empty()) {
  2981. f = cmStrCat(dir, '/', targetNames.ImportOutput);
  2982. gg->AddToManifest(f);
  2983. }
  2984. if (!targetNames.ImportLibrary.empty()) {
  2985. f = cmStrCat(dir, '/', targetNames.ImportLibrary);
  2986. gg->AddToManifest(f);
  2987. }
  2988. if (!targetNames.ImportReal.empty()) {
  2989. f = cmStrCat(dir, '/', targetNames.ImportReal);
  2990. gg->AddToManifest(f);
  2991. }
  2992. }
  2993. cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
  2994. std::string const& lang, std::string const& config) const
  2995. {
  2996. cm::optional<cmStandardLevel> level;
  2997. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  2998. auto i = this->ExplicitStandardLevel.find(key);
  2999. if (i != this->ExplicitStandardLevel.end()) {
  3000. level = i->second;
  3001. }
  3002. return level;
  3003. }
  3004. void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
  3005. std::string const& config,
  3006. cmStandardLevel level)
  3007. {
  3008. auto e = this->ExplicitStandardLevel.emplace(
  3009. cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
  3010. if (!e.second && e.first->second < level) {
  3011. e.first->second = level;
  3012. }
  3013. }
  3014. bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
  3015. {
  3016. cmStandardLevelResolver standardResolver(this->Makefile);
  3017. for (std::string const& lang :
  3018. this->Makefile->GetState()->GetEnabledLanguages()) {
  3019. if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
  3020. if (cm::optional<cmStandardLevel> langLevel =
  3021. standardResolver.LanguageStandardLevel(lang, *languageStd)) {
  3022. this->UpdateExplicitStandardLevel(lang, config, *langLevel);
  3023. }
  3024. }
  3025. }
  3026. // Compute the language standard based on the compile features.
  3027. std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
  3028. for (BT<std::string> const& f : features) {
  3029. std::string lang;
  3030. if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
  3031. lang, nullptr)) {
  3032. return false;
  3033. }
  3034. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  3035. cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
  3036. cm::optional<cmStandardLevel> featureLevel;
  3037. std::string newRequiredStandard;
  3038. if (!standardResolver.GetNewRequiredStandard(
  3039. this->Target->GetName(), f.Value, currentLanguageStandard,
  3040. featureLevel, newRequiredStandard)) {
  3041. return false;
  3042. }
  3043. if (featureLevel) {
  3044. this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
  3045. }
  3046. if (!newRequiredStandard.empty()) {
  3047. BTs<std::string>& languageStandardProperty =
  3048. this->LanguageStandardMap[key];
  3049. if (languageStandardProperty.Value != newRequiredStandard) {
  3050. languageStandardProperty.Value = newRequiredStandard;
  3051. languageStandardProperty.Backtraces.clear();
  3052. }
  3053. languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
  3054. }
  3055. }
  3056. return true;
  3057. }
  3058. bool cmGeneratorTarget::ComputeCompileFeatures(
  3059. std::string const& config, std::set<LanguagePair> const& languagePairs)
  3060. {
  3061. for (auto const& language : languagePairs) {
  3062. BTs<std::string> const* generatorTargetLanguageStandard =
  3063. this->GetLanguageStandardProperty(language.first, config);
  3064. if (!generatorTargetLanguageStandard) {
  3065. // If the standard isn't explicitly set we copy it over from the
  3066. // specified paired language.
  3067. std::string key =
  3068. cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
  3069. BTs<std::string> const* standardToCopy =
  3070. this->GetLanguageStandardProperty(language.second, config);
  3071. if (standardToCopy) {
  3072. this->LanguageStandardMap[key] = *standardToCopy;
  3073. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  3074. } else {
  3075. cmValue defaultStandard = this->Makefile->GetDefinition(
  3076. cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
  3077. if (defaultStandard) {
  3078. this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
  3079. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  3080. }
  3081. }
  3082. // Custom updates for the CUDA standard.
  3083. if (generatorTargetLanguageStandard && (language.first == "CUDA")) {
  3084. if (generatorTargetLanguageStandard->Value == "98") {
  3085. this->LanguageStandardMap[key].Value = "03";
  3086. }
  3087. }
  3088. }
  3089. }
  3090. return true;
  3091. }
  3092. std::string cmGeneratorTarget::GetImportedLibName(
  3093. std::string const& config) const
  3094. {
  3095. if (cmGeneratorTarget::ImportInfo const* info =
  3096. this->GetImportInfo(config)) {
  3097. return info->LibName;
  3098. }
  3099. return std::string();
  3100. }
  3101. std::string cmGeneratorTarget::GetFullPath(std::string const& config,
  3102. cmStateEnums::ArtifactType artifact,
  3103. bool realname) const
  3104. {
  3105. if (this->IsImported()) {
  3106. return this->Target->ImportedGetFullPath(config, artifact);
  3107. }
  3108. return this->NormalGetFullPath(config, artifact, realname);
  3109. }
  3110. std::string cmGeneratorTarget::NormalGetFullPath(
  3111. std::string const& config, cmStateEnums::ArtifactType artifact,
  3112. bool realname) const
  3113. {
  3114. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  3115. if (this->IsAppBundleOnApple()) {
  3116. fpath =
  3117. cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
  3118. }
  3119. // Add the full name of the target.
  3120. switch (artifact) {
  3121. case cmStateEnums::RuntimeBinaryArtifact:
  3122. if (realname) {
  3123. fpath += this->NormalGetRealName(config);
  3124. } else {
  3125. fpath +=
  3126. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
  3127. }
  3128. break;
  3129. case cmStateEnums::ImportLibraryArtifact:
  3130. if (realname) {
  3131. fpath +=
  3132. this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
  3133. } else {
  3134. fpath +=
  3135. this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
  3136. }
  3137. break;
  3138. }
  3139. return fpath;
  3140. }
  3141. std::string cmGeneratorTarget::NormalGetRealName(
  3142. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3143. {
  3144. // This should not be called for imported targets.
  3145. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3146. // enforcement of the limited imported target API.
  3147. if (this->IsImported()) {
  3148. std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
  3149. this->GetName());
  3150. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3151. }
  3152. Names names = this->GetType() == cmStateEnums::EXECUTABLE
  3153. ? this->GetExecutableNames(config)
  3154. : this->GetLibraryNames(config);
  3155. // Compute the real name that will be built.
  3156. return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
  3157. : names.ImportReal;
  3158. }
  3159. cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
  3160. std::string const& config) const
  3161. {
  3162. cmGeneratorTarget::Names targetNames;
  3163. // This should not be called for imported targets.
  3164. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3165. // enforcement of the limited imported target API.
  3166. if (this->IsImported()) {
  3167. std::string msg =
  3168. cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
  3169. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3170. }
  3171. // Check for library version properties.
  3172. cmValue version = this->GetProperty("VERSION");
  3173. cmValue soversion = this->GetProperty("SOVERSION");
  3174. if (!this->HasSOName(config) ||
  3175. this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
  3176. this->IsFrameworkOnApple()) {
  3177. // Versioning is supported only for shared libraries and modules,
  3178. // and then only when the platform supports an soname flag.
  3179. version = nullptr;
  3180. soversion = nullptr;
  3181. }
  3182. if (version && !soversion) {
  3183. // The soversion must be set if the library version is set. Use
  3184. // the library version as the soversion.
  3185. soversion = version;
  3186. }
  3187. if (!version && soversion) {
  3188. // Use the soversion as the library version.
  3189. version = soversion;
  3190. }
  3191. // Get the components of the library name.
  3192. NameComponents const& components = this->GetFullNameInternalComponents(
  3193. config, cmStateEnums::RuntimeBinaryArtifact);
  3194. // The library name.
  3195. targetNames.Base = components.base;
  3196. targetNames.Output =
  3197. cmStrCat(components.prefix, targetNames.Base, components.suffix);
  3198. if (this->IsFrameworkOnApple()) {
  3199. targetNames.Real = components.prefix;
  3200. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3201. targetNames.Real +=
  3202. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3203. }
  3204. targetNames.Real += cmStrCat(targetNames.Base, components.suffix);
  3205. targetNames.SharedObject = targetNames.Real;
  3206. } else if (this->IsArchivedAIXSharedLibrary()) {
  3207. targetNames.SharedObject =
  3208. cmStrCat(components.prefix, targetNames.Base, ".so");
  3209. if (soversion) {
  3210. targetNames.SharedObject += ".";
  3211. targetNames.SharedObject += *soversion;
  3212. }
  3213. targetNames.Real = targetNames.Output;
  3214. } else {
  3215. // The library's soname.
  3216. targetNames.SharedObject = this->ComputeVersionedName(
  3217. components.prefix, targetNames.Base, components.suffix,
  3218. targetNames.Output, soversion);
  3219. // The library's real name on disk.
  3220. targetNames.Real = this->ComputeVersionedName(
  3221. components.prefix, targetNames.Base, components.suffix,
  3222. targetNames.Output, version);
  3223. }
  3224. // The import library names.
  3225. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3226. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3227. NameComponents const& importComponents =
  3228. this->GetFullNameInternalComponents(config,
  3229. cmStateEnums::ImportLibraryArtifact);
  3230. targetNames.ImportOutput = cmStrCat(
  3231. importComponents.prefix, importComponents.base, importComponents.suffix);
  3232. if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
  3233. targetNames.ImportReal = components.prefix;
  3234. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3235. targetNames.ImportReal +=
  3236. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3237. }
  3238. targetNames.ImportReal +=
  3239. cmStrCat(importComponents.base, importComponents.suffix);
  3240. targetNames.ImportLibrary = targetNames.ImportOutput;
  3241. } else {
  3242. // The import library's soname.
  3243. targetNames.ImportLibrary = this->ComputeVersionedName(
  3244. importComponents.prefix, importComponents.base,
  3245. importComponents.suffix, targetNames.ImportOutput, soversion);
  3246. // The import library's real name on disk.
  3247. targetNames.ImportReal = this->ComputeVersionedName(
  3248. importComponents.prefix, importComponents.base,
  3249. importComponents.suffix, targetNames.ImportOutput, version);
  3250. }
  3251. }
  3252. // The program database file name.
  3253. targetNames.PDB = this->GetPDBName(config);
  3254. return targetNames;
  3255. }
  3256. cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
  3257. std::string const& config) const
  3258. {
  3259. cmGeneratorTarget::Names targetNames;
  3260. // This should not be called for imported targets.
  3261. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3262. // enforcement of the limited imported target API.
  3263. if (this->IsImported()) {
  3264. std::string msg = cmStrCat(
  3265. "GetExecutableNames called on imported target: ", this->GetName());
  3266. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3267. }
  3268. // This versioning is supported only for executables and then only
  3269. // when the platform supports symbolic links.
  3270. #if defined(_WIN32) && !defined(__CYGWIN__)
  3271. cmValue version;
  3272. #else
  3273. // Check for executable version properties.
  3274. cmValue version = this->GetProperty("VERSION");
  3275. if (this->GetType() != cmStateEnums::EXECUTABLE ||
  3276. this->Makefile->IsOn("XCODE")) {
  3277. version = nullptr;
  3278. }
  3279. #endif
  3280. // Get the components of the executable name.
  3281. NameComponents const& components = this->GetFullNameInternalComponents(
  3282. config, cmStateEnums::RuntimeBinaryArtifact);
  3283. // The executable name.
  3284. targetNames.Base = components.base;
  3285. if (this->IsArchivedAIXSharedLibrary()) {
  3286. targetNames.Output = components.prefix + targetNames.Base;
  3287. } else {
  3288. targetNames.Output =
  3289. components.prefix + targetNames.Base + components.suffix;
  3290. }
  3291. // The executable's real name on disk.
  3292. #if defined(__CYGWIN__)
  3293. targetNames.Real = components.prefix + targetNames.Base;
  3294. #else
  3295. targetNames.Real = targetNames.Output;
  3296. #endif
  3297. if (version) {
  3298. targetNames.Real += "-";
  3299. targetNames.Real += *version;
  3300. }
  3301. #if defined(__CYGWIN__)
  3302. targetNames.Real += components.suffix;
  3303. #endif
  3304. // The import library name.
  3305. targetNames.ImportLibrary =
  3306. this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
  3307. targetNames.ImportReal = targetNames.ImportLibrary;
  3308. targetNames.ImportOutput = targetNames.ImportLibrary;
  3309. // The program database file name.
  3310. targetNames.PDB = this->GetPDBName(config);
  3311. return targetNames;
  3312. }
  3313. std::string cmGeneratorTarget::GetFullNameInternal(
  3314. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3315. {
  3316. NameComponents const& components =
  3317. this->GetFullNameInternalComponents(config, artifact);
  3318. return components.prefix + components.base + components.suffix;
  3319. }
  3320. std::string cmGeneratorTarget::ImportedGetLocation(
  3321. std::string const& config) const
  3322. {
  3323. assert(this->IsImported());
  3324. return this->Target->ImportedGetFullPath(
  3325. config, cmStateEnums::RuntimeBinaryArtifact);
  3326. }
  3327. std::string cmGeneratorTarget::GetFullNameImported(
  3328. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3329. {
  3330. return cmSystemTools::GetFilenameName(
  3331. this->Target->ImportedGetFullPath(config, artifact));
  3332. }
  3333. cmGeneratorTarget::NameComponents const&
  3334. cmGeneratorTarget::GetFullNameInternalComponents(
  3335. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3336. {
  3337. assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
  3338. artifact == cmStateEnums::ImportLibraryArtifact);
  3339. FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
  3340. ? RuntimeBinaryFullNameCache
  3341. : ImportLibraryFullNameCache;
  3342. auto search = cache.find(config);
  3343. if (search != cache.end()) {
  3344. return search->second;
  3345. }
  3346. // Use just the target name for non-main target types.
  3347. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3348. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3349. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3350. this->GetType() != cmStateEnums::EXECUTABLE) {
  3351. NameComponents components;
  3352. components.base = this->GetName();
  3353. return cache.emplace(config, std::move(components)).first->second;
  3354. }
  3355. bool const isImportedLibraryArtifact =
  3356. (artifact == cmStateEnums::ImportLibraryArtifact);
  3357. // Return an empty name for the import library if this platform
  3358. // does not support import libraries.
  3359. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  3360. return cache.emplace(config, NameComponents()).first->second;
  3361. }
  3362. NameComponents parts;
  3363. std::string& outPrefix = parts.prefix;
  3364. std::string& outBase = parts.base;
  3365. std::string& outSuffix = parts.suffix;
  3366. // retrieve prefix and suffix
  3367. std::string ll = this->GetLinkerLanguage(config);
  3368. cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
  3369. cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
  3370. // The implib option is only allowed for shared libraries, module
  3371. // libraries, and executables.
  3372. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3373. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3374. this->GetType() != cmStateEnums::EXECUTABLE) {
  3375. artifact = cmStateEnums::RuntimeBinaryArtifact;
  3376. }
  3377. // Compute the full name for main target types.
  3378. std::string configPostfix = this->GetFilePostfix(config);
  3379. // frameworks have directory prefix
  3380. std::string fw_prefix;
  3381. if (this->IsFrameworkOnApple()) {
  3382. fw_prefix =
  3383. cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
  3384. targetPrefix = cmValue(fw_prefix);
  3385. if (!isImportedLibraryArtifact) {
  3386. // no suffix
  3387. targetSuffix = nullptr;
  3388. }
  3389. }
  3390. if (this->IsCFBundleOnApple()) {
  3391. fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
  3392. targetPrefix = cmValue(fw_prefix);
  3393. targetSuffix = nullptr;
  3394. }
  3395. // Begin the final name with the prefix.
  3396. outPrefix = targetPrefix ? *targetPrefix : "";
  3397. // Append the target name or property-specified name.
  3398. outBase += this->GetOutputName(config, artifact);
  3399. // Append the per-configuration postfix.
  3400. // When using Xcode, the postfix should be part of the suffix rather than
  3401. // the base, because the suffix ends up being used in Xcode's
  3402. // EXECUTABLE_SUFFIX attribute.
  3403. if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
  3404. configPostfix += *targetSuffix;
  3405. targetSuffix = cmValue(configPostfix);
  3406. } else {
  3407. outBase += configPostfix;
  3408. }
  3409. // Name shared libraries with their version number on some platforms.
  3410. if (cmValue soversion = this->GetProperty("SOVERSION")) {
  3411. cmValue dllProp;
  3412. if (this->IsDLLPlatform()) {
  3413. dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
  3414. }
  3415. if (this->GetType() == cmStateEnums::SHARED_LIBRARY &&
  3416. !isImportedLibraryArtifact &&
  3417. (dllProp.IsOn() ||
  3418. (!dllProp.IsSet() &&
  3419. this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
  3420. outBase += "-";
  3421. outBase += *soversion;
  3422. }
  3423. }
  3424. // Append the suffix.
  3425. outSuffix = targetSuffix ? *targetSuffix : "";
  3426. return cache.emplace(config, std::move(parts)).first->second;
  3427. }
  3428. std::string cmGeneratorTarget::GetLinkerLanguage(
  3429. std::string const& config) const
  3430. {
  3431. return this->GetLinkClosure(config)->LinkerLanguage;
  3432. }
  3433. std::string cmGeneratorTarget::GetLinkerTool(std::string const& config) const
  3434. {
  3435. return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
  3436. }
  3437. std::string cmGeneratorTarget::GetLinkerTool(std::string const& lang,
  3438. std::string const& config) const
  3439. {
  3440. auto linkMode = cmStrCat(
  3441. "CMAKE_", lang, this->IsDeviceLink() ? "_DEVICE_" : "_", "LINK_MODE");
  3442. auto mode = this->Makefile->GetDefinition(linkMode);
  3443. if (!mode || mode != "LINKER"_s) {
  3444. return this->Makefile->GetDefinition("CMAKE_LINKER");
  3445. }
  3446. auto linkerType = this->GetLinkerTypeProperty(lang, config);
  3447. if (linkerType.empty()) {
  3448. linkerType = "DEFAULT";
  3449. }
  3450. auto usingLinker =
  3451. cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
  3452. "LINKER_", linkerType);
  3453. auto linkerTool = this->Makefile->GetDefinition(usingLinker);
  3454. if (!linkerTool) {
  3455. if (this->GetGlobalGenerator()->IsVisualStudio() &&
  3456. linkerType == "DEFAULT"_s) {
  3457. return std::string{};
  3458. }
  3459. // fall-back to generic definition
  3460. linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
  3461. if (linkerType != "DEFAULT"_s) {
  3462. auto isCMakeLinkerType = [](std::string const& type) -> bool {
  3463. return std::all_of(type.cbegin(), type.cend(),
  3464. [](char c) { return std::isupper(c); });
  3465. };
  3466. if (isCMakeLinkerType(linkerType)) {
  3467. this->LocalGenerator->IssueMessage(
  3468. MessageType::FATAL_ERROR,
  3469. cmStrCat("LINKER_TYPE '", linkerType,
  3470. "' is unknown or not supported by this toolchain."));
  3471. } else {
  3472. this->LocalGenerator->IssueMessage(
  3473. MessageType::FATAL_ERROR,
  3474. cmStrCat("LINKER_TYPE '", linkerType,
  3475. "' is unknown. Did you forget to define the '", usingLinker,
  3476. "' variable?"));
  3477. }
  3478. }
  3479. }
  3480. return linkerTool;
  3481. }
  3482. bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
  3483. std::string const& config) const
  3484. {
  3485. // FIXME(#25486): Account for the LINKER_TYPE target property.
  3486. // Also factor out the hard-coded list below into a platform
  3487. // information table based on the linker id.
  3488. std::string ll = this->GetLinkerLanguage(config);
  3489. std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
  3490. cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
  3491. // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
  3492. // recursively by default. The Solaris linker has similar behavior.
  3493. return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
  3494. }
  3495. std::string cmGeneratorTarget::GetPDBOutputName(
  3496. std::string const& config) const
  3497. {
  3498. // Lookup/compute/cache the pdb output name for this configuration.
  3499. auto i = this->PdbOutputNameMap.find(config);
  3500. if (i == this->PdbOutputNameMap.end()) {
  3501. // Add empty name in map to detect potential recursion.
  3502. PdbOutputNameMapType::value_type entry(config, "");
  3503. i = this->PdbOutputNameMap.insert(entry).first;
  3504. // Compute output name.
  3505. std::vector<std::string> props;
  3506. std::string configUpper = cmSystemTools::UpperCase(config);
  3507. if (!configUpper.empty()) {
  3508. // PDB_NAME_<CONFIG>
  3509. props.push_back("PDB_NAME_" + configUpper);
  3510. }
  3511. // PDB_NAME
  3512. props.emplace_back("PDB_NAME");
  3513. std::string outName;
  3514. for (std::string const& p : props) {
  3515. if (cmValue outNameProp = this->GetProperty(p)) {
  3516. outName = *outNameProp;
  3517. break;
  3518. }
  3519. }
  3520. // Now evaluate genex and update the previously-prepared map entry.
  3521. if (outName.empty()) {
  3522. i->second = cmStrCat(
  3523. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact),
  3524. this->GetPolicyStatusCMP0202() != cmPolicies::NEW
  3525. ? this->GetFilePostfix(config)
  3526. : "");
  3527. } else {
  3528. i->second =
  3529. cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
  3530. }
  3531. } else if (i->second.empty()) {
  3532. // An empty map entry indicates we have been called recursively
  3533. // from the above block.
  3534. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  3535. MessageType::FATAL_ERROR,
  3536. "Target '" + this->GetName() + "' PDB_NAME depends on itself.",
  3537. this->GetBacktrace());
  3538. }
  3539. return i->second;
  3540. }
  3541. std::string cmGeneratorTarget::GetPDBName(std::string const& config) const
  3542. {
  3543. NameComponents const& parts = this->GetFullNameInternalComponents(
  3544. config, cmStateEnums::RuntimeBinaryArtifact);
  3545. std::string base = this->GetPDBOutputName(config);
  3546. return cmStrCat(parts.prefix, base,
  3547. this->GetPolicyStatusCMP0202() == cmPolicies::NEW
  3548. ? this->GetFilePostfix(config)
  3549. : "",
  3550. ".pdb");
  3551. }
  3552. std::string cmGeneratorTarget::GetObjectDirectory(
  3553. std::string const& config) const
  3554. {
  3555. std::string obj_dir =
  3556. this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
  3557. #if defined(__APPLE__)
  3558. // Replace Xcode's placeholder for the object file directory since
  3559. // installation and export scripts need to know the real directory.
  3560. // Xcode has build-time settings (e.g. for sanitizers) that affect this,
  3561. // but we use the default here. Users that want to enable sanitizers
  3562. // will do so at the cost of object library installation and export.
  3563. cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
  3564. "Objects-normal");
  3565. #endif
  3566. return obj_dir;
  3567. }
  3568. void cmGeneratorTarget::GetTargetObjectNames(
  3569. std::string const& config, std::vector<std::string>& objects) const
  3570. {
  3571. this->GetTargetObjectLocations(
  3572. config,
  3573. [&objects](cmObjectLocation const& buildLoc, cmObjectLocation const&) {
  3574. objects.push_back(buildLoc.GetPath());
  3575. });
  3576. }
  3577. void cmGeneratorTarget::GetTargetObjectLocations(
  3578. std::string const& config,
  3579. std::function<void(cmObjectLocation const&, cmObjectLocation const&)> cb)
  3580. const
  3581. {
  3582. std::vector<cmSourceFile const*> objectSources;
  3583. this->GetObjectSources(objectSources, config);
  3584. std::map<cmSourceFile const*, cmObjectLocations> mapping;
  3585. for (cmSourceFile const* sf : objectSources) {
  3586. mapping[sf];
  3587. }
  3588. this->LocalGenerator->ComputeObjectFilenames(mapping, config, this);
  3589. auto const buildUseShortPaths = this->GetUseShortObjectNames()
  3590. ? cmObjectLocations::UseShortPath::Yes
  3591. : cmObjectLocations::UseShortPath::No;
  3592. auto const installUseShortPaths = this->GetUseShortObjectNamesForInstall();
  3593. for (cmSourceFile const* src : objectSources) {
  3594. // Find the object file name corresponding to this source file.
  3595. auto map_it = mapping.find(src);
  3596. auto const& buildLoc = map_it->second.GetLocation(buildUseShortPaths);
  3597. auto const& installLoc =
  3598. map_it->second.GetInstallLocation(installUseShortPaths, config);
  3599. // It must exist because we populated the mapping just above.
  3600. assert(!buildLoc.GetPath().empty());
  3601. assert(!installLoc.GetPath().empty());
  3602. cb(buildLoc, installLoc);
  3603. }
  3604. // We need to compute the relative path from the root of
  3605. // of the object directory to handle subdirectory paths
  3606. std::string rootObjectDir = this->GetObjectDirectory(config);
  3607. rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
  3608. auto ispcObjects = this->GetGeneratedISPCObjects(config);
  3609. for (std::string const& output : ispcObjects) {
  3610. auto relativePathFromObjectDir = output.substr(rootObjectDir.size());
  3611. cmObjectLocation ispcLoc(relativePathFromObjectDir);
  3612. // FIXME: apply short path to this object if needed.
  3613. cb(ispcLoc, ispcLoc);
  3614. }
  3615. }
  3616. bool cmGeneratorTarget::StrictTargetComparison::operator()(
  3617. cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
  3618. {
  3619. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  3620. if (nameResult == 0) {
  3621. return strcmp(
  3622. t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
  3623. t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
  3624. }
  3625. return nameResult < 0;
  3626. }
  3627. struct cmGeneratorTarget::SourceFileFlags
  3628. cmGeneratorTarget::GetTargetSourceFileFlags(cmSourceFile const* sf) const
  3629. {
  3630. struct SourceFileFlags flags;
  3631. this->ConstructSourceFileFlags();
  3632. auto si = this->SourceFlagsMap.find(sf);
  3633. if (si != this->SourceFlagsMap.end()) {
  3634. flags = si->second;
  3635. } else {
  3636. // Handle the MACOSX_PACKAGE_LOCATION property on source files that
  3637. // were not listed in one of the other lists.
  3638. if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
  3639. flags.MacFolder = location->c_str();
  3640. bool const stripResources =
  3641. this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
  3642. if (*location == "Resources") {
  3643. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3644. if (stripResources) {
  3645. flags.MacFolder = "";
  3646. }
  3647. } else if (cmHasLiteralPrefix(*location, "Resources/")) {
  3648. flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
  3649. if (stripResources) {
  3650. flags.MacFolder += cmStrLen("Resources/");
  3651. }
  3652. } else {
  3653. flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
  3654. }
  3655. }
  3656. }
  3657. return flags;
  3658. }
  3659. void cmGeneratorTarget::ConstructSourceFileFlags() const
  3660. {
  3661. if (this->SourceFileFlagsConstructed) {
  3662. return;
  3663. }
  3664. this->SourceFileFlagsConstructed = true;
  3665. // Process public headers to mark the source files.
  3666. if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
  3667. cmList relFiles{ *files };
  3668. for (auto const& relFile : relFiles) {
  3669. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3670. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3671. flags.MacFolder = "Headers";
  3672. flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
  3673. }
  3674. }
  3675. }
  3676. // Process private headers after public headers so that they take
  3677. // precedence if a file is listed in both.
  3678. if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
  3679. cmList relFiles{ *files };
  3680. for (auto const& relFile : relFiles) {
  3681. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3682. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3683. flags.MacFolder = "PrivateHeaders";
  3684. flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
  3685. }
  3686. }
  3687. }
  3688. // Mark sources listed as resources.
  3689. if (cmValue files = this->GetProperty("RESOURCE")) {
  3690. cmList relFiles{ *files };
  3691. for (auto const& relFile : relFiles) {
  3692. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3693. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3694. flags.MacFolder = "";
  3695. if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
  3696. flags.MacFolder = "Resources";
  3697. }
  3698. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3699. }
  3700. }
  3701. }
  3702. }
  3703. bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
  3704. {
  3705. bool previous = this->DeviceLink;
  3706. this->DeviceLink = deviceLink;
  3707. return previous;
  3708. }
  3709. void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
  3710. {
  3711. int patch;
  3712. this->GetTargetVersion("VERSION", major, minor, patch);
  3713. }
  3714. void cmGeneratorTarget::GetTargetVersionFallback(
  3715. std::string const& property, std::string const& fallback_property,
  3716. int& major, int& minor, int& patch) const
  3717. {
  3718. if (this->GetProperty(property)) {
  3719. this->GetTargetVersion(property, major, minor, patch);
  3720. } else {
  3721. this->GetTargetVersion(fallback_property, major, minor, patch);
  3722. }
  3723. }
  3724. void cmGeneratorTarget::GetTargetVersion(std::string const& property,
  3725. int& major, int& minor,
  3726. int& patch) const
  3727. {
  3728. // Set the default values.
  3729. major = 0;
  3730. minor = 0;
  3731. patch = 0;
  3732. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3733. if (cmValue version = this->GetProperty(property)) {
  3734. // Try to parse the version number and store the results that were
  3735. // successfully parsed.
  3736. int parsed_major;
  3737. int parsed_minor;
  3738. int parsed_patch;
  3739. switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
  3740. &parsed_patch)) {
  3741. case 3:
  3742. patch = parsed_patch;
  3743. CM_FALLTHROUGH;
  3744. case 2:
  3745. minor = parsed_minor;
  3746. CM_FALLTHROUGH;
  3747. case 1:
  3748. major = parsed_major;
  3749. CM_FALLTHROUGH;
  3750. default:
  3751. break;
  3752. }
  3753. }
  3754. }
  3755. std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
  3756. std::string const& lang, std::string const& config) const
  3757. {
  3758. // This is activated by the presence of a default selection whether or
  3759. // not it is overridden by a property.
  3760. cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
  3761. cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
  3762. if (!cmNonempty(runtimeLibraryDefault)) {
  3763. return std::string();
  3764. }
  3765. cmValue runtimeLibraryValue =
  3766. this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
  3767. if (!runtimeLibraryValue) {
  3768. runtimeLibraryValue = runtimeLibraryDefault;
  3769. }
  3770. return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
  3771. *runtimeLibraryValue, this->LocalGenerator, config, this));
  3772. }
  3773. std::string cmGeneratorTarget::GetFortranModuleDirectory(
  3774. std::string const& working_dir) const
  3775. {
  3776. if (!this->FortranModuleDirectoryCreated) {
  3777. this->FortranModuleDirectory =
  3778. this->CreateFortranModuleDirectory(working_dir);
  3779. this->FortranModuleDirectoryCreated = true;
  3780. }
  3781. return this->FortranModuleDirectory;
  3782. }
  3783. bool cmGeneratorTarget::IsFortranBuildingIntrinsicModules() const
  3784. {
  3785. // ATTENTION Before 4.0 the property name was misspelled.
  3786. // Check the correct name first and than the old name.
  3787. if (cmValue prop = this->GetProperty("Fortran_BUILDING_INTRINSIC_MODULES")) {
  3788. return prop.IsOn();
  3789. }
  3790. if (cmValue prop =
  3791. this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
  3792. return prop.IsOn();
  3793. }
  3794. return false;
  3795. }
  3796. std::string cmGeneratorTarget::CreateFortranModuleDirectory(
  3797. std::string const& working_dir) const
  3798. {
  3799. std::string mod_dir;
  3800. std::string target_mod_dir;
  3801. if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
  3802. target_mod_dir = *prop;
  3803. } else {
  3804. std::string const& default_mod_dir =
  3805. this->LocalGenerator->GetCurrentBinaryDirectory();
  3806. if (default_mod_dir != working_dir) {
  3807. target_mod_dir = default_mod_dir;
  3808. }
  3809. }
  3810. cmValue moddir_flag =
  3811. this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
  3812. if (!target_mod_dir.empty() && moddir_flag) {
  3813. // Compute the full path to the module directory.
  3814. if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
  3815. // Already a full path.
  3816. mod_dir = target_mod_dir;
  3817. } else {
  3818. // Interpret relative to the current output directory.
  3819. mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  3820. '/', target_mod_dir);
  3821. }
  3822. // Make sure the module output directory exists.
  3823. cmSystemTools::MakeDirectory(mod_dir);
  3824. }
  3825. return mod_dir;
  3826. }
  3827. void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
  3828. std::string const& config)
  3829. {
  3830. std::string config_upper;
  3831. if (!config.empty()) {
  3832. config_upper = cmSystemTools::UpperCase(config);
  3833. }
  3834. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3835. if (iter == this->ISPCGeneratedHeaders.end()) {
  3836. std::vector<std::string> headers;
  3837. headers.emplace_back(header);
  3838. this->ISPCGeneratedHeaders.insert({ config_upper, headers });
  3839. } else {
  3840. iter->second.emplace_back(header);
  3841. }
  3842. }
  3843. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
  3844. std::string const& config) const
  3845. {
  3846. std::string config_upper;
  3847. if (!config.empty()) {
  3848. config_upper = cmSystemTools::UpperCase(config);
  3849. }
  3850. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3851. if (iter == this->ISPCGeneratedHeaders.end()) {
  3852. return std::vector<std::string>{};
  3853. }
  3854. return iter->second;
  3855. }
  3856. void cmGeneratorTarget::AddISPCGeneratedObject(std::vector<std::string>&& objs,
  3857. std::string const& config)
  3858. {
  3859. std::string config_upper;
  3860. if (!config.empty()) {
  3861. config_upper = cmSystemTools::UpperCase(config);
  3862. }
  3863. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3864. if (iter == this->ISPCGeneratedObjects.end()) {
  3865. this->ISPCGeneratedObjects.insert({ config_upper, objs });
  3866. } else {
  3867. iter->second.insert(iter->second.end(), objs.begin(), objs.end());
  3868. }
  3869. }
  3870. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCObjects(
  3871. std::string const& config) const
  3872. {
  3873. std::string config_upper;
  3874. if (!config.empty()) {
  3875. config_upper = cmSystemTools::UpperCase(config);
  3876. }
  3877. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3878. if (iter == this->ISPCGeneratedObjects.end()) {
  3879. return std::vector<std::string>{};
  3880. }
  3881. return iter->second;
  3882. }
  3883. std::string cmGeneratorTarget::GetFrameworkVersion() const
  3884. {
  3885. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3886. if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
  3887. return *fversion;
  3888. }
  3889. if (cmValue tversion = this->GetProperty("VERSION")) {
  3890. return *tversion;
  3891. }
  3892. return "A";
  3893. }
  3894. std::string cmGeneratorTarget::ComputeVersionedName(std::string const& prefix,
  3895. std::string const& base,
  3896. std::string const& suffix,
  3897. std::string const& name,
  3898. cmValue version) const
  3899. {
  3900. std::string vName = this->IsApple() ? (prefix + base) : name;
  3901. if (version) {
  3902. vName += ".";
  3903. vName += *version;
  3904. }
  3905. vName += this->IsApple() ? suffix : std::string();
  3906. return vName;
  3907. }
  3908. std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
  3909. {
  3910. return this->Target->GetProperties().GetKeys();
  3911. }
  3912. void cmGeneratorTarget::ReportPropertyOrigin(
  3913. std::string const& p, std::string const& result, std::string const& report,
  3914. std::string const& compatibilityType) const
  3915. {
  3916. cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
  3917. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3918. bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
  3919. cm::contains(debugProperties, p);
  3920. this->DebugCompatiblePropertiesDone[p] = true;
  3921. if (!debugOrigin) {
  3922. return;
  3923. }
  3924. std::string areport =
  3925. cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
  3926. this->GetName(), "\" (result: \"", result, "\"):\n", report);
  3927. this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
  3928. areport);
  3929. }
  3930. std::string cmGeneratorTarget::GetDirectory(
  3931. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3932. {
  3933. if (this->IsImported()) {
  3934. auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
  3935. if (this->IsFrameworkOnApple()) {
  3936. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  3937. fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
  3938. if (fwDescriptor) {
  3939. return fwDescriptor->Directory;
  3940. }
  3941. }
  3942. // Return the directory from which the target is imported.
  3943. return cmSystemTools::GetFilenamePath(fullPath);
  3944. }
  3945. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  3946. // Return the directory in which the target will be built.
  3947. switch (artifact) {
  3948. case cmStateEnums::RuntimeBinaryArtifact:
  3949. return info->OutDir;
  3950. case cmStateEnums::ImportLibraryArtifact:
  3951. return info->ImpDir;
  3952. }
  3953. }
  3954. return "";
  3955. }
  3956. bool cmGeneratorTarget::UsesDefaultOutputDir(
  3957. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3958. {
  3959. std::string dir;
  3960. return this->ComputeOutputDir(config, artifact, dir);
  3961. }
  3962. cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
  3963. std::string const& config) const
  3964. {
  3965. // There is no output information for imported targets.
  3966. if (this->IsImported()) {
  3967. return nullptr;
  3968. }
  3969. // Synthetic targets don't have output.
  3970. if (this->IsSynthetic()) {
  3971. return nullptr;
  3972. }
  3973. // Only libraries and executables have well-defined output files.
  3974. if (!this->HaveWellDefinedOutputFiles()) {
  3975. std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
  3976. this->GetName(), " which has type ",
  3977. cmState::GetTargetTypeName(this->GetType()));
  3978. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3979. return nullptr;
  3980. }
  3981. // Lookup/compute/cache the output information for this configuration.
  3982. std::string config_upper;
  3983. if (!config.empty()) {
  3984. config_upper = cmSystemTools::UpperCase(config);
  3985. }
  3986. auto i = this->OutputInfoMap.find(config_upper);
  3987. if (i == this->OutputInfoMap.end()) {
  3988. // Add empty info in map to detect potential recursion.
  3989. OutputInfo info;
  3990. OutputInfoMapType::value_type entry(config_upper, info);
  3991. i = this->OutputInfoMap.insert(entry).first;
  3992. // Compute output directories.
  3993. this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
  3994. info.OutDir);
  3995. this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
  3996. info.ImpDir);
  3997. if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
  3998. info.PdbDir = info.OutDir;
  3999. }
  4000. // Now update the previously-prepared map entry.
  4001. i->second = info;
  4002. } else if (i->second.empty()) {
  4003. // An empty map entry indicates we have been called recursively
  4004. // from the above block.
  4005. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  4006. MessageType::FATAL_ERROR,
  4007. "Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
  4008. this->GetBacktrace());
  4009. return nullptr;
  4010. }
  4011. return &i->second;
  4012. }
  4013. bool cmGeneratorTarget::ComputeOutputDir(std::string const& config,
  4014. cmStateEnums::ArtifactType artifact,
  4015. std::string& out) const
  4016. {
  4017. bool usesDefaultOutputDir = false;
  4018. std::string conf = config;
  4019. // Look for a target property defining the target output directory
  4020. // based on the target type.
  4021. std::string targetTypeName = this->GetOutputTargetType(artifact);
  4022. std::string propertyName;
  4023. if (!targetTypeName.empty()) {
  4024. propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
  4025. }
  4026. // Check for a per-configuration output directory target property.
  4027. std::string configUpper = cmSystemTools::UpperCase(conf);
  4028. std::string configProp;
  4029. if (!targetTypeName.empty()) {
  4030. configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
  4031. }
  4032. // Select an output directory.
  4033. if (cmValue config_outdir = this->GetProperty(configProp)) {
  4034. // Use the user-specified per-configuration output directory.
  4035. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  4036. config, this);
  4037. // Skip per-configuration subdirectory.
  4038. conf.clear();
  4039. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  4040. // Use the user-specified output directory.
  4041. out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
  4042. config, this);
  4043. // Skip per-configuration subdirectory if the value contained a
  4044. // generator expression.
  4045. if (out != *outdir) {
  4046. conf.clear();
  4047. }
  4048. } else if (this->GetType() == cmStateEnums::EXECUTABLE) {
  4049. // Lookup the output path for executables.
  4050. out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
  4051. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4052. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4053. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4054. // Lookup the output path for libraries.
  4055. out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
  4056. }
  4057. if (out.empty()) {
  4058. // Default to the current output directory.
  4059. usesDefaultOutputDir = true;
  4060. out = ".";
  4061. }
  4062. // Convert the output path to a full path in case it is
  4063. // specified as a relative path. Treat a relative path as
  4064. // relative to the current output directory for this makefile.
  4065. out = (cmSystemTools::CollapseFullPath(
  4066. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  4067. // The generator may add the configuration's subdirectory.
  4068. if (!conf.empty()) {
  4069. bool useEPN =
  4070. this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
  4071. std::string suffix =
  4072. usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
  4073. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  4074. "/", conf, suffix, out);
  4075. }
  4076. return usesDefaultOutputDir;
  4077. }
  4078. bool cmGeneratorTarget::ComputePDBOutputDir(std::string const& kind,
  4079. std::string const& config,
  4080. std::string& out) const
  4081. {
  4082. // Look for a target property defining the target output directory
  4083. // based on the target type.
  4084. std::string propertyName;
  4085. if (!kind.empty()) {
  4086. propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
  4087. }
  4088. std::string conf = config;
  4089. // Check for a per-configuration output directory target property.
  4090. std::string configUpper = cmSystemTools::UpperCase(conf);
  4091. std::string configProp;
  4092. if (!kind.empty()) {
  4093. configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
  4094. }
  4095. // Select an output directory.
  4096. if (cmValue config_outdir = this->GetProperty(configProp)) {
  4097. // Use the user-specified per-configuration output directory.
  4098. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  4099. config);
  4100. // Skip per-configuration subdirectory.
  4101. conf.clear();
  4102. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  4103. // Use the user-specified output directory.
  4104. out =
  4105. cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
  4106. // Skip per-configuration subdirectory if the value contained a
  4107. // generator expression.
  4108. if (out != *outdir) {
  4109. conf.clear();
  4110. }
  4111. }
  4112. if (out.empty()) {
  4113. // Compile output should always have a path.
  4114. if (kind == "COMPILE_PDB"_s) {
  4115. out = this->GetSupportDirectory();
  4116. } else {
  4117. return false;
  4118. }
  4119. }
  4120. // Convert the output path to a full path in case it is
  4121. // specified as a relative path. Treat a relative path as
  4122. // relative to the current output directory for this makefile.
  4123. out = (cmSystemTools::CollapseFullPath(
  4124. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  4125. // The generator may add the configuration's subdirectory.
  4126. if (!conf.empty()) {
  4127. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  4128. "/", conf, "", out);
  4129. }
  4130. return true;
  4131. }
  4132. bool cmGeneratorTarget::HaveInstallTreeRPATH(std::string const& config) const
  4133. {
  4134. std::string install_rpath;
  4135. this->GetInstallRPATH(config, install_rpath);
  4136. return !install_rpath.empty() &&
  4137. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  4138. }
  4139. bool cmGeneratorTarget::GetBuildRPATH(std::string const& config,
  4140. std::string& rpath) const
  4141. {
  4142. return this->GetRPATH(config, "BUILD_RPATH", rpath);
  4143. }
  4144. bool cmGeneratorTarget::GetInstallRPATH(std::string const& config,
  4145. std::string& rpath) const
  4146. {
  4147. return this->GetRPATH(config, "INSTALL_RPATH", rpath);
  4148. }
  4149. bool cmGeneratorTarget::GetRPATH(std::string const& config,
  4150. std::string const& prop,
  4151. std::string& rpath) const
  4152. {
  4153. cmValue value = this->GetProperty(prop);
  4154. if (!value) {
  4155. return false;
  4156. }
  4157. rpath =
  4158. cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
  4159. return true;
  4160. }
  4161. cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
  4162. std::string const& config) const
  4163. {
  4164. // There is no imported information for non-imported targets.
  4165. if (!this->IsImported()) {
  4166. return nullptr;
  4167. }
  4168. // Lookup/compute/cache the import information for this
  4169. // configuration.
  4170. std::string config_upper;
  4171. if (!config.empty()) {
  4172. config_upper = cmSystemTools::UpperCase(config);
  4173. } else {
  4174. config_upper = "NOCONFIG";
  4175. }
  4176. auto i = this->ImportInfoMap.find(config_upper);
  4177. if (i == this->ImportInfoMap.end()) {
  4178. ImportInfo info;
  4179. this->ComputeImportInfo(config_upper, info);
  4180. ImportInfoMapType::value_type entry(config_upper, info);
  4181. i = this->ImportInfoMap.insert(entry).first;
  4182. }
  4183. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  4184. return &i->second;
  4185. }
  4186. // If the location is empty then the target is not available for
  4187. // this configuration.
  4188. if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
  4189. return nullptr;
  4190. }
  4191. // Return the import information.
  4192. return &i->second;
  4193. }
  4194. void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
  4195. ImportInfo& info) const
  4196. {
  4197. // This method finds information about an imported target from its
  4198. // properties. The "IMPORTED_" namespace is reserved for properties
  4199. // defined by the project exporting the target.
  4200. // Initialize members.
  4201. info.NoSOName = false;
  4202. cmValue loc = nullptr;
  4203. cmValue imp = nullptr;
  4204. std::string suffix;
  4205. if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
  4206. return;
  4207. }
  4208. // Get the link interface.
  4209. {
  4210. // Use the INTERFACE_LINK_LIBRARIES special representation directly
  4211. // to get backtraces.
  4212. cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
  4213. if (!entries.empty()) {
  4214. info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
  4215. for (BT<std::string> const& entry : entries) {
  4216. info.Libraries.emplace_back(entry);
  4217. }
  4218. } else if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  4219. std::string linkProp =
  4220. cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
  4221. cmValue propertyLibs = this->GetProperty(linkProp);
  4222. if (!propertyLibs) {
  4223. linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
  4224. propertyLibs = this->GetProperty(linkProp);
  4225. }
  4226. if (propertyLibs) {
  4227. info.LibrariesProp = linkProp;
  4228. info.Libraries.emplace_back(*propertyLibs);
  4229. }
  4230. }
  4231. }
  4232. for (BT<std::string> const& entry :
  4233. this->Target->GetLinkInterfaceDirectEntries()) {
  4234. info.LibrariesHeadInclude.emplace_back(entry);
  4235. }
  4236. for (BT<std::string> const& entry :
  4237. this->Target->GetLinkInterfaceDirectExcludeEntries()) {
  4238. info.LibrariesHeadExclude.emplace_back(entry);
  4239. }
  4240. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  4241. if (loc) {
  4242. info.LibName = *loc;
  4243. }
  4244. return;
  4245. }
  4246. // A provided configuration has been chosen. Load the
  4247. // configuration's properties.
  4248. // Get the location.
  4249. if (loc) {
  4250. info.Location = *loc;
  4251. } else {
  4252. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  4253. if (cmValue config_location = this->GetProperty(impProp)) {
  4254. info.Location = *config_location;
  4255. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  4256. info.Location = *location;
  4257. }
  4258. }
  4259. // Get the soname.
  4260. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4261. std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
  4262. if (cmValue config_soname = this->GetProperty(soProp)) {
  4263. info.SOName = *config_soname;
  4264. } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
  4265. info.SOName = *soname;
  4266. }
  4267. }
  4268. // Get the "no-soname" mark.
  4269. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4270. std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
  4271. if (cmValue config_no_soname = this->GetProperty(soProp)) {
  4272. info.NoSOName = config_no_soname.IsOn();
  4273. } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
  4274. info.NoSOName = no_soname.IsOn();
  4275. }
  4276. }
  4277. // Get the import library.
  4278. if (imp) {
  4279. info.ImportLibrary = *imp;
  4280. } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4281. this->IsExecutableWithExports()) {
  4282. std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
  4283. if (cmValue config_implib = this->GetProperty(impProp)) {
  4284. info.ImportLibrary = *config_implib;
  4285. } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
  4286. info.ImportLibrary = *implib;
  4287. }
  4288. }
  4289. // Get the link dependencies.
  4290. {
  4291. std::string linkProp =
  4292. cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
  4293. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4294. info.SharedDeps = *config_libs;
  4295. } else if (cmValue libs =
  4296. this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
  4297. info.SharedDeps = *libs;
  4298. }
  4299. }
  4300. // Get the link languages.
  4301. if (this->LinkLanguagePropagatesToDependents()) {
  4302. std::string linkProp =
  4303. cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
  4304. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4305. info.Languages = *config_libs;
  4306. } else if (cmValue libs =
  4307. this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
  4308. info.Languages = *libs;
  4309. }
  4310. }
  4311. // Get information if target is managed assembly.
  4312. {
  4313. std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
  4314. if (cmValue pc = this->GetProperty(linkProp + suffix)) {
  4315. info.Managed = this->CheckManagedType(*pc);
  4316. } else if (cmValue p = this->GetProperty(linkProp)) {
  4317. info.Managed = this->CheckManagedType(*p);
  4318. }
  4319. }
  4320. // Get the cyclic repetition count.
  4321. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4322. std::string linkProp =
  4323. cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
  4324. if (cmValue config_reps = this->GetProperty(linkProp)) {
  4325. sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
  4326. } else if (cmValue reps =
  4327. this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
  4328. sscanf(reps->c_str(), "%u", &info.Multiplicity);
  4329. }
  4330. }
  4331. }
  4332. bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
  4333. std::vector<cmSourceFile*>& files) const
  4334. {
  4335. std::vector<std::string> const& configs =
  4336. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4337. auto it = configs.begin();
  4338. std::string const& firstConfig = *it;
  4339. this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
  4340. for (; it != configs.end(); ++it) {
  4341. std::vector<cmSourceFile*> configFiles;
  4342. this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
  4343. if (configFiles != files) {
  4344. std::string firstConfigFiles;
  4345. char const* sep = "";
  4346. for (cmSourceFile* f : files) {
  4347. firstConfigFiles += sep;
  4348. firstConfigFiles += f->ResolveFullPath();
  4349. sep = "\n ";
  4350. }
  4351. std::string thisConfigFiles;
  4352. sep = "";
  4353. for (cmSourceFile* f : configFiles) {
  4354. thisConfigFiles += sep;
  4355. thisConfigFiles += f->ResolveFullPath();
  4356. sep = "\n ";
  4357. }
  4358. std::ostringstream e;
  4359. /* clang-format off */
  4360. e << "Target \"" << this->GetName()
  4361. << "\" has source files which vary by "
  4362. "configuration. This is not supported by the \""
  4363. << this->GlobalGenerator->GetName()
  4364. << "\" generator.\n"
  4365. "Config \"" << firstConfig << "\":\n"
  4366. " " << firstConfigFiles << "\n"
  4367. "Config \"" << *it << "\":\n"
  4368. " " << thisConfigFiles << "\n";
  4369. /* clang-format on */
  4370. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4371. return false;
  4372. }
  4373. }
  4374. return true;
  4375. }
  4376. void cmGeneratorTarget::GetObjectLibrariesInSources(
  4377. std::vector<BT<cmGeneratorTarget*>>& objlibs) const
  4378. {
  4379. // FIXME: This searches SOURCES for TARGET_OBJECTS for backwards
  4380. // compatibility with the OLD behavior of CMP0026 since this
  4381. // could be called at configure time. CMP0026 has been removed,
  4382. // so this should now be called only at generate time.
  4383. // Therefore we should be able to improve the implementation
  4384. // with generate-time information.
  4385. cmBTStringRange rng = this->Target->GetSourceEntries();
  4386. for (auto const& entry : rng) {
  4387. cmList files{ entry.Value };
  4388. for (auto const& li : files) {
  4389. if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
  4390. std::string objLibName = li.substr(17, li.size() - 18);
  4391. if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
  4392. continue;
  4393. }
  4394. cmGeneratorTarget* objLib =
  4395. this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
  4396. if (objLib) {
  4397. objlibs.emplace_back(objLib, entry.Backtrace);
  4398. }
  4399. }
  4400. }
  4401. }
  4402. }
  4403. std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
  4404. {
  4405. // Strip whitespace off the library names because we used to do this
  4406. // in case variables were expanded at generate time. We no longer
  4407. // do the expansion but users link to libraries like " ${VAR} ".
  4408. std::string lib = item;
  4409. std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
  4410. if (pos != std::string::npos) {
  4411. lib = lib.substr(pos);
  4412. }
  4413. pos = lib.find_last_not_of(" \t\r\n");
  4414. if (pos != std::string::npos) {
  4415. lib = lib.substr(0, pos + 1);
  4416. }
  4417. if (lib != item) {
  4418. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  4419. std::ostringstream e;
  4420. e << "Target \"" << this->GetName() << "\" links to item \"" << item
  4421. << "\" which has leading or trailing whitespace. "
  4422. << "This is now an error according to policy CMP0004.";
  4423. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(), this->GetBacktrace());
  4424. }
  4425. return lib;
  4426. }
  4427. bool cmGeneratorTarget::IsDeprecated() const
  4428. {
  4429. cmValue deprecation = this->GetProperty("DEPRECATION");
  4430. return cmNonempty(deprecation);
  4431. }
  4432. std::string cmGeneratorTarget::GetDeprecation() const
  4433. {
  4434. // find DEPRECATION property
  4435. if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
  4436. return *deprecation;
  4437. }
  4438. return std::string();
  4439. }
  4440. void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
  4441. std::string const& config) const
  4442. {
  4443. // Targets that do not compile anything have no languages.
  4444. if (!this->CanCompileSources()) {
  4445. return;
  4446. }
  4447. std::vector<cmSourceFile*> sourceFiles;
  4448. this->GetSourceFiles(sourceFiles, config);
  4449. for (cmSourceFile* src : sourceFiles) {
  4450. std::string const& lang = src->GetOrDetermineLanguage();
  4451. if (!lang.empty()) {
  4452. languages.insert(lang);
  4453. }
  4454. }
  4455. std::set<cmGeneratorTarget const*> objectLibraries =
  4456. this->GetSourceObjectLibraries(config);
  4457. for (cmGeneratorTarget const* objLib : objectLibraries) {
  4458. objLib->GetLanguages(languages, config);
  4459. }
  4460. }
  4461. std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
  4462. std::string const& config) const
  4463. {
  4464. std::set<cmGeneratorTarget const*> objectLibraries;
  4465. std::vector<cmSourceFile const*> externalObjects;
  4466. this->GetExternalObjects(externalObjects, config);
  4467. for (cmSourceFile const* extObj : externalObjects) {
  4468. std::string objLib = extObj->GetObjectLibrary();
  4469. if (cmGeneratorTarget* tgt =
  4470. this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
  4471. objectLibraries.insert(tgt);
  4472. }
  4473. }
  4474. return objectLibraries;
  4475. }
  4476. bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
  4477. std::string const& config) const
  4478. {
  4479. std::set<std::string> languages;
  4480. this->GetLanguages(languages, config);
  4481. return languages.count(language);
  4482. }
  4483. bool cmGeneratorTarget::IsCSharpOnly() const
  4484. {
  4485. // Only certain target types may compile CSharp.
  4486. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4487. this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4488. this->GetType() != cmStateEnums::EXECUTABLE) {
  4489. return false;
  4490. }
  4491. std::set<std::string> languages = this->GetAllConfigCompileLanguages();
  4492. // Consider an explicit linker language property, but *not* the
  4493. // computed linker language that may depend on linked targets.
  4494. cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
  4495. if (cmNonempty(linkLang)) {
  4496. languages.insert(*linkLang);
  4497. }
  4498. return languages.size() == 1 && languages.count("CSharp") > 0;
  4499. }
  4500. bool cmGeneratorTarget::IsDotNetSdkTarget() const
  4501. {
  4502. return !this->GetProperty("DOTNET_SDK").IsEmpty();
  4503. }
  4504. void cmGeneratorTarget::ComputeLinkImplementationLanguages(
  4505. std::string const& config, cmOptionalLinkImplementation& impl) const
  4506. {
  4507. // This target needs runtime libraries for its source languages.
  4508. std::set<std::string> languages;
  4509. // Get languages used in our source files.
  4510. this->GetLanguages(languages, config);
  4511. // Copy the set of languages to the link implementation.
  4512. impl.Languages.insert(impl.Languages.begin(), languages.begin(),
  4513. languages.end());
  4514. }
  4515. bool cmGeneratorTarget::HaveBuildTreeRPATH(std::string const& config) const
  4516. {
  4517. if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
  4518. return false;
  4519. }
  4520. std::string build_rpath;
  4521. if (this->GetBuildRPATH(config, build_rpath)) {
  4522. return true;
  4523. }
  4524. if (cmLinkImplementationLibraries const* impl =
  4525. this->GetLinkImplementationLibraries(config, UseTo::Link)) {
  4526. return !impl->Libraries.empty();
  4527. }
  4528. return false;
  4529. }
  4530. bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
  4531. std::string const& p) const
  4532. {
  4533. return cm::contains(this->LinkImplicitNullProperties, p);
  4534. }
  4535. bool cmGeneratorTarget::ApplyCXXStdTargets()
  4536. {
  4537. cmStandardLevelResolver standardResolver(this->Makefile);
  4538. cmStandardLevel const cxxStd23 =
  4539. *standardResolver.LanguageStandardLevel("CXX", "23");
  4540. std::vector<std::string> const& configs =
  4541. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4542. auto std_prop = this->GetProperty("CXX_MODULE_STD");
  4543. if (!std_prop) {
  4544. // TODO(cxxmodules): Add a target policy to flip the default here. Set
  4545. // `std_prop` based on it.
  4546. return true;
  4547. }
  4548. std::string std_prop_value;
  4549. if (std_prop) {
  4550. // Evaluate generator expressions.
  4551. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  4552. auto cge = ge.Parse(*std_prop);
  4553. if (!cge) {
  4554. this->Makefile->IssueMessage(
  4555. MessageType::FATAL_ERROR,
  4556. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4557. this->GetName(), "\" is not a valid generator expression."));
  4558. return false;
  4559. }
  4560. // But do not allow context-sensitive queries. Whether a target uses
  4561. // `import std` should not depend on configuration or properties of the
  4562. // consumer (head target). The link language also shouldn't matter, so ban
  4563. // it as well.
  4564. if (cge->GetHadHeadSensitiveCondition()) {
  4565. // Not reachable; all target-sensitive genexes actually fail to parse.
  4566. this->Makefile->IssueMessage(
  4567. MessageType::FATAL_ERROR,
  4568. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4569. this->GetName(),
  4570. "\" contains a condition that queries the "
  4571. "consuming target which is not supported."));
  4572. return false;
  4573. }
  4574. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  4575. // Not reachable; all link language genexes actually fail to parse.
  4576. this->Makefile->IssueMessage(
  4577. MessageType::FATAL_ERROR,
  4578. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4579. this->GetName(),
  4580. "\" contains a condition that queries the "
  4581. "link language which is not supported."));
  4582. return false;
  4583. }
  4584. std_prop_value = cge->Evaluate(this->LocalGenerator, "");
  4585. if (cge->GetHadContextSensitiveCondition()) {
  4586. this->Makefile->IssueMessage(
  4587. MessageType::FATAL_ERROR,
  4588. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4589. this->GetName(),
  4590. "\" contains a context-sensitive condition "
  4591. "that is not supported."));
  4592. return false;
  4593. }
  4594. }
  4595. auto use_std = cmIsOn(std_prop_value);
  4596. // If we have a value and it is not true, there's nothing to do.
  4597. if (std_prop && !use_std) {
  4598. return true;
  4599. }
  4600. for (auto const& config : configs) {
  4601. if (this->HaveCxxModuleSupport(config) != Cxx20SupportLevel::Supported) {
  4602. continue;
  4603. }
  4604. cm::optional<cmStandardLevel> explicitLevel =
  4605. this->GetExplicitStandardLevel("CXX", config);
  4606. if (!explicitLevel || *explicitLevel < cxxStd23) {
  4607. continue;
  4608. }
  4609. auto const stdLevel =
  4610. standardResolver.GetLevelString("CXX", *explicitLevel);
  4611. auto const targetName = cmStrCat("__CMAKE::CXX", stdLevel);
  4612. if (!this->Makefile->FindTargetToUse(targetName)) {
  4613. auto basicReason = this->Makefile->GetDefinition(cmStrCat(
  4614. "CMAKE_CXX", stdLevel, "_COMPILER_IMPORT_STD_NOT_FOUND_MESSAGE"));
  4615. std::string reason;
  4616. if (!basicReason.IsEmpty()) {
  4617. reason = cmStrCat(" Reason:\n ", basicReason);
  4618. }
  4619. this->Makefile->IssueMessage(
  4620. MessageType::FATAL_ERROR,
  4621. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4622. this->GetName(), "\" requires that the \"", targetName,
  4623. "\" target exist, but it was not provided by the toolchain.",
  4624. reason));
  4625. break;
  4626. }
  4627. // Check the experimental feature here as well. A toolchain may have
  4628. // provided the target and skipped the check in the toolchain preparation
  4629. // logic.
  4630. if (!cmExperimental::HasSupportEnabled(
  4631. *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
  4632. break;
  4633. }
  4634. this->Target->AppendProperty(
  4635. "LINK_LIBRARIES",
  4636. cmStrCat("$<BUILD_LOCAL_INTERFACE:$<$<CONFIG:", config, ">:", targetName,
  4637. ">>"));
  4638. }
  4639. return true;
  4640. }
  4641. bool cmGeneratorTarget::DiscoverSyntheticTargets(cmSyntheticTargetCache& cache,
  4642. std::string const& config)
  4643. {
  4644. std::vector<std::string> allConfigs =
  4645. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4646. cmOptionalLinkImplementation impl;
  4647. this->ComputeLinkImplementationLibraries(config, impl, UseTo::Link);
  4648. cmCxxModuleUsageEffects usage(this);
  4649. auto& SyntheticDeps = this->Configs[config].SyntheticDeps;
  4650. for (auto const& entry : impl.Libraries) {
  4651. auto const* gt = entry.Target;
  4652. if (!gt || !gt->IsImported()) {
  4653. continue;
  4654. }
  4655. if (gt->HaveCxx20ModuleSources()) {
  4656. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  4657. constexpr size_t HASH_TRUNCATION = 12;
  4658. auto dirhash = hasher.HashString(
  4659. gt->GetLocalGenerator()->GetCurrentBinaryDirectory());
  4660. std::string safeName = gt->GetName();
  4661. cmSystemTools::ReplaceString(safeName, ":", "_");
  4662. auto targetIdent =
  4663. hasher.HashString(cmStrCat("@d_", dirhash, "@u_", usage.GetHash()));
  4664. std::string targetName =
  4665. cmStrCat(safeName, "@synth_", targetIdent.substr(0, HASH_TRUNCATION));
  4666. // Check the cache to see if this instance of the imported target has
  4667. // already been created.
  4668. auto cached = cache.CxxModuleTargets.find(targetName);
  4669. cmGeneratorTarget const* synthDep = nullptr;
  4670. if (cached == cache.CxxModuleTargets.end()) {
  4671. auto const* model = gt->Target;
  4672. auto* mf = gt->Makefile;
  4673. auto* lg = gt->GetLocalGenerator();
  4674. auto* tgt = mf->AddSynthesizedTarget(cmStateEnums::INTERFACE_LIBRARY,
  4675. targetName);
  4676. // Copy relevant information from the existing IMPORTED target.
  4677. // Copy policies to the target.
  4678. tgt->CopyPolicyStatuses(model);
  4679. // Copy file sets.
  4680. {
  4681. auto fsNames = model->GetAllFileSetNames();
  4682. for (auto const& fsName : fsNames) {
  4683. auto const* fs = model->GetFileSet(fsName);
  4684. if (!fs) {
  4685. mf->IssueMessage(MessageType::INTERNAL_ERROR,
  4686. cmStrCat("Failed to find file set named '",
  4687. fsName, "' on target '",
  4688. tgt->GetName(), '\''));
  4689. continue;
  4690. }
  4691. auto* newFs = tgt
  4692. ->GetOrCreateFileSet(fs->GetName(), fs->GetType(),
  4693. fs->GetVisibility())
  4694. .first;
  4695. newFs->CopyEntries(fs);
  4696. }
  4697. }
  4698. // Copy imported C++ module properties.
  4699. tgt->CopyImportedCxxModulesEntries(model);
  4700. // Copy other properties which may affect the C++ module BMI
  4701. // generation.
  4702. tgt->CopyImportedCxxModulesProperties(model);
  4703. tgt->AddLinkLibrary(*mf,
  4704. cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
  4705. GENERAL_LibraryType);
  4706. // Apply usage requirements to the target.
  4707. usage.ApplyToTarget(tgt);
  4708. // Create the generator target and attach it to the local generator.
  4709. auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
  4710. synthDep = gtp.get();
  4711. cache.CxxModuleTargets[targetName] = synthDep;
  4712. // See `localGen->ComputeTargetCompileFeatures()` call in
  4713. // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
  4714. // this.
  4715. for (auto const& innerConfig : allConfigs) {
  4716. gtp->ComputeCompileFeatures(innerConfig);
  4717. }
  4718. // See `cmGlobalGenerator::ApplyCXXStdTargets` in
  4719. // `cmGlobalGenerator::Compute` for non-synthetic target resolutions.
  4720. gtp->ApplyCXXStdTargets();
  4721. gtp->DiscoverSyntheticTargets(cache, config);
  4722. lg->AddGeneratorTarget(std::move(gtp));
  4723. } else {
  4724. synthDep = cached->second;
  4725. }
  4726. SyntheticDeps[gt].push_back(synthDep);
  4727. }
  4728. }
  4729. return true;
  4730. }
  4731. bool cmGeneratorTarget::HasPackageReferences() const
  4732. {
  4733. return this->IsInBuildSystem() &&
  4734. !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
  4735. }
  4736. std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
  4737. {
  4738. cmList packageReferences;
  4739. if (this->IsInBuildSystem()) {
  4740. if (cmValue vsPackageReferences =
  4741. this->GetProperty("VS_PACKAGE_REFERENCES")) {
  4742. packageReferences.assign(*vsPackageReferences);
  4743. }
  4744. }
  4745. return std::move(packageReferences.data());
  4746. }
  4747. std::string cmGeneratorTarget::GetPDBDirectory(std::string const& config) const
  4748. {
  4749. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  4750. // Return the directory in which the target will be built.
  4751. return info->PdbDir;
  4752. }
  4753. return "";
  4754. }
  4755. bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
  4756. {
  4757. return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
  4758. }
  4759. bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
  4760. std::string const& gnuName,
  4761. std::string& out,
  4762. char const* newExt) const
  4763. {
  4764. if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
  4765. gnuName.substr(gnuName.size() - 6) == ".dll.a") {
  4766. out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
  4767. newExt ? newExt : ".lib");
  4768. return true;
  4769. }
  4770. return false;
  4771. }
  4772. bool cmGeneratorTarget::HasContextDependentSources() const
  4773. {
  4774. return this->SourcesAreContextDependent == Tribool::True;
  4775. }
  4776. bool cmGeneratorTarget::IsExecutableWithExports() const
  4777. {
  4778. return this->Target->IsExecutableWithExports();
  4779. }
  4780. bool cmGeneratorTarget::IsSharedLibraryWithExports() const
  4781. {
  4782. return this->Target->IsSharedLibraryWithExports();
  4783. }
  4784. bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
  4785. {
  4786. bool generate_Stubs = true;
  4787. if (this->GetGlobalGenerator()->IsXcode()) {
  4788. // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
  4789. // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
  4790. if (cmValue propGenStubs =
  4791. this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4792. generate_Stubs = propGenStubs == "YES";
  4793. } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
  4794. "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4795. generate_Stubs = varGenStubs == "YES";
  4796. }
  4797. }
  4798. return (this->IsDLLPlatform() &&
  4799. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4800. this->IsExecutableWithExports()) &&
  4801. // Assemblies which have only managed code do not have
  4802. // import libraries.
  4803. this->GetManagedType(config) != ManagedType::Managed) ||
  4804. (this->IsAIX() && this->IsExecutableWithExports()) ||
  4805. (this->Makefile->PlatformSupportsAppleTextStubs() &&
  4806. this->IsSharedLibraryWithExports() && generate_Stubs);
  4807. }
  4808. bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
  4809. {
  4810. return this->HasImportLibrary(config) ||
  4811. // On DLL platforms we always generate the import library name
  4812. // just in case the sources have export markup.
  4813. (this->IsDLLPlatform() &&
  4814. (this->GetType() == cmStateEnums::EXECUTABLE ||
  4815. this->GetType() == cmStateEnums::MODULE_LIBRARY));
  4816. }
  4817. bool cmGeneratorTarget::GetUseShortObjectNames(
  4818. cmStateEnums::IntermediateDirKind kind) const
  4819. {
  4820. return this->LocalGenerator->UseShortObjectNames(kind);
  4821. }
  4822. cmObjectLocations::UseShortPath
  4823. cmGeneratorTarget::GetUseShortObjectNamesForInstall() const
  4824. {
  4825. auto prop = this->Target->GetProperty("INSTALL_OBJECT_NAME_STRATEGY");
  4826. if (prop == "SHORT"_s) {
  4827. return cmObjectLocations::UseShortPath::Yes;
  4828. }
  4829. if (prop == "FULL"_s) {
  4830. return cmObjectLocations::UseShortPath::No;
  4831. }
  4832. if (prop.IsSet()) {
  4833. this->Makefile->IssueMessage(
  4834. MessageType::FATAL_ERROR,
  4835. cmStrCat("Property INSTALL_OBJECT_NAME_STRATEGY of target \"",
  4836. this->GetName(), "\" set to the unsupported strategy ", prop));
  4837. }
  4838. return cmObjectLocations::UseShortPath::No;
  4839. }
  4840. std::string cmGeneratorTarget::GetSupportDirectory(
  4841. cmStateEnums::IntermediateDirKind kind) const
  4842. {
  4843. cmLocalGenerator* lg = this->GetLocalGenerator();
  4844. return cmStrCat(lg->GetObjectOutputRoot(kind), '/',
  4845. lg->GetTargetDirectory(this, kind));
  4846. }
  4847. std::string cmGeneratorTarget::GetCMFSupportDirectory(
  4848. cmStateEnums::IntermediateDirKind kind) const
  4849. {
  4850. cmLocalGenerator* lg = this->GetLocalGenerator();
  4851. if (!lg->AlwaysUsesCMFPaths()) {
  4852. return cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  4853. lg->GetTargetDirectory(this, kind));
  4854. }
  4855. return cmStrCat(lg->GetObjectOutputRoot(kind), '/',
  4856. lg->GetTargetDirectory(this, kind));
  4857. }
  4858. bool cmGeneratorTarget::IsLinkable() const
  4859. {
  4860. return (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4861. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4862. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  4863. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY ||
  4864. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4865. this->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  4866. this->IsExecutableWithExports());
  4867. }
  4868. bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
  4869. {
  4870. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  4871. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4872. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  4873. return false;
  4874. }
  4875. if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
  4876. // Do not use the linker dependency file because it includes shared
  4877. // libraries as well
  4878. return false;
  4879. }
  4880. std::string const depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
  4881. auto linkLanguage = this->GetLinkerLanguage(config);
  4882. std::string const langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
  4883. "_LINK_DEPENDS_USE_LINKER") };
  4884. return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
  4885. this->Makefile->IsOn(depsUseLinker)) &&
  4886. this->Makefile->IsOn(langDepsUseLinker);
  4887. }
  4888. bool cmGeneratorTarget::IsFrameworkOnApple() const
  4889. {
  4890. return this->Target->IsFrameworkOnApple();
  4891. }
  4892. bool cmGeneratorTarget::IsArchivedAIXSharedLibrary() const
  4893. {
  4894. return this->Target->IsArchivedAIXSharedLibrary();
  4895. }
  4896. bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
  4897. std::string const& config) const
  4898. {
  4899. if (this->IsApple() && this->IsImported() &&
  4900. (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4901. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4902. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) {
  4903. std::string cfg = config;
  4904. if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
  4905. // FIXME(#25515): Remove the need for this workaround.
  4906. // The Xcode generator queries include directories without any
  4907. // specific configuration. Pick one in case this target does
  4908. // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
  4909. cfg =
  4910. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
  4911. }
  4912. return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
  4913. }
  4914. return false;
  4915. }
  4916. bool cmGeneratorTarget::IsAppBundleOnApple() const
  4917. {
  4918. return this->Target->IsAppBundleOnApple();
  4919. }
  4920. bool cmGeneratorTarget::IsXCTestOnApple() const
  4921. {
  4922. return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
  4923. }
  4924. bool cmGeneratorTarget::IsCFBundleOnApple() const
  4925. {
  4926. return (this->GetType() == cmStateEnums::MODULE_LIBRARY && this->IsApple() &&
  4927. this->GetPropertyAsBool("BUNDLE"));
  4928. }
  4929. cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
  4930. std::string const& propval) const
  4931. {
  4932. // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
  4933. // or only C++/CLI) does only depend on whether the property is an empty
  4934. // string or contains any value at all. In Visual Studio generators
  4935. // this propval is prepended with /clr[:] which results in:
  4936. //
  4937. // 1. propval does not exist: no /clr flag, unmanaged target, has import
  4938. // lib
  4939. // 2. empty propval: add /clr as flag, mixed unmanaged/managed
  4940. // target, has import lib
  4941. // 3. netcore propval: add /clr:netcore as flag, mixed
  4942. // unmanaged/managed target, has import lib.
  4943. // 4. any value (safe,pure): add /clr:[propval] as flag, target with
  4944. // managed code only, no import lib
  4945. if (propval.empty() || propval == "netcore") {
  4946. return ManagedType::Mixed;
  4947. }
  4948. return ManagedType::Managed;
  4949. }
  4950. cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
  4951. std::string const& config) const
  4952. {
  4953. // Only libraries and executables can be managed targets.
  4954. if (this->GetType() > cmStateEnums::SHARED_LIBRARY) {
  4955. return ManagedType::Undefined;
  4956. }
  4957. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4958. return ManagedType::Native;
  4959. }
  4960. // Check imported target.
  4961. if (this->IsImported()) {
  4962. if (cmGeneratorTarget::ImportInfo const* info =
  4963. this->GetImportInfo(config)) {
  4964. return info->Managed;
  4965. }
  4966. return ManagedType::Undefined;
  4967. }
  4968. // Check for explicitly set clr target property.
  4969. if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  4970. return this->CheckManagedType(*clr);
  4971. }
  4972. // C# targets are always managed. This language specific check
  4973. // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
  4974. // has to be set manually for C# targets.
  4975. return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
  4976. }
  4977. bool cmGeneratorTarget::AddHeaderSetVerification()
  4978. {
  4979. if (!this->GetPropertyAsBool("VERIFY_INTERFACE_HEADER_SETS")) {
  4980. return true;
  4981. }
  4982. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4983. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4984. this->GetType() != cmStateEnums::UNKNOWN_LIBRARY &&
  4985. this->GetType() != cmStateEnums::OBJECT_LIBRARY &&
  4986. this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4987. !this->IsExecutableWithExports()) {
  4988. return true;
  4989. }
  4990. auto verifyValue = this->GetProperty("INTERFACE_HEADER_SETS_TO_VERIFY");
  4991. bool const all = verifyValue.IsEmpty();
  4992. std::set<std::string> verifySet;
  4993. if (!all) {
  4994. cmList verifyList{ verifyValue };
  4995. verifySet.insert(verifyList.begin(), verifyList.end());
  4996. }
  4997. cmTarget* verifyTarget = nullptr;
  4998. cmTarget* allVerifyTarget =
  4999. this->GlobalGenerator->GetMakefiles().front()->FindTargetToUse(
  5000. "all_verify_interface_header_sets",
  5001. { cmStateEnums::TargetDomain::NATIVE });
  5002. auto interfaceFileSetEntries = this->Target->GetInterfaceHeaderSetsEntries();
  5003. std::set<cmFileSet*> fileSets;
  5004. for (auto const& entry : interfaceFileSetEntries) {
  5005. for (auto const& name : cmList{ entry.Value }) {
  5006. if (all || verifySet.count(name)) {
  5007. fileSets.insert(this->Target->GetFileSet(name));
  5008. verifySet.erase(name);
  5009. }
  5010. }
  5011. }
  5012. if (!verifySet.empty()) {
  5013. this->Makefile->IssueMessage(
  5014. MessageType::FATAL_ERROR,
  5015. cmStrCat("Property INTERFACE_HEADER_SETS_TO_VERIFY of target \"",
  5016. this->GetName(),
  5017. "\" contained the following header sets that are nonexistent "
  5018. "or not INTERFACE:\n ",
  5019. cmJoin(verifySet, "\n ")));
  5020. return false;
  5021. }
  5022. cm::optional<std::set<std::string>> languages;
  5023. for (auto* fileSet : fileSets) {
  5024. auto dirCges = fileSet->CompileDirectoryEntries();
  5025. auto fileCges = fileSet->CompileFileEntries();
  5026. static auto const contextSensitive =
  5027. [](std::unique_ptr<cmCompiledGeneratorExpression> const& cge) {
  5028. return cge->GetHadContextSensitiveCondition();
  5029. };
  5030. bool dirCgesContextSensitive = false;
  5031. bool fileCgesContextSensitive = false;
  5032. std::vector<std::string> dirs;
  5033. std::map<std::string, std::vector<std::string>> filesPerDir;
  5034. bool first = true;
  5035. for (auto const& config : this->Makefile->GetGeneratorConfigs(
  5036. cmMakefile::GeneratorConfigQuery::IncludeEmptyConfig)) {
  5037. cm::GenEx::Context context(this->LocalGenerator, config);
  5038. if (first || dirCgesContextSensitive) {
  5039. dirs = fileSet->EvaluateDirectoryEntries(dirCges, context, this);
  5040. dirCgesContextSensitive =
  5041. std::any_of(dirCges.begin(), dirCges.end(), contextSensitive);
  5042. }
  5043. if (first || fileCgesContextSensitive) {
  5044. filesPerDir.clear();
  5045. for (auto const& fileCge : fileCges) {
  5046. fileSet->EvaluateFileEntry(dirs, filesPerDir, fileCge, context,
  5047. this);
  5048. if (fileCge->GetHadContextSensitiveCondition()) {
  5049. fileCgesContextSensitive = true;
  5050. }
  5051. }
  5052. }
  5053. for (auto const& files : filesPerDir) {
  5054. for (auto const& file : files.second) {
  5055. std::string filename = this->GenerateHeaderSetVerificationFile(
  5056. *this->Makefile->GetOrCreateSource(file), files.first, languages);
  5057. if (filename.empty()) {
  5058. continue;
  5059. }
  5060. if (!verifyTarget) {
  5061. {
  5062. cmMakefile::PolicyPushPop polScope(this->Makefile);
  5063. this->Makefile->SetPolicy(cmPolicies::CMP0119, cmPolicies::NEW);
  5064. verifyTarget = this->Makefile->AddLibrary(
  5065. cmStrCat(this->GetName(), "_verify_interface_header_sets"),
  5066. cmStateEnums::OBJECT_LIBRARY, {}, true);
  5067. }
  5068. verifyTarget->AddLinkLibrary(
  5069. *this->Makefile, this->GetName(),
  5070. cmTargetLinkLibraryType::GENERAL_LibraryType);
  5071. verifyTarget->SetProperty("AUTOMOC", "OFF");
  5072. verifyTarget->SetProperty("AUTORCC", "OFF");
  5073. verifyTarget->SetProperty("AUTOUIC", "OFF");
  5074. verifyTarget->SetProperty("DISABLE_PRECOMPILE_HEADERS", "ON");
  5075. verifyTarget->SetProperty("UNITY_BUILD", "OFF");
  5076. verifyTarget->SetProperty("CXX_SCAN_FOR_MODULES", "OFF");
  5077. verifyTarget->FinalizeTargetConfiguration(
  5078. this->Makefile->GetCompileDefinitionsEntries());
  5079. if (!allVerifyTarget) {
  5080. allVerifyTarget = this->GlobalGenerator->GetMakefiles()
  5081. .front()
  5082. ->AddNewUtilityTarget(
  5083. "all_verify_interface_header_sets", true);
  5084. }
  5085. allVerifyTarget->AddUtility(verifyTarget->GetName(), false);
  5086. }
  5087. if (fileCgesContextSensitive) {
  5088. filename = cmStrCat("$<$<CONFIG:", config, ">:", filename, '>');
  5089. }
  5090. verifyTarget->AddSource(filename);
  5091. }
  5092. }
  5093. if (!dirCgesContextSensitive && !fileCgesContextSensitive) {
  5094. break;
  5095. }
  5096. first = false;
  5097. }
  5098. }
  5099. if (verifyTarget) {
  5100. this->LocalGenerator->AddGeneratorTarget(
  5101. cm::make_unique<cmGeneratorTarget>(verifyTarget, this->LocalGenerator));
  5102. }
  5103. return true;
  5104. }
  5105. std::string cmGeneratorTarget::GenerateHeaderSetVerificationFile(
  5106. cmSourceFile& source, std::string const& dir,
  5107. cm::optional<std::set<std::string>>& languages) const
  5108. {
  5109. std::string extension;
  5110. std::string language = source.GetOrDetermineLanguage();
  5111. if (source.GetPropertyAsBool("SKIP_LINTING")) {
  5112. return std::string{};
  5113. }
  5114. if (language.empty()) {
  5115. if (!languages) {
  5116. languages.emplace();
  5117. for (auto const& tgtSource : this->GetAllConfigSources()) {
  5118. auto const& tgtSourceLanguage =
  5119. tgtSource.Source->GetOrDetermineLanguage();
  5120. if (tgtSourceLanguage == "CXX") {
  5121. languages->insert("CXX");
  5122. break; // C++ overrides everything else, so we don't need to keep
  5123. // checking.
  5124. }
  5125. if (tgtSourceLanguage == "C") {
  5126. languages->insert("C");
  5127. }
  5128. }
  5129. if (languages->empty()) {
  5130. std::vector<std::string> languagesVector;
  5131. this->GlobalGenerator->GetEnabledLanguages(languagesVector);
  5132. languages->insert(languagesVector.begin(), languagesVector.end());
  5133. }
  5134. }
  5135. if (languages->count("CXX")) {
  5136. language = "CXX";
  5137. } else if (languages->count("C")) {
  5138. language = "C";
  5139. }
  5140. }
  5141. if (language == "C") {
  5142. extension = ".c";
  5143. } else if (language == "CXX") {
  5144. extension = ".cxx";
  5145. } else {
  5146. return "";
  5147. }
  5148. std::string headerFilename = dir;
  5149. if (!headerFilename.empty()) {
  5150. headerFilename += '/';
  5151. }
  5152. headerFilename += source.GetLocation().GetName();
  5153. auto filename = cmStrCat(
  5154. this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->GetName(),
  5155. "_verify_interface_header_sets/", headerFilename, extension);
  5156. auto* verificationSource = this->Makefile->GetOrCreateSource(filename);
  5157. source.SetSpecialSourceType(
  5158. cmSourceFile::SpecialSourceType::HeaderSetVerificationSource);
  5159. verificationSource->SetProperty("LANGUAGE", language);
  5160. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(filename));
  5161. cmGeneratedFileStream fout(filename);
  5162. fout.SetCopyIfDifferent(true);
  5163. // The IWYU "associated" pragma tells include-what-you-use to
  5164. // consider the headerFile as part of the entire language
  5165. // unit within include-what-you-use and as a result allows
  5166. // one to get IWYU advice for headers.
  5167. // Also suppress clang-tidy include checks in generated code.
  5168. fout
  5169. << "/* NOLINTNEXTLINE(misc-header-include-cycle,misc-include-cleaner) */\n"
  5170. << "#include <" << headerFilename << "> /* IWYU pragma: associated */\n";
  5171. fout.close();
  5172. return filename;
  5173. }
  5174. std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
  5175. std::string const& config) const
  5176. {
  5177. if (!(this->IsApple() && this->IsImported() &&
  5178. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  5179. this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  5180. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY))) {
  5181. return {};
  5182. }
  5183. std::string desiredConfig = config;
  5184. if (config.empty()) {
  5185. desiredConfig = "NOCONFIG";
  5186. }
  5187. std::string result;
  5188. cmValue loc = nullptr;
  5189. cmValue imp = nullptr;
  5190. std::string suffix;
  5191. if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
  5192. if (loc) {
  5193. result = *loc;
  5194. } else {
  5195. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  5196. if (cmValue configLocation = this->GetProperty(impProp)) {
  5197. result = *configLocation;
  5198. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  5199. result = *location;
  5200. }
  5201. }
  5202. if (cmSystemTools::IsPathToXcFramework(result)) {
  5203. return result;
  5204. }
  5205. }
  5206. return {};
  5207. }
  5208. bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
  5209. {
  5210. auto sources = this->GetSourceFiles(config);
  5211. bool const have_direct = std::any_of(
  5212. sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
  5213. return sf.Value->GetLanguage() == "Fortran"_s;
  5214. });
  5215. bool have_via_target_objects = false;
  5216. if (!have_direct) {
  5217. auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
  5218. have_via_target_objects =
  5219. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  5220. [&config](cmGeneratorTarget const* tgt) -> bool {
  5221. return tgt->HaveFortranSources(config);
  5222. });
  5223. }
  5224. return have_direct || have_via_target_objects;
  5225. }
  5226. bool cmGeneratorTarget::HaveFortranSources() const
  5227. {
  5228. auto sources = this->GetAllConfigSources();
  5229. bool const have_direct = std::any_of(
  5230. sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
  5231. return sf.Source->GetLanguage() == "Fortran"_s;
  5232. });
  5233. bool have_via_target_objects = false;
  5234. if (!have_direct) {
  5235. std::vector<std::string> configs =
  5236. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  5237. for (auto const& config : configs) {
  5238. auto const sourceObjectLibraries =
  5239. this->GetSourceObjectLibraries(config);
  5240. have_via_target_objects =
  5241. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  5242. [&config](cmGeneratorTarget const* tgt) -> bool {
  5243. return tgt->HaveFortranSources(config);
  5244. });
  5245. if (have_via_target_objects) {
  5246. break;
  5247. }
  5248. }
  5249. }
  5250. return have_direct || have_via_target_objects;
  5251. }
  5252. bool cmGeneratorTarget::HaveCxx20ModuleSources(std::string* errorMessage) const
  5253. {
  5254. auto const& fs_names = this->Target->GetAllFileSetNames();
  5255. return std::any_of(
  5256. fs_names.begin(), fs_names.end(),
  5257. [this, errorMessage](std::string const& name) -> bool {
  5258. auto const* file_set = this->Target->GetFileSet(name);
  5259. if (!file_set) {
  5260. auto message = cmStrCat("Target \"", this->Target->GetName(),
  5261. "\" is tracked to have file set \"", name,
  5262. "\", but it was not found.");
  5263. if (errorMessage) {
  5264. *errorMessage = std::move(message);
  5265. } else {
  5266. this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
  5267. }
  5268. return false;
  5269. }
  5270. auto const& fs_type = file_set->GetType();
  5271. return fs_type == "CXX_MODULES"_s;
  5272. });
  5273. }
  5274. cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
  5275. std::string const& config) const
  5276. {
  5277. auto const* state = this->Makefile->GetState();
  5278. if (!state->GetLanguageEnabled("CXX")) {
  5279. return Cxx20SupportLevel::MissingCxx;
  5280. }
  5281. cmValue standardDefault =
  5282. this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  5283. if (!standardDefault || standardDefault->empty()) {
  5284. // We do not know any meaningful C++ standard levels for this compiler.
  5285. return Cxx20SupportLevel::NoCxx20;
  5286. }
  5287. cmStandardLevelResolver standardResolver(this->Makefile);
  5288. cmStandardLevel const cxxStd20 =
  5289. *standardResolver.LanguageStandardLevel("CXX", "20");
  5290. cm::optional<cmStandardLevel> explicitLevel =
  5291. this->GetExplicitStandardLevel("CXX", config);
  5292. if (!explicitLevel || *explicitLevel < cxxStd20) {
  5293. return Cxx20SupportLevel::NoCxx20;
  5294. }
  5295. cmValue scandepRule =
  5296. this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
  5297. if (!scandepRule) {
  5298. return Cxx20SupportLevel::MissingRule;
  5299. }
  5300. return Cxx20SupportLevel::Supported;
  5301. }
  5302. void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
  5303. {
  5304. bool haveScannableSources = false;
  5305. // Check for `CXX_MODULE*` file sets and a lack of support.
  5306. if (this->HaveCxx20ModuleSources()) {
  5307. haveScannableSources = true;
  5308. }
  5309. if (!haveScannableSources) {
  5310. // Check to see if there are regular sources that have requested scanning.
  5311. auto sources = this->GetSourceFiles(config);
  5312. for (auto const& source : sources) {
  5313. auto const* sf = source.Value;
  5314. auto const& lang = sf->GetLanguage();
  5315. if (lang != "CXX"_s) {
  5316. continue;
  5317. }
  5318. // Ignore sources which do not need dyndep.
  5319. if (this->NeedDyndepForSource(lang, config, sf)) {
  5320. haveScannableSources = true;
  5321. }
  5322. }
  5323. }
  5324. // If there isn't anything scannable, ignore it.
  5325. if (!haveScannableSources) {
  5326. return;
  5327. }
  5328. // If the generator doesn't support modules at all, error that we have
  5329. // sources that require the support.
  5330. if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5331. cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
  5332. this->Makefile->IssueMessage(
  5333. MessageType::FATAL_ERROR,
  5334. cmStrCat("The target named \"", this->GetName(),
  5335. "\" has C++ sources that may use modules, but modules are not "
  5336. "supported by this generator:\n ",
  5337. this->GetGlobalGenerator()->GetName(),
  5338. "\n"
  5339. "Modules are supported only by Ninja, Ninja Multi-Config, "
  5340. "and Visual Studio generators for VS 17.4 and newer. "
  5341. "See the cmake-cxxmodules(7) manual for details. "
  5342. "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
  5343. "disable scanning."));
  5344. return;
  5345. }
  5346. switch (this->HaveCxxModuleSupport(config)) {
  5347. case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
  5348. this->Makefile->IssueMessage(
  5349. MessageType::FATAL_ERROR,
  5350. cmStrCat("The target named \"", this->GetName(),
  5351. "\" has C++ sources that use modules, but the \"CXX\" "
  5352. "language has not been enabled."));
  5353. break;
  5354. case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
  5355. cmStandardLevelResolver standardResolver(this->Makefile);
  5356. auto effStandard =
  5357. standardResolver.GetEffectiveStandard(this, "CXX", config);
  5358. if (effStandard.empty()) {
  5359. effStandard = "; no C++ standard found";
  5360. } else {
  5361. effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
  5362. }
  5363. this->Makefile->IssueMessage(
  5364. MessageType::FATAL_ERROR,
  5365. cmStrCat(
  5366. "The target named \"", this->GetName(),
  5367. "\" has C++ sources that use modules, but does not include "
  5368. "\"cxx_std_20\" (or newer) among its `target_compile_features`",
  5369. effStandard, '.'));
  5370. } break;
  5371. case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
  5372. this->Makefile->IssueMessage(
  5373. MessageType::FATAL_ERROR,
  5374. cmStrCat("The target named \"", this->GetName(),
  5375. "\" has C++ sources that may use modules, but the compiler "
  5376. "does not provide a way to discover the import graph "
  5377. "dependencies. See the cmake-cxxmodules(7) manual for "
  5378. "details. Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
  5379. "enable or disable scanning."));
  5380. } break;
  5381. case cmGeneratorTarget::Cxx20SupportLevel::Supported:
  5382. // All is well.
  5383. break;
  5384. }
  5385. }
  5386. bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
  5387. std::string const& config) const
  5388. {
  5389. if (lang != "CXX"_s) {
  5390. return false;
  5391. }
  5392. return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
  5393. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5394. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5395. }
  5396. bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
  5397. std::string const& config) const
  5398. {
  5399. return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
  5400. }
  5401. cmFileSet const* cmGeneratorTarget::GetFileSetForSource(
  5402. std::string const& config, cmSourceFile const* sf) const
  5403. {
  5404. this->BuildFileSetInfoCache(config);
  5405. auto const& path = sf->GetFullPath();
  5406. auto const& per_config = this->Configs[config];
  5407. auto const fsit = per_config.FileSetCache.find(path);
  5408. if (fsit == per_config.FileSetCache.end()) {
  5409. return nullptr;
  5410. }
  5411. return fsit->second;
  5412. }
  5413. bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
  5414. std::string const& config,
  5415. cmSourceFile const* sf) const
  5416. {
  5417. // Fortran always needs to be scanned.
  5418. if (lang == "Fortran"_s) {
  5419. return true;
  5420. }
  5421. // Only C++ code needs scanned otherwise.
  5422. if (lang != "CXX"_s) {
  5423. return false;
  5424. }
  5425. // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
  5426. // enforced elsewhere).
  5427. auto const* fs = this->GetFileSetForSource(config, sf);
  5428. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  5429. return true;
  5430. }
  5431. auto targetDyndep = this->NeedCxxDyndep(config);
  5432. if (targetDyndep == CxxModuleSupport::Unavailable) {
  5433. return false;
  5434. }
  5435. auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
  5436. if (sfProp.IsSet()) {
  5437. return sfProp.IsOn();
  5438. }
  5439. return targetDyndep == CxxModuleSupport::Enabled;
  5440. }
  5441. cmGeneratorTarget::CxxModuleSupport cmGeneratorTarget::NeedCxxDyndep(
  5442. std::string const& config) const
  5443. {
  5444. bool haveRule = false;
  5445. switch (this->HaveCxxModuleSupport(config)) {
  5446. case Cxx20SupportLevel::MissingCxx:
  5447. case Cxx20SupportLevel::NoCxx20:
  5448. return CxxModuleSupport::Unavailable;
  5449. case Cxx20SupportLevel::MissingRule:
  5450. break;
  5451. case Cxx20SupportLevel::Supported:
  5452. haveRule = true;
  5453. break;
  5454. }
  5455. bool haveGeneratorSupport =
  5456. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5457. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5458. auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
  5459. if (tgtProp.IsSet()) {
  5460. return tgtProp.IsOn() ? CxxModuleSupport::Enabled
  5461. : CxxModuleSupport::Disabled;
  5462. }
  5463. CxxModuleSupport policyAnswer = CxxModuleSupport::Unavailable;
  5464. switch (this->GetPolicyStatusCMP0155()) {
  5465. case cmPolicies::WARN:
  5466. case cmPolicies::OLD:
  5467. // The OLD behavior is to not scan the source.
  5468. policyAnswer = CxxModuleSupport::Disabled;
  5469. break;
  5470. case cmPolicies::NEW:
  5471. // The NEW behavior is to scan the source if the compiler supports
  5472. // scanning and the generator supports it.
  5473. if (haveRule && haveGeneratorSupport) {
  5474. policyAnswer = CxxModuleSupport::Enabled;
  5475. } else {
  5476. policyAnswer = CxxModuleSupport::Disabled;
  5477. }
  5478. break;
  5479. }
  5480. return policyAnswer;
  5481. }
  5482. std::string cmGeneratorTarget::BuildDatabasePath(
  5483. std::string const& lang, std::string const& config) const
  5484. {
  5485. // Check to see if the target wants it.
  5486. if (!this->GetPropertyAsBool("EXPORT_BUILD_DATABASE")) {
  5487. return {};
  5488. }
  5489. if (!cmExperimental::HasSupportEnabled(
  5490. *this->Makefile, cmExperimental::Feature::ExportBuildDatabase)) {
  5491. return {};
  5492. }
  5493. // Check to see if the generator supports it.
  5494. if (!this->GetGlobalGenerator()->SupportsBuildDatabase()) {
  5495. return {};
  5496. }
  5497. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  5498. return cmStrCat(this->GetSupportDirectory(), '/', config, '/', lang,
  5499. "_build_database.json");
  5500. }
  5501. return cmStrCat(this->GetSupportDirectory(), '/', lang,
  5502. "_build_database.json");
  5503. }
  5504. void cmGeneratorTarget::BuildFileSetInfoCache(std::string const& config) const
  5505. {
  5506. auto& per_config = this->Configs[config];
  5507. if (per_config.BuiltFileSetCache) {
  5508. return;
  5509. }
  5510. auto const* tgt = this->Target;
  5511. for (auto const& name : tgt->GetAllFileSetNames()) {
  5512. auto const* file_set = tgt->GetFileSet(name);
  5513. if (!file_set) {
  5514. tgt->GetMakefile()->IssueMessage(
  5515. MessageType::INTERNAL_ERROR,
  5516. cmStrCat("Target \"", tgt->GetName(),
  5517. "\" is tracked to have file set \"", name,
  5518. "\", but it was not found."));
  5519. continue;
  5520. }
  5521. cm::GenEx::Context context(this->LocalGenerator, config);
  5522. auto fileEntries = file_set->CompileFileEntries();
  5523. auto directoryEntries = file_set->CompileDirectoryEntries();
  5524. auto directories =
  5525. file_set->EvaluateDirectoryEntries(directoryEntries, context, this);
  5526. std::map<std::string, std::vector<std::string>> files;
  5527. for (auto const& entry : fileEntries) {
  5528. file_set->EvaluateFileEntry(directories, files, entry, context, this);
  5529. }
  5530. for (auto const& it : files) {
  5531. for (auto const& filename : it.second) {
  5532. auto collapsedFile = cmSystemTools::CollapseFullPath(filename);
  5533. per_config.FileSetCache[collapsedFile] = file_set;
  5534. }
  5535. }
  5536. }
  5537. per_config.BuiltFileSetCache = true;
  5538. }
  5539. std::string cmGeneratorTarget::GetSwiftModuleName() const
  5540. {
  5541. return this->GetPropertyOrDefault("Swift_MODULE_NAME", this->GetName());
  5542. }
  5543. std::string cmGeneratorTarget::GetSwiftModuleFileName() const
  5544. {
  5545. std::string moduleFilename = this->GetPropertyOrDefault(
  5546. "Swift_MODULE", this->GetSwiftModuleName() + ".swiftmodule");
  5547. if (this->GetPolicyStatusCMP0195() == cmPolicies::NEW) {
  5548. if (cmValue moduleTriple =
  5549. this->Makefile->GetDefinition("CMAKE_Swift_MODULE_TRIPLE")) {
  5550. moduleFilename += "/" + *moduleTriple + ".swiftmodule";
  5551. }
  5552. }
  5553. return moduleFilename;
  5554. }
  5555. std::string cmGeneratorTarget::GetSwiftModuleDirectory(
  5556. std::string const& config) const
  5557. {
  5558. // This is like the *_OUTPUT_DIRECTORY properties except that we don't have a
  5559. // separate per-configuration target property.
  5560. //
  5561. // The property expands generator expressions. Multi-config generators append
  5562. // a per-configuration subdirectory to the specified directory unless a
  5563. // generator expression is used.
  5564. bool appendConfigDir = true;
  5565. std::string moduleDirectory;
  5566. if (cmValue value = this->GetProperty("Swift_MODULE_DIRECTORY")) {
  5567. moduleDirectory = cmGeneratorExpression::Evaluate(
  5568. *value, this->LocalGenerator, config, this);
  5569. appendConfigDir = *value == moduleDirectory;
  5570. }
  5571. if (moduleDirectory.empty()) {
  5572. moduleDirectory = this->LocalGenerator->GetCurrentBinaryDirectory();
  5573. }
  5574. if (appendConfigDir) {
  5575. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  5576. "/", config, "", moduleDirectory);
  5577. }
  5578. return moduleDirectory;
  5579. }
  5580. std::string cmGeneratorTarget::GetSwiftModulePath(
  5581. std::string const& config) const
  5582. {
  5583. return this->GetSwiftModuleDirectory(config) + "/" +
  5584. this->GetSwiftModuleFileName();
  5585. }
  5586. std::string cmGeneratorTarget::GetPropertyOrDefault(
  5587. std::string const& property, std::string defaultValue) const
  5588. {
  5589. if (cmValue name = this->GetProperty(property)) {
  5590. return *name;
  5591. }
  5592. return defaultValue;
  5593. }