cmGeneratorTarget.cxx 197 KB

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