cmGeneratorTarget.cxx 205 KB

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