cmGeneratorTarget.cxx 196 KB

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