cmGeneratorTarget.cxx 178 KB

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