cmGeneratorTarget.cxx 178 KB

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