cmGeneratorTarget.cxx 196 KB

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