cmGeneratorTarget.cxx 206 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324
  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. cmList const& cmGeneratorTarget::GetSharedLibraryCompileDefs(
  1632. std::string const& config) const
  1633. {
  1634. {
  1635. auto it = this->SharedLibraryCompileDefs.find(config);
  1636. if (it != this->SharedLibraryCompileDefs.end()) {
  1637. return it->second;
  1638. }
  1639. }
  1640. auto emplaceResult =
  1641. this->SharedLibraryCompileDefs.emplace(config, cmList{});
  1642. auto& defs = emplaceResult.first->second;
  1643. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1644. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1645. return defs;
  1646. }
  1647. if (this->GetPolicyStatusCMP0203() != cmPolicies::NEW) {
  1648. return defs;
  1649. }
  1650. auto linkerLang = this->GetLinkerLanguage(config);
  1651. auto definitionVar =
  1652. cmStrCat("CMAKE_", linkerLang, "_SHARED_LIBRARY_COMPILE_DEFINITIONS");
  1653. defs = this->Makefile->GetSafeDefinition(definitionVar);
  1654. return defs;
  1655. }
  1656. cmGeneratorTarget::NameComponents const&
  1657. cmGeneratorTarget::GetFullNameComponents(
  1658. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1659. {
  1660. return this->GetFullNameInternalComponents(config, artifact);
  1661. }
  1662. std::string cmGeneratorTarget::BuildBundleDirectory(
  1663. std::string const& base, std::string const& config,
  1664. BundleDirectoryLevel level) const
  1665. {
  1666. std::string fpath = base;
  1667. if (this->IsAppBundleOnApple()) {
  1668. fpath += this->GetAppBundleDirectory(config, level);
  1669. }
  1670. if (this->IsFrameworkOnApple()) {
  1671. fpath += this->GetFrameworkDirectory(config, level);
  1672. }
  1673. if (this->IsCFBundleOnApple()) {
  1674. fpath += this->GetCFBundleDirectory(config, level);
  1675. }
  1676. return fpath;
  1677. }
  1678. std::string cmGeneratorTarget::GetMacContentDirectory(
  1679. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1680. {
  1681. // Start with the output directory for the target.
  1682. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  1683. BundleDirectoryLevel level = ContentLevel;
  1684. if (this->IsFrameworkOnApple()) {
  1685. // additional files with a framework go into the version specific
  1686. // directory
  1687. level = FullLevel;
  1688. }
  1689. fpath = this->BuildBundleDirectory(fpath, config, level);
  1690. return fpath;
  1691. }
  1692. std::string cmGeneratorTarget::GetEffectiveFolderName() const
  1693. {
  1694. std::string effectiveFolder;
  1695. if (!this->GlobalGenerator->UseFolderProperty()) {
  1696. return effectiveFolder;
  1697. }
  1698. cmValue targetFolder = this->GetProperty("FOLDER");
  1699. if (targetFolder) {
  1700. effectiveFolder += *targetFolder;
  1701. }
  1702. return effectiveFolder;
  1703. }
  1704. cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
  1705. std::string const& config) const
  1706. {
  1707. // There is no compile information for imported targets.
  1708. if (this->IsImported()) {
  1709. return nullptr;
  1710. }
  1711. if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  1712. std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ",
  1713. this->GetName(), " which has type ",
  1714. cmState::GetTargetTypeName(this->GetType()));
  1715. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  1716. return nullptr;
  1717. }
  1718. // Lookup/compute/cache the compile information for this configuration.
  1719. std::string config_upper;
  1720. if (!config.empty()) {
  1721. config_upper = cmSystemTools::UpperCase(config);
  1722. }
  1723. auto i = this->CompileInfoMap.find(config_upper);
  1724. if (i == this->CompileInfoMap.end()) {
  1725. CompileInfo info;
  1726. this->ComputePDBOutputDir("COMPILE_PDB", config, info.CompilePdbDir);
  1727. CompileInfoMapType::value_type entry(config_upper, info);
  1728. i = this->CompileInfoMap.insert(entry).first;
  1729. }
  1730. return &i->second;
  1731. }
  1732. cmGeneratorTarget::ModuleDefinitionInfo const*
  1733. cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
  1734. {
  1735. // A module definition file only makes sense on certain target types.
  1736. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1737. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1738. !this->IsExecutableWithExports()) {
  1739. return nullptr;
  1740. }
  1741. // Lookup/compute/cache the compile information for this configuration.
  1742. std::string config_upper;
  1743. if (!config.empty()) {
  1744. config_upper = cmSystemTools::UpperCase(config);
  1745. }
  1746. auto i = this->ModuleDefinitionInfoMap.find(config_upper);
  1747. if (i == this->ModuleDefinitionInfoMap.end()) {
  1748. ModuleDefinitionInfo info;
  1749. this->ComputeModuleDefinitionInfo(config, info);
  1750. ModuleDefinitionInfoMapType::value_type entry(config_upper, info);
  1751. i = this->ModuleDefinitionInfoMap.insert(entry).first;
  1752. }
  1753. return &i->second;
  1754. }
  1755. void cmGeneratorTarget::ComputeModuleDefinitionInfo(
  1756. std::string const& config, ModuleDefinitionInfo& info) const
  1757. {
  1758. this->GetModuleDefinitionSources(info.Sources, config);
  1759. info.WindowsExportAllSymbols =
  1760. this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  1761. this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS");
  1762. #if !defined(CMAKE_BOOTSTRAP)
  1763. info.DefFileGenerated =
  1764. info.WindowsExportAllSymbols || info.Sources.size() > 1;
  1765. #else
  1766. // Our __create_def helper is not available during CMake bootstrap.
  1767. info.DefFileGenerated = false;
  1768. #endif
  1769. if (info.DefFileGenerated) {
  1770. info.DefFile =
  1771. this->GetObjectDirectory(config) /* has slash */ + "exports.def";
  1772. } else if (!info.Sources.empty()) {
  1773. info.DefFile = info.Sources.front()->GetFullPath();
  1774. }
  1775. }
  1776. bool cmGeneratorTarget::IsAIX() const
  1777. {
  1778. return this->Target->IsAIX();
  1779. }
  1780. bool cmGeneratorTarget::IsApple() const
  1781. {
  1782. return this->Target->IsApple();
  1783. }
  1784. bool cmGeneratorTarget::IsDLLPlatform() const
  1785. {
  1786. return this->Target->IsDLLPlatform();
  1787. }
  1788. void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
  1789. std::string const& config) const
  1790. {
  1791. char const* prop =
  1792. this->GetLinkInterfaceDependentStringProperty("AUTOUIC_OPTIONS", config);
  1793. if (!prop) {
  1794. return;
  1795. }
  1796. cm::GenEx::Context context(this->LocalGenerator, config);
  1797. cmGeneratorExpressionDAGChecker dagChecker{
  1798. this, "AUTOUIC_OPTIONS", nullptr, nullptr, context,
  1799. };
  1800. cmExpandList(cmGeneratorExpression::Evaluate(
  1801. prop, context.LG, context.Config, this, &dagChecker),
  1802. result);
  1803. }
  1804. void cmGeneratorTarget::TraceDependencies()
  1805. {
  1806. // CMake-generated targets have no dependencies to trace. Normally tracing
  1807. // would find nothing anyway, but when building CMake itself the "install"
  1808. // target command ends up referencing the "cmake" target but we do not
  1809. // really want the dependency because "install" depend on "all" anyway.
  1810. if (this->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1811. return;
  1812. }
  1813. // Use a helper object to trace the dependencies.
  1814. cmTargetTraceDependencies tracer(this);
  1815. tracer.Trace();
  1816. }
  1817. std::string cmGeneratorTarget::GetCompilePDBDirectory(
  1818. std::string const& config) const
  1819. {
  1820. if (CompileInfo const* info = this->GetCompileInfo(config)) {
  1821. return info->CompilePdbDir;
  1822. }
  1823. return "";
  1824. }
  1825. std::vector<std::string> cmGeneratorTarget::GetAppleArchs(
  1826. std::string const& config, cm::optional<std::string> lang) const
  1827. {
  1828. cmList archList;
  1829. if (!this->IsApple()) {
  1830. return std::move(archList.data());
  1831. }
  1832. cmValue archs = nullptr;
  1833. if (!config.empty()) {
  1834. std::string defVarName =
  1835. cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config));
  1836. archs = this->GetProperty(defVarName);
  1837. }
  1838. if (!archs) {
  1839. archs = this->GetProperty("OSX_ARCHITECTURES");
  1840. }
  1841. if (archs) {
  1842. archList.assign(*archs);
  1843. }
  1844. if (archList.empty() &&
  1845. // Fall back to a default architecture if no compiler target is set.
  1846. (!lang ||
  1847. this->Makefile
  1848. ->GetDefinition(cmStrCat("CMAKE_", *lang, "_COMPILER_TARGET"))
  1849. .IsEmpty())) {
  1850. archList.assign(
  1851. this->Makefile->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  1852. }
  1853. return std::move(archList.data());
  1854. }
  1855. namespace {
  1856. bool IsSupportedClassifiedFlagsLanguage(std::string const& lang)
  1857. {
  1858. return lang == "CXX"_s;
  1859. }
  1860. bool CanUseCompilerLauncher(std::string const& lang)
  1861. {
  1862. // Also found in `cmCommonTargetGenerator::GetCompilerLauncher`.
  1863. return lang == "C"_s || lang == "CXX"_s || lang == "Fortran"_s ||
  1864. lang == "CUDA"_s || lang == "HIP"_s || lang == "ISPC"_s ||
  1865. lang == "OBJC"_s || lang == "OBJCXX"_s;
  1866. }
  1867. // FIXME: return a vector of `cm::string_view` instead to avoid lots of tiny
  1868. // allocations.
  1869. std::vector<std::string> SplitFlags(std::string const& flags)
  1870. {
  1871. std::vector<std::string> options;
  1872. #ifdef _WIN32
  1873. cmSystemTools::ParseWindowsCommandLine(flags.c_str(), options);
  1874. #else
  1875. cmSystemTools::ParseUnixCommandLine(flags.c_str(), options);
  1876. #endif
  1877. return options;
  1878. }
  1879. }
  1880. cmGeneratorTarget::ClassifiedFlags
  1881. cmGeneratorTarget::GetClassifiedFlagsForSource(cmSourceFile const* sf,
  1882. std::string const& config)
  1883. {
  1884. auto& sourceFlagsCache = this->Configs[config].SourceFlags;
  1885. auto cacheEntry = sourceFlagsCache.lower_bound(sf);
  1886. if (cacheEntry != sourceFlagsCache.end() && cacheEntry->first == sf) {
  1887. return cacheEntry->second;
  1888. }
  1889. ClassifiedFlags flags;
  1890. std::string const& lang = sf->GetLanguage();
  1891. if (!IsSupportedClassifiedFlagsLanguage(lang)) {
  1892. return flags;
  1893. }
  1894. auto* const lg = this->GetLocalGenerator();
  1895. auto const* const mf = this->Makefile;
  1896. // Compute the compiler launcher flags.
  1897. if (CanUseCompilerLauncher(lang)) {
  1898. // Compiler launchers are all execution flags and should not be relevant to
  1899. // the actual compilation.
  1900. FlagClassification cls = FlagClassification::ExecutionFlag;
  1901. FlagKind kind = FlagKind::NotAFlag;
  1902. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  1903. cmValue clauncher = this->GetProperty(clauncher_prop);
  1904. std::string const evaluatedClauncher = cmGeneratorExpression::Evaluate(
  1905. *clauncher, lg, config, this, nullptr, this, lang);
  1906. for (auto const& flag : SplitFlags(evaluatedClauncher)) {
  1907. flags.emplace_back(cls, kind, flag);
  1908. }
  1909. }
  1910. ClassifiedFlags define_flags;
  1911. ClassifiedFlags include_flags;
  1912. ClassifiedFlags compile_flags;
  1913. SourceVariables sfVars = this->GetSourceVariables(sf, config);
  1914. // Compute language flags.
  1915. {
  1916. FlagClassification cls = FlagClassification::BaselineFlag;
  1917. FlagKind kind = FlagKind::Compile;
  1918. std::string mfFlags;
  1919. // Explicitly add the explicit language flag before any other flag
  1920. // so user flags can override it.
  1921. this->AddExplicitLanguageFlags(mfFlags, *sf);
  1922. for (auto const& flag : SplitFlags(mfFlags)) {
  1923. flags.emplace_back(cls, kind, flag);
  1924. }
  1925. }
  1926. std::unordered_map<std::string, std::string> pchSources;
  1927. std::string filterArch;
  1928. {
  1929. std::vector<std::string> pchArchs = this->GetPchArchs(config, lang);
  1930. for (std::string const& arch : pchArchs) {
  1931. std::string const pchSource = this->GetPchSource(config, lang, arch);
  1932. if (pchSource == sf->GetFullPath()) {
  1933. filterArch = arch;
  1934. }
  1935. if (!pchSource.empty()) {
  1936. pchSources.insert(std::make_pair(pchSource, arch));
  1937. }
  1938. }
  1939. }
  1940. // Compute target-wide flags.
  1941. {
  1942. FlagClassification cls = FlagClassification::BaselineFlag;
  1943. // Compile flags
  1944. {
  1945. FlagKind kind = FlagKind::Compile;
  1946. std::string targetFlags;
  1947. lg->GetTargetCompileFlags(this, config, lang, targetFlags, filterArch);
  1948. for (auto&& flag : SplitFlags(targetFlags)) {
  1949. compile_flags.emplace_back(cls, kind, std::move(flag));
  1950. }
  1951. }
  1952. // Define flags
  1953. {
  1954. FlagKind kind = FlagKind::Definition;
  1955. std::set<std::string> defines;
  1956. lg->GetTargetDefines(this, config, lang, defines);
  1957. std::string defineFlags;
  1958. lg->JoinDefines(defines, defineFlags, lang);
  1959. for (auto&& flag : SplitFlags(defineFlags)) {
  1960. define_flags.emplace_back(cls, kind, std::move(flag));
  1961. }
  1962. }
  1963. // Include flags
  1964. {
  1965. FlagKind kind = FlagKind::Include;
  1966. std::vector<std::string> includes;
  1967. lg->GetIncludeDirectories(includes, this, lang, config);
  1968. auto includeFlags =
  1969. lg->GetIncludeFlags(includes, this, lang, config, false);
  1970. for (auto&& flag : SplitFlags(includeFlags)) {
  1971. include_flags.emplace_back(cls, kind, std::move(flag));
  1972. }
  1973. }
  1974. }
  1975. std::string const COMPILE_FLAGS("COMPILE_FLAGS");
  1976. std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
  1977. cmGeneratorExpressionInterpreter genexInterpreter(lg, config, this, lang);
  1978. // Source-specific flags.
  1979. {
  1980. FlagClassification cls = FlagClassification::PrivateFlag;
  1981. FlagKind kind = FlagKind::Compile;
  1982. std::string sourceFlags;
  1983. if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
  1984. lg->AppendFlags(sourceFlags,
  1985. genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  1986. }
  1987. if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  1988. lg->AppendCompileOptions(
  1989. sourceFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  1990. }
  1991. for (auto&& flag : SplitFlags(sourceFlags)) {
  1992. compile_flags.emplace_back(cls, kind, std::move(flag));
  1993. }
  1994. // Dependency tracking flags.
  1995. {
  1996. if (!sfVars.DependencyFlags.empty()) {
  1997. cmRulePlaceholderExpander::RuleVariables vars;
  1998. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  1999. vars.DependencyFile = sfVars.DependencyFile.c_str();
  2000. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  2001. std::string depfileFlags = sfVars.DependencyFlags;
  2002. rulePlaceholderExpander->ExpandRuleVariables(lg, depfileFlags, vars);
  2003. for (auto&& flag : SplitFlags(depfileFlags)) {
  2004. compile_flags.emplace_back(FlagClassification::LocationFlag,
  2005. FlagKind::BuildSystem, std::move(flag));
  2006. }
  2007. }
  2008. }
  2009. }
  2010. // Precompiled headers.
  2011. {
  2012. FlagClassification cls = FlagClassification::PrivateFlag;
  2013. FlagKind kind = FlagKind::Compile;
  2014. std::string pchFlags;
  2015. // Add precompile headers compile options.
  2016. if (!sf->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  2017. if (!pchSources.empty()) {
  2018. std::string pchOptions;
  2019. auto pchIt = pchSources.find(sf->GetFullPath());
  2020. if (pchIt != pchSources.end()) {
  2021. pchOptions =
  2022. this->GetPchCreateCompileOptions(config, lang, pchIt->second);
  2023. } else {
  2024. pchOptions = this->GetPchUseCompileOptions(config, lang);
  2025. }
  2026. this->LocalGenerator->AppendCompileOptions(
  2027. pchFlags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  2028. }
  2029. }
  2030. for (auto&& flag : SplitFlags(pchFlags)) {
  2031. compile_flags.emplace_back(cls, kind, std::move(flag));
  2032. }
  2033. }
  2034. // C++ module flags.
  2035. if (lang == "CXX"_s) {
  2036. FlagClassification cls = FlagClassification::LocationFlag;
  2037. FlagKind kind = FlagKind::BuildSystem;
  2038. std::string bmiFlags;
  2039. auto const* fs = this->GetFileSetForSource(config, sf);
  2040. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  2041. if (lang != "CXX"_s) {
  2042. mf->IssueMessage(
  2043. MessageType::FATAL_ERROR,
  2044. cmStrCat(
  2045. "Target \"", this->Target->GetName(), "\" contains the source\n ",
  2046. sf->GetFullPath(), "\nin a file set of type \"", fs->GetType(),
  2047. R"(" but the source is not classified as a "CXX" source.)"));
  2048. }
  2049. if (!this->Target->IsNormal()) {
  2050. auto flag = mf->GetSafeDefinition("CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  2051. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2052. compileObjectVars.Object = sfVars.ObjectFileDir.c_str();
  2053. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2054. rulePlaceholderExpander->ExpandRuleVariables(lg, flag,
  2055. compileObjectVars);
  2056. lg->AppendCompileOptions(bmiFlags, flag);
  2057. }
  2058. }
  2059. for (auto&& flag : SplitFlags(bmiFlags)) {
  2060. compile_flags.emplace_back(cls, kind, std::move(flag));
  2061. }
  2062. }
  2063. cmRulePlaceholderExpander::RuleVariables vars;
  2064. vars.CMTargetName = this->GetName().c_str();
  2065. vars.CMTargetType = cmState::GetTargetTypeName(this->GetType()).c_str();
  2066. vars.Language = lang.c_str();
  2067. auto const sfPath = this->LocalGenerator->ConvertToOutputFormat(
  2068. sf->GetFullPath(), cmOutputConverter::SHELL);
  2069. // Compute the base compiler command line. We'll find placeholders and
  2070. // replace them with arguments later in this function.
  2071. {
  2072. FlagClassification cls = FlagClassification::ExecutionFlag;
  2073. FlagKind kind = FlagKind::NotAFlag;
  2074. std::string const cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  2075. std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
  2076. cmList compileCmds(compileCmd); // FIXME: which command to use?
  2077. std::string& cmd = compileCmds[0];
  2078. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2079. static std::string const PlaceholderDefines = "__CMAKE_DEFINES";
  2080. static std::string const PlaceholderIncludes = "__CMAKE_INCLUDES";
  2081. static std::string const PlaceholderFlags = "__CMAKE_FLAGS";
  2082. static std::string const PlaceholderSource = "__CMAKE_SOURCE";
  2083. vars.Defines = PlaceholderDefines.c_str();
  2084. vars.Includes = PlaceholderIncludes.c_str();
  2085. vars.TargetPDB = sfVars.TargetPDB.c_str();
  2086. vars.TargetCompilePDB = sfVars.TargetCompilePDB.c_str();
  2087. vars.Object = sfVars.ObjectFileDir.c_str();
  2088. vars.ObjectDir = sfVars.ObjectDir.c_str();
  2089. vars.ObjectFileDir = sfVars.ObjectFileDir.c_str();
  2090. vars.TargetSupportDir = sfVars.TargetSupportDir.c_str();
  2091. vars.Flags = PlaceholderFlags.c_str();
  2092. vars.DependencyFile = sfVars.DependencyFile.c_str();
  2093. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  2094. vars.Source = PlaceholderSource.c_str();
  2095. rulePlaceholderExpander->ExpandRuleVariables(lg, cmd, vars);
  2096. for (auto&& flag : SplitFlags(cmd)) {
  2097. if (flag == PlaceholderDefines) {
  2098. flags.insert(flags.end(), define_flags.begin(), define_flags.end());
  2099. } else if (flag == PlaceholderIncludes) {
  2100. flags.insert(flags.end(), include_flags.begin(), include_flags.end());
  2101. } else if (flag == PlaceholderFlags) {
  2102. flags.insert(flags.end(), compile_flags.begin(), compile_flags.end());
  2103. } else if (flag == PlaceholderSource) {
  2104. flags.emplace_back(FlagClassification::LocationFlag,
  2105. FlagKind::BuildSystem, sfPath);
  2106. } else {
  2107. flags.emplace_back(cls, kind, std::move(flag));
  2108. // All remaining flags here are build system flags.
  2109. kind = FlagKind::BuildSystem;
  2110. }
  2111. }
  2112. }
  2113. cacheEntry = sourceFlagsCache.emplace_hint(cacheEntry, sf, std::move(flags));
  2114. return cacheEntry->second;
  2115. }
  2116. cmGeneratorTarget::SourceVariables cmGeneratorTarget::GetSourceVariables(
  2117. cmSourceFile const* sf, std::string const& config)
  2118. {
  2119. SourceVariables vars;
  2120. auto const language = sf->GetLanguage();
  2121. auto const targetType = this->GetType();
  2122. auto const* const lg = this->GetLocalGenerator();
  2123. auto const* const gg = this->GetGlobalGenerator();
  2124. auto const* const mf = this->Makefile;
  2125. // PDB settings.
  2126. {
  2127. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  2128. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  2129. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  2130. std::string pdbPath;
  2131. std::string compilePdbPath;
  2132. if (targetType <= cmStateEnums::OBJECT_LIBRARY) {
  2133. compilePdbPath = this->GetCompilePDBPath(config);
  2134. if (compilePdbPath.empty()) {
  2135. // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
  2136. // A trailing slash tells the toolchain to add its default file name.
  2137. compilePdbPath = this->GetSupportDirectory();
  2138. if (gg->IsMultiConfig()) {
  2139. compilePdbPath = cmStrCat(compilePdbPath, '/', config);
  2140. }
  2141. compilePdbPath += '/';
  2142. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  2143. // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
  2144. compilePdbPath = cmStrCat(compilePdbPath, this->GetName(), ".pdb");
  2145. }
  2146. }
  2147. }
  2148. if (targetType == cmStateEnums::EXECUTABLE ||
  2149. targetType == cmStateEnums::STATIC_LIBRARY ||
  2150. targetType == cmStateEnums::SHARED_LIBRARY ||
  2151. targetType == cmStateEnums::MODULE_LIBRARY) {
  2152. pdbPath = cmStrCat(this->GetPDBDirectory(config), '/',
  2153. this->GetPDBName(config));
  2154. }
  2155. vars.TargetPDB = lg->ConvertToOutputFormat(
  2156. gg->ConvertToOutputPath(std::move(pdbPath)), cmOutputConverter::SHELL);
  2157. vars.TargetCompilePDB = lg->ConvertToOutputFormat(
  2158. gg->ConvertToOutputPath(std::move(compilePdbPath)),
  2159. cmOutputConverter::SHELL);
  2160. }
  2161. }
  2162. // Object settings.
  2163. {
  2164. std::string const targetSupportDir = lg->MaybeRelativeToTopBinDir(
  2165. gg->ConvertToOutputPath(this->GetCMFSupportDirectory()));
  2166. std::string const objectDir = gg->ConvertToOutputPath(
  2167. cmStrCat(this->GetSupportDirectory(), gg->GetConfigDirectory(config)));
  2168. std::string const objectFileName = this->GetObjectName(sf);
  2169. std::string const objectFilePath =
  2170. cmStrCat(objectDir, '/', objectFileName);
  2171. vars.TargetSupportDir =
  2172. lg->ConvertToOutputFormat(targetSupportDir, cmOutputConverter::SHELL);
  2173. vars.ObjectDir =
  2174. lg->ConvertToOutputFormat(objectDir, cmOutputConverter::SHELL);
  2175. vars.ObjectFileDir =
  2176. lg->ConvertToOutputFormat(objectFilePath, cmOutputConverter::SHELL);
  2177. // Dependency settings.
  2178. {
  2179. std::string const depfileFormatName =
  2180. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT");
  2181. std::string const depfileFormat =
  2182. mf->GetSafeDefinition(depfileFormatName);
  2183. if (depfileFormat != "msvc"_s) {
  2184. std::string const flagsName =
  2185. cmStrCat("CMAKE_DEPFILE_FLAGS_", language);
  2186. std::string const depfileFlags = mf->GetSafeDefinition(flagsName);
  2187. if (!depfileFlags.empty()) {
  2188. bool replaceExt = false;
  2189. if (!language.empty()) {
  2190. std::string const repVar =
  2191. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  2192. replaceExt = mf->IsOn(repVar);
  2193. }
  2194. std::string const depfilePath = cmStrCat(
  2195. objectDir, '/',
  2196. replaceExt
  2197. ? cmSystemTools::GetFilenameWithoutLastExtension(objectFileName)
  2198. : objectFileName,
  2199. ".d");
  2200. vars.DependencyFlags = depfileFlags;
  2201. vars.DependencyTarget = vars.ObjectFileDir;
  2202. vars.DependencyFile =
  2203. lg->ConvertToOutputFormat(depfilePath, cmOutputConverter::SHELL);
  2204. }
  2205. }
  2206. }
  2207. }
  2208. return vars;
  2209. }
  2210. void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
  2211. cmSourceFile const& sf) const
  2212. {
  2213. cmValue lang = sf.GetProperty("LANGUAGE");
  2214. if (!lang) {
  2215. return;
  2216. }
  2217. switch (this->GetPolicyStatusCMP0119()) {
  2218. case cmPolicies::WARN:
  2219. CM_FALLTHROUGH;
  2220. case cmPolicies::OLD:
  2221. // The OLD behavior is to not add explicit language flags.
  2222. return;
  2223. case cmPolicies::NEW:
  2224. // The NEW behavior is to add explicit language flags.
  2225. break;
  2226. }
  2227. this->LocalGenerator->AppendFeatureOptions(flags, *lang,
  2228. "EXPLICIT_LANGUAGE");
  2229. }
  2230. void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
  2231. std::string const& config,
  2232. std::string& flags) const
  2233. {
  2234. std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
  2235. if (arch.empty()) {
  2236. switch (this->GetPolicyStatusCMP0104()) {
  2237. case cmPolicies::WARN:
  2238. if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
  2239. this->Makefile->IssueMessage(
  2240. MessageType::AUTHOR_WARNING,
  2241. cmPolicies::GetPolicyWarning(cmPolicies::CMP0104) +
  2242. "\nCUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2243. "\".");
  2244. }
  2245. CM_FALLTHROUGH;
  2246. case cmPolicies::OLD:
  2247. break;
  2248. default:
  2249. this->Makefile->IssueMessage(
  2250. MessageType::FATAL_ERROR,
  2251. "CUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2252. "\".");
  2253. }
  2254. }
  2255. // If CUDA_ARCHITECTURES is false we don't add any architectures.
  2256. if (cmIsOff(arch)) {
  2257. return;
  2258. }
  2259. this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
  2260. std::move(arch), flags);
  2261. }
  2262. void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
  2263. std::string const& config,
  2264. std::string const& lang,
  2265. std::string arch,
  2266. std::string& flags) const
  2267. {
  2268. std::string const& compiler = this->Makefile->GetSafeDefinition(
  2269. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2270. bool const ipoEnabled = this->IsIPOEnabled(lang, config);
  2271. // Check for special modes: `all`, `all-major`.
  2272. if (arch == "all" || arch == "all-major") {
  2273. if (compiler == "NVIDIA" &&
  2274. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2275. this->Makefile->GetDefinition(cmStrCat(
  2276. "CMAKE_", lang, "_COMPILER_VERSION")),
  2277. "11.5")) {
  2278. flags = cmStrCat(flags, " -arch=", arch);
  2279. return;
  2280. }
  2281. if (arch == "all") {
  2282. arch = *this->Makefile->GetDefinition(
  2283. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
  2284. } else if (arch == "all-major") {
  2285. arch = *this->Makefile->GetDefinition(
  2286. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
  2287. }
  2288. } else if (arch == "native") {
  2289. cmValue native = this->Makefile->GetDefinition(
  2290. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
  2291. if (native.IsEmpty()) {
  2292. this->Makefile->IssueMessage(
  2293. MessageType::FATAL_ERROR,
  2294. cmStrCat(lang,
  2295. "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
  2296. "detected."));
  2297. }
  2298. if (compiler == "NVIDIA" &&
  2299. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2300. this->Makefile->GetDefinition(cmStrCat(
  2301. "CMAKE_", lang, "_COMPILER_VERSION")),
  2302. "11.6")) {
  2303. flags = cmStrCat(flags, " -arch=", arch);
  2304. return;
  2305. }
  2306. arch = *native;
  2307. }
  2308. struct CudaArchitecture
  2309. {
  2310. std::string name;
  2311. bool real{ true };
  2312. bool virtual_{ true };
  2313. };
  2314. std::vector<CudaArchitecture> architectures;
  2315. {
  2316. cmList options(arch);
  2317. for (auto& option : options) {
  2318. CudaArchitecture architecture;
  2319. // Architecture name is up to the first specifier.
  2320. std::size_t pos = option.find_first_of('-');
  2321. architecture.name = option.substr(0, pos);
  2322. if (pos != std::string::npos) {
  2323. cm::string_view specifier{ option.c_str() + pos + 1,
  2324. option.length() - pos - 1 };
  2325. if (specifier == "real") {
  2326. architecture.real = true;
  2327. architecture.virtual_ = false;
  2328. } else if (specifier == "virtual") {
  2329. architecture.real = false;
  2330. architecture.virtual_ = true;
  2331. } else {
  2332. this->Makefile->IssueMessage(
  2333. MessageType::FATAL_ERROR,
  2334. "Unknown CUDA architecture specifier \"" + std::string(specifier) +
  2335. "\".");
  2336. }
  2337. }
  2338. architectures.emplace_back(architecture);
  2339. }
  2340. }
  2341. if (compiler == "NVIDIA") {
  2342. if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
  2343. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  2344. cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
  2345. flags += *cudaIPOFlags;
  2346. }
  2347. }
  2348. for (CudaArchitecture& architecture : architectures) {
  2349. flags +=
  2350. " \"--generate-code=arch=compute_" + architecture.name + ",code=[";
  2351. if (architecture.virtual_) {
  2352. flags += "compute_" + architecture.name;
  2353. if (ipoEnabled || architecture.real) {
  2354. flags += ",";
  2355. }
  2356. }
  2357. if (ipoEnabled) {
  2358. if (compileOrLink == cmBuildStep::Compile) {
  2359. flags += "lto_" + architecture.name;
  2360. } else if (compileOrLink == cmBuildStep::Link) {
  2361. flags += "sm_" + architecture.name;
  2362. }
  2363. } else if (architecture.real) {
  2364. flags += "sm_" + architecture.name;
  2365. }
  2366. flags += "]\"";
  2367. }
  2368. } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
  2369. for (CudaArchitecture& architecture : architectures) {
  2370. flags += " --cuda-gpu-arch=sm_" + architecture.name;
  2371. if (!architecture.real) {
  2372. this->Makefile->IssueMessage(
  2373. MessageType::WARNING,
  2374. "Clang doesn't support disabling CUDA real code generation.");
  2375. }
  2376. if (!architecture.virtual_) {
  2377. flags += " --no-cuda-include-ptx=sm_" + architecture.name;
  2378. }
  2379. }
  2380. }
  2381. }
  2382. void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
  2383. {
  2384. std::string const& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  2385. // If ISPC_TARGET is false we don't add any architectures.
  2386. if (cmIsOff(arch)) {
  2387. return;
  2388. }
  2389. std::string const& compiler =
  2390. this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
  2391. if (compiler == "Intel") {
  2392. cmList targets(arch);
  2393. if (!targets.empty()) {
  2394. flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
  2395. }
  2396. }
  2397. }
  2398. void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
  2399. std::string const& config,
  2400. std::string& flags) const
  2401. {
  2402. std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
  2403. if (arch.empty()) {
  2404. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  2405. "HIP_ARCHITECTURES is empty for target \"" +
  2406. this->GetName() + "\".");
  2407. }
  2408. // If HIP_ARCHITECTURES is false we don't add any architectures.
  2409. if (cmIsOff(arch)) {
  2410. return;
  2411. }
  2412. if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
  2413. this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
  2414. std::move(arch), flags);
  2415. return;
  2416. }
  2417. cmList options(arch);
  2418. for (std::string& option : options) {
  2419. flags += " --offload-arch=" + option;
  2420. }
  2421. }
  2422. void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
  2423. {
  2424. std::string const& compiler =
  2425. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  2426. if (compiler == "Clang") {
  2427. // Pass CUDA toolkit explicitly to Clang.
  2428. // Clang's searching for the system CUDA toolkit isn't very good and it's
  2429. // expected the user will explicitly pass the toolkit path.
  2430. // This also avoids Clang having to search for the toolkit on every
  2431. // invocation.
  2432. std::string toolkitRoot =
  2433. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
  2434. if (!toolkitRoot.empty()) {
  2435. flags += " --cuda-path=" +
  2436. this->LocalGenerator->ConvertToOutputFormat(toolkitRoot,
  2437. cmOutputConverter::SHELL);
  2438. }
  2439. }
  2440. }
  2441. //----------------------------------------------------------------------------
  2442. std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
  2443. std::string const& var, std::string const& lang,
  2444. std::string const& config) const
  2445. {
  2446. if (this->IsIPOEnabled(lang, config)) {
  2447. std::string varIPO = var + "_IPO";
  2448. if (this->Makefile->IsDefinitionSet(varIPO)) {
  2449. return varIPO;
  2450. }
  2451. }
  2452. return var;
  2453. }
  2454. //----------------------------------------------------------------------------
  2455. std::string cmGeneratorTarget::GetCreateRuleVariable(
  2456. std::string const& lang, std::string const& config) const
  2457. {
  2458. switch (this->GetType()) {
  2459. case cmStateEnums::STATIC_LIBRARY: {
  2460. std::string var = "CMAKE_" + lang + "_CREATE_STATIC_LIBRARY";
  2461. return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
  2462. }
  2463. case cmStateEnums::SHARED_LIBRARY:
  2464. if (this->IsArchivedAIXSharedLibrary()) {
  2465. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY_ARCHIVE";
  2466. }
  2467. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY";
  2468. case cmStateEnums::MODULE_LIBRARY:
  2469. return "CMAKE_" + lang + "_CREATE_SHARED_MODULE";
  2470. case cmStateEnums::EXECUTABLE:
  2471. if (this->IsExecutableWithExports()) {
  2472. std::string linkExeWithExports =
  2473. "CMAKE_" + lang + "_LINK_EXECUTABLE_WITH_EXPORTS";
  2474. if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
  2475. return linkExeWithExports;
  2476. }
  2477. }
  2478. return "CMAKE_" + lang + "_LINK_EXECUTABLE";
  2479. default:
  2480. break;
  2481. }
  2482. return "";
  2483. }
  2484. //----------------------------------------------------------------------------
  2485. std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
  2486. std::string const& lang) const
  2487. {
  2488. cmValue val =
  2489. this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
  2490. if (!cmNonempty(val)) {
  2491. return {};
  2492. }
  2493. std::string path = *val;
  2494. if (!cmSystemTools::FileIsFullPath(path)) {
  2495. path =
  2496. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
  2497. }
  2498. return cmSystemTools::CollapseFullPath(path);
  2499. }
  2500. struct CycleWatcher
  2501. {
  2502. CycleWatcher(bool& flag)
  2503. : Flag(flag)
  2504. {
  2505. this->Flag = true;
  2506. }
  2507. ~CycleWatcher() { this->Flag = false; }
  2508. bool& Flag;
  2509. };
  2510. cmGeneratorTarget const* cmGeneratorTarget::GetPchReuseTarget() const
  2511. {
  2512. if (this->ComputingPchReuse) {
  2513. // TODO: Get the full cycle.
  2514. if (!this->PchReuseCycleDetected) {
  2515. this->Makefile->IssueMessage(
  2516. MessageType::FATAL_ERROR,
  2517. cmStrCat("Circular PCH reuse target involving '", this->GetName(),
  2518. '\''));
  2519. }
  2520. this->PchReuseCycleDetected = true;
  2521. return nullptr;
  2522. }
  2523. CycleWatcher watch(this->ComputingPchReuse);
  2524. (void)watch;
  2525. cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2526. if (!pchReuseFrom) {
  2527. return nullptr;
  2528. }
  2529. cmGeneratorTarget const* generatorTarget =
  2530. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2531. if (!generatorTarget) {
  2532. this->Makefile->IssueMessage(
  2533. MessageType::FATAL_ERROR,
  2534. cmStrCat(
  2535. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2536. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
  2537. }
  2538. if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
  2539. this->Makefile->IssueMessage(
  2540. MessageType::FATAL_ERROR,
  2541. cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
  2542. this->GetName(), "\")\n"));
  2543. }
  2544. if (generatorTarget) {
  2545. if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2546. this->Makefile->IssueMessage(
  2547. MessageType::FATAL_ERROR,
  2548. cmStrCat(
  2549. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2550. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS".)"));
  2551. return nullptr;
  2552. }
  2553. if (auto const* recurseReuseTarget =
  2554. generatorTarget->GetPchReuseTarget()) {
  2555. return recurseReuseTarget;
  2556. }
  2557. }
  2558. return generatorTarget;
  2559. }
  2560. cmGeneratorTarget* cmGeneratorTarget::GetPchReuseTarget()
  2561. {
  2562. if (this->ComputingPchReuse) {
  2563. // TODO: Get the full cycle.
  2564. if (!this->PchReuseCycleDetected) {
  2565. this->Makefile->IssueMessage(
  2566. MessageType::FATAL_ERROR,
  2567. cmStrCat("Circular PCH reuse target involving '", this->GetName(),
  2568. '\''));
  2569. }
  2570. this->PchReuseCycleDetected = true;
  2571. return nullptr;
  2572. }
  2573. CycleWatcher watch(this->ComputingPchReuse);
  2574. (void)watch;
  2575. cmValue pchReuseFrom = this->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2576. if (!pchReuseFrom) {
  2577. return nullptr;
  2578. }
  2579. cmGeneratorTarget* generatorTarget =
  2580. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2581. if (!generatorTarget) {
  2582. this->Makefile->IssueMessage(
  2583. MessageType::FATAL_ERROR,
  2584. cmStrCat(
  2585. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2586. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property does not exist.)"));
  2587. }
  2588. if (this->GetProperty("PRECOMPILE_HEADERS").IsOn()) {
  2589. this->Makefile->IssueMessage(
  2590. MessageType::FATAL_ERROR,
  2591. cmStrCat("PRECOMPILE_HEADERS property is already set on target (\"",
  2592. this->GetName(), "\")\n"));
  2593. }
  2594. if (generatorTarget) {
  2595. if (generatorTarget->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2596. this->Makefile->IssueMessage(
  2597. MessageType::FATAL_ERROR,
  2598. cmStrCat(
  2599. "Target \"", *pchReuseFrom, "\" for the \"", this->GetName(),
  2600. R"(" target's "PRECOMPILE_HEADERS_REUSE_FROM" property has set "DISABLE_PRECOMPILE_HEADERS".)"));
  2601. return nullptr;
  2602. }
  2603. if (auto* recurseReuseTarget = generatorTarget->GetPchReuseTarget()) {
  2604. return recurseReuseTarget;
  2605. }
  2606. }
  2607. return generatorTarget;
  2608. }
  2609. std::vector<std::string> cmGeneratorTarget::GetPchArchs(
  2610. std::string const& config, std::string const& lang) const
  2611. {
  2612. std::vector<std::string> pchArchs;
  2613. if (!this->GetGlobalGenerator()->IsXcode()) {
  2614. pchArchs = this->GetAppleArchs(config, lang);
  2615. }
  2616. if (pchArchs.size() < 2) {
  2617. // We do not need per-arch PCH files when building for one architecture.
  2618. pchArchs = { {} };
  2619. }
  2620. return pchArchs;
  2621. }
  2622. std::string cmGeneratorTarget::GetPchHeader(std::string const& config,
  2623. std::string const& language,
  2624. std::string const& arch) const
  2625. {
  2626. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2627. language != "OBJCXX") {
  2628. return std::string();
  2629. }
  2630. if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2631. return std::string();
  2632. }
  2633. cmGeneratorTarget const* generatorTarget = this;
  2634. cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
  2635. bool const haveReuseTarget = reuseTarget && reuseTarget != this;
  2636. if (reuseTarget) {
  2637. generatorTarget = reuseTarget;
  2638. }
  2639. auto const inserted =
  2640. this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
  2641. if (inserted.second) {
  2642. std::vector<BT<std::string>> const headers =
  2643. this->GetPrecompileHeaders(config, language);
  2644. if (headers.empty() && !haveReuseTarget) {
  2645. return std::string();
  2646. }
  2647. std::string& filename = inserted.first->second;
  2648. std::map<std::string, std::string> const languageToExtension = {
  2649. { "C", ".h" },
  2650. { "CXX", ".hxx" },
  2651. { "OBJC", ".objc.h" },
  2652. { "OBJCXX", ".objcxx.hxx" }
  2653. };
  2654. filename = generatorTarget->GetCMFSupportDirectory();
  2655. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2656. filename = cmStrCat(filename, '/', config);
  2657. }
  2658. // This is acceptable as its the source file, won't have a rename/hash
  2659. filename =
  2660. cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat('_', arch),
  2661. languageToExtension.at(language));
  2662. std::string const filename_tmp = cmStrCat(filename, ".tmp");
  2663. if (!haveReuseTarget) {
  2664. cmValue pchPrologue =
  2665. this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
  2666. cmValue pchEpilogue =
  2667. this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
  2668. std::string firstHeaderOnDisk;
  2669. {
  2670. cmGeneratedFileStream file(
  2671. filename_tmp, false,
  2672. this->GetGlobalGenerator()->GetMakefileEncoding());
  2673. file << "/* generated by CMake */\n\n";
  2674. if (pchPrologue) {
  2675. file << *pchPrologue << "\n";
  2676. }
  2677. if (this->GetGlobalGenerator()->IsXcode()) {
  2678. file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2679. }
  2680. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2681. file << "#ifdef __cplusplus\n";
  2682. }
  2683. for (auto const& header_bt : headers) {
  2684. if (header_bt.Value.empty()) {
  2685. continue;
  2686. }
  2687. if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
  2688. file << "#include " << header_bt.Value << "\n";
  2689. } else {
  2690. file << "#include \"" << header_bt.Value << "\"\n";
  2691. }
  2692. if (cmSystemTools::FileExists(header_bt.Value) &&
  2693. firstHeaderOnDisk.empty()) {
  2694. firstHeaderOnDisk = header_bt.Value;
  2695. }
  2696. }
  2697. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2698. file << "#endif // __cplusplus\n";
  2699. }
  2700. if (this->GetGlobalGenerator()->IsXcode()) {
  2701. file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2702. }
  2703. if (pchEpilogue) {
  2704. file << *pchEpilogue << "\n";
  2705. }
  2706. }
  2707. if (!firstHeaderOnDisk.empty()) {
  2708. cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
  2709. }
  2710. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2711. }
  2712. }
  2713. return inserted.first->second;
  2714. }
  2715. std::string cmGeneratorTarget::GetPchSource(std::string const& config,
  2716. std::string const& language,
  2717. std::string const& arch) const
  2718. {
  2719. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2720. language != "OBJCXX") {
  2721. return std::string();
  2722. }
  2723. auto const inserted =
  2724. this->PchSources.insert(std::make_pair(language + config + arch, ""));
  2725. if (inserted.second) {
  2726. std::string const pchHeader = this->GetPchHeader(config, language, arch);
  2727. if (pchHeader.empty()) {
  2728. return std::string();
  2729. }
  2730. std::string& filename = inserted.first->second;
  2731. cmGeneratorTarget const* generatorTarget = this;
  2732. cmGeneratorTarget const* reuseTarget = this->GetPchReuseTarget();
  2733. bool const haveReuseTarget = reuseTarget && reuseTarget != this;
  2734. if (reuseTarget) {
  2735. generatorTarget = reuseTarget;
  2736. }
  2737. filename =
  2738. cmStrCat(generatorTarget->GetCMFSupportDirectory(), "/cmake_pch");
  2739. // For GCC the source extension will be transformed into .h[xx].gch
  2740. if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2741. std::map<std::string, std::string> const languageToExtension = {
  2742. { "C", ".h.c" },
  2743. { "CXX", ".hxx.cxx" },
  2744. { "OBJC", ".objc.h.m" },
  2745. { "OBJCXX", ".objcxx.hxx.mm" }
  2746. };
  2747. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
  2748. languageToExtension.at(language));
  2749. } else {
  2750. std::map<std::string, std::string> const languageToExtension = {
  2751. { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
  2752. };
  2753. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat('_', arch),
  2754. languageToExtension.at(language));
  2755. }
  2756. std::string const filename_tmp = cmStrCat(filename, ".tmp");
  2757. if (!haveReuseTarget) {
  2758. {
  2759. cmGeneratedFileStream file(filename_tmp);
  2760. file << "/* generated by CMake */\n";
  2761. }
  2762. cmFileTimes::Copy(pchHeader, filename_tmp);
  2763. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2764. }
  2765. }
  2766. return inserted.first->second;
  2767. }
  2768. std::string cmGeneratorTarget::GetPchFileObject(std::string const& config,
  2769. std::string const& language,
  2770. std::string const& arch)
  2771. {
  2772. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2773. language != "OBJCXX") {
  2774. return std::string();
  2775. }
  2776. auto const inserted =
  2777. this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
  2778. if (inserted.second) {
  2779. std::string const pchSource = this->GetPchSource(config, language, arch);
  2780. if (pchSource.empty()) {
  2781. return std::string();
  2782. }
  2783. std::string& filename = inserted.first->second;
  2784. auto* pchSf = this->Makefile->GetOrCreateSource(
  2785. pchSource, false, cmSourceFileLocationKind::Known);
  2786. pchSf->SetSpecialSourceType(cmSourceFile::SpecialSourceType::PchSource);
  2787. pchSf->ResolveFullPath();
  2788. filename = cmStrCat(this->GetObjectDirectory(config), '/',
  2789. this->GetObjectName(pchSf));
  2790. }
  2791. return inserted.first->second;
  2792. }
  2793. std::string cmGeneratorTarget::GetPchFile(std::string const& config,
  2794. std::string const& language,
  2795. std::string const& arch)
  2796. {
  2797. auto const inserted =
  2798. this->PchFiles.insert(std::make_pair(language + config + arch, ""));
  2799. if (inserted.second) {
  2800. std::string& pchFile = inserted.first->second;
  2801. std::string const pchExtension =
  2802. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2803. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2804. auto replaceExtension = [](std::string const& str,
  2805. std::string const& ext) -> std::string {
  2806. auto dot_pos = str.rfind('.');
  2807. std::string result;
  2808. if (dot_pos != std::string::npos) {
  2809. result = str.substr(0, dot_pos);
  2810. }
  2811. result += ext;
  2812. return result;
  2813. };
  2814. cmGeneratorTarget* generatorTarget = this;
  2815. cmGeneratorTarget* reuseTarget = this->GetPchReuseTarget();
  2816. if (reuseTarget) {
  2817. generatorTarget = reuseTarget;
  2818. }
  2819. std::string const pchFileObject =
  2820. generatorTarget->GetPchFileObject(config, language, arch);
  2821. if (!pchExtension.empty()) {
  2822. pchFile = replaceExtension(pchFileObject, pchExtension);
  2823. }
  2824. } else {
  2825. if (this->GetUseShortObjectNames() && !pchExtension.empty()) {
  2826. auto pchSource = this->GetPchSource(config, language, arch);
  2827. auto* pchSf = this->Makefile->GetOrCreateSource(
  2828. pchSource, false, cmSourceFileLocationKind::Known);
  2829. pchSf->SetSpecialSourceType(
  2830. cmSourceFile::SpecialSourceType::PchSource);
  2831. pchSf->ResolveFullPath();
  2832. std::string cfgSubdir;
  2833. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2834. cfgSubdir = cmStrCat(config, '/');
  2835. }
  2836. pchFile = cmStrCat(
  2837. this->GetSupportDirectory(), '/', cfgSubdir,
  2838. this->LocalGenerator->GetShortObjectFileName(*pchSf), pchExtension);
  2839. } else {
  2840. pchFile =
  2841. cmStrCat(this->GetPchHeader(config, language, arch), pchExtension);
  2842. }
  2843. }
  2844. }
  2845. return inserted.first->second;
  2846. }
  2847. std::string cmGeneratorTarget::GetPchCreateCompileOptions(
  2848. std::string const& config, std::string const& language,
  2849. std::string const& arch)
  2850. {
  2851. auto const inserted = this->PchCreateCompileOptions.insert(
  2852. std::make_pair(language + config + arch, ""));
  2853. if (inserted.second) {
  2854. std::string& createOptionList = inserted.first->second;
  2855. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2856. createOptionList = this->Makefile->GetSafeDefinition(
  2857. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2858. }
  2859. if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
  2860. std::string varName = cmStrCat(
  2861. "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
  2862. std::string instantiateOption =
  2863. this->Makefile->GetSafeDefinition(varName);
  2864. if (!instantiateOption.empty()) {
  2865. createOptionList = cmStrCat(createOptionList, ';', instantiateOption);
  2866. }
  2867. }
  2868. std::string const createOptVar =
  2869. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
  2870. createOptionList = cmStrCat(
  2871. createOptionList, ';', this->Makefile->GetSafeDefinition(createOptVar));
  2872. std::string const pchHeader = this->GetPchHeader(config, language, arch);
  2873. std::string const pchFile = this->GetPchFile(config, language, arch);
  2874. if (GlobalGenerator->IsFastbuild()) {
  2875. // Account for potential spaces in a shell-friendly way.
  2876. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
  2877. '"' + pchHeader + '"');
  2878. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>",
  2879. '"' + pchFile + '"');
  2880. } else {
  2881. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>",
  2882. pchHeader);
  2883. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
  2884. }
  2885. }
  2886. return inserted.first->second;
  2887. }
  2888. std::string cmGeneratorTarget::GetPchUseCompileOptions(
  2889. std::string const& config, std::string const& language,
  2890. std::string const& arch)
  2891. {
  2892. auto const inserted = this->PchUseCompileOptions.insert(
  2893. std::make_pair(language + config + arch, ""));
  2894. if (inserted.second) {
  2895. std::string& useOptionList = inserted.first->second;
  2896. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2897. useOptionList = this->Makefile->GetSafeDefinition(
  2898. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2899. }
  2900. std::string const useOptVar =
  2901. cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
  2902. std::string const& useOptionListProperty =
  2903. this->GetSafeProperty(useOptVar);
  2904. useOptionList = cmStrCat(
  2905. useOptionList, ';',
  2906. useOptionListProperty.empty()
  2907. ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
  2908. : useOptionListProperty);
  2909. std::string const pchHeader = this->GetPchHeader(config, language, arch);
  2910. std::string const pchFile = this->GetPchFile(config, language, arch);
  2911. if (GlobalGenerator->IsFastbuild()) {
  2912. // Account for potential spaces in a shell-friendly way.
  2913. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>",
  2914. '"' + pchHeader + '"');
  2915. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>",
  2916. '"' + pchFile + '"');
  2917. } else {
  2918. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
  2919. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
  2920. }
  2921. }
  2922. return inserted.first->second;
  2923. }
  2924. void cmGeneratorTarget::AddSourceFileToUnityBatch(
  2925. std::string const& sourceFilename)
  2926. {
  2927. this->UnityBatchedSourceFiles.insert(sourceFilename);
  2928. }
  2929. bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
  2930. std::string const& sourceFilename) const
  2931. {
  2932. if (!this->GetPropertyAsBool("UNITY_BUILD")) {
  2933. return false;
  2934. }
  2935. return this->UnityBatchedSourceFiles.find(sourceFilename) !=
  2936. this->UnityBatchedSourceFiles.end();
  2937. }
  2938. void cmGeneratorTarget::ComputeTargetManifest(std::string const& config) const
  2939. {
  2940. if (this->IsImported()) {
  2941. return;
  2942. }
  2943. cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
  2944. // Get the names.
  2945. cmGeneratorTarget::Names targetNames;
  2946. if (this->GetType() == cmStateEnums::EXECUTABLE) {
  2947. targetNames = this->GetExecutableNames(config);
  2948. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2949. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2950. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2951. targetNames = this->GetLibraryNames(config);
  2952. } else {
  2953. return;
  2954. }
  2955. // Get the directory.
  2956. std::string dir =
  2957. this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
  2958. // Add each name.
  2959. std::string f;
  2960. if (!targetNames.Output.empty()) {
  2961. f = cmStrCat(dir, '/', targetNames.Output);
  2962. gg->AddToManifest(f);
  2963. }
  2964. if (!targetNames.SharedObject.empty()) {
  2965. f = cmStrCat(dir, '/', targetNames.SharedObject);
  2966. gg->AddToManifest(f);
  2967. }
  2968. if (!targetNames.Real.empty()) {
  2969. f = cmStrCat(dir, '/', targetNames.Real);
  2970. gg->AddToManifest(f);
  2971. }
  2972. if (!targetNames.PDB.empty()) {
  2973. f = cmStrCat(dir, '/', targetNames.PDB);
  2974. gg->AddToManifest(f);
  2975. }
  2976. dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
  2977. if (!targetNames.ImportOutput.empty()) {
  2978. f = cmStrCat(dir, '/', targetNames.ImportOutput);
  2979. gg->AddToManifest(f);
  2980. }
  2981. if (!targetNames.ImportLibrary.empty()) {
  2982. f = cmStrCat(dir, '/', targetNames.ImportLibrary);
  2983. gg->AddToManifest(f);
  2984. }
  2985. if (!targetNames.ImportReal.empty()) {
  2986. f = cmStrCat(dir, '/', targetNames.ImportReal);
  2987. gg->AddToManifest(f);
  2988. }
  2989. }
  2990. cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
  2991. std::string const& lang, std::string const& config) const
  2992. {
  2993. cm::optional<cmStandardLevel> level;
  2994. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  2995. auto i = this->ExplicitStandardLevel.find(key);
  2996. if (i != this->ExplicitStandardLevel.end()) {
  2997. level = i->second;
  2998. }
  2999. return level;
  3000. }
  3001. void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
  3002. std::string const& config,
  3003. cmStandardLevel level)
  3004. {
  3005. auto e = this->ExplicitStandardLevel.emplace(
  3006. cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
  3007. if (!e.second && e.first->second < level) {
  3008. e.first->second = level;
  3009. }
  3010. }
  3011. bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
  3012. {
  3013. cmStandardLevelResolver standardResolver(this->Makefile);
  3014. for (std::string const& lang :
  3015. this->Makefile->GetState()->GetEnabledLanguages()) {
  3016. if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
  3017. if (cm::optional<cmStandardLevel> langLevel =
  3018. standardResolver.LanguageStandardLevel(lang, *languageStd)) {
  3019. this->UpdateExplicitStandardLevel(lang, config, *langLevel);
  3020. }
  3021. }
  3022. }
  3023. // Compute the language standard based on the compile features.
  3024. std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
  3025. for (BT<std::string> const& f : features) {
  3026. std::string lang;
  3027. if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
  3028. lang, nullptr)) {
  3029. return false;
  3030. }
  3031. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  3032. cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
  3033. cm::optional<cmStandardLevel> featureLevel;
  3034. std::string newRequiredStandard;
  3035. if (!standardResolver.GetNewRequiredStandard(
  3036. this->Target->GetName(), f.Value, currentLanguageStandard,
  3037. featureLevel, newRequiredStandard)) {
  3038. return false;
  3039. }
  3040. if (featureLevel) {
  3041. this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
  3042. }
  3043. if (!newRequiredStandard.empty()) {
  3044. BTs<std::string>& languageStandardProperty =
  3045. this->LanguageStandardMap[key];
  3046. if (languageStandardProperty.Value != newRequiredStandard) {
  3047. languageStandardProperty.Value = newRequiredStandard;
  3048. languageStandardProperty.Backtraces.clear();
  3049. }
  3050. languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
  3051. }
  3052. }
  3053. return true;
  3054. }
  3055. bool cmGeneratorTarget::ComputeCompileFeatures(
  3056. std::string const& config, std::set<LanguagePair> const& languagePairs)
  3057. {
  3058. for (auto const& language : languagePairs) {
  3059. BTs<std::string> const* generatorTargetLanguageStandard =
  3060. this->GetLanguageStandardProperty(language.first, config);
  3061. if (!generatorTargetLanguageStandard) {
  3062. // If the standard isn't explicitly set we copy it over from the
  3063. // specified paired language.
  3064. std::string key =
  3065. cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
  3066. BTs<std::string> const* standardToCopy =
  3067. this->GetLanguageStandardProperty(language.second, config);
  3068. if (standardToCopy) {
  3069. this->LanguageStandardMap[key] = *standardToCopy;
  3070. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  3071. } else {
  3072. cmValue defaultStandard = this->Makefile->GetDefinition(
  3073. cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
  3074. if (defaultStandard) {
  3075. this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
  3076. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  3077. }
  3078. }
  3079. // Custom updates for the CUDA standard.
  3080. if (generatorTargetLanguageStandard && (language.first == "CUDA")) {
  3081. if (generatorTargetLanguageStandard->Value == "98") {
  3082. this->LanguageStandardMap[key].Value = "03";
  3083. }
  3084. }
  3085. }
  3086. }
  3087. return true;
  3088. }
  3089. std::string cmGeneratorTarget::GetImportedLibName(
  3090. std::string const& config) const
  3091. {
  3092. if (cmGeneratorTarget::ImportInfo const* info =
  3093. this->GetImportInfo(config)) {
  3094. return info->LibName;
  3095. }
  3096. return std::string();
  3097. }
  3098. std::string cmGeneratorTarget::GetFullPath(std::string const& config,
  3099. cmStateEnums::ArtifactType artifact,
  3100. bool realname) const
  3101. {
  3102. if (this->IsImported()) {
  3103. return this->Target->ImportedGetFullPath(config, artifact);
  3104. }
  3105. return this->NormalGetFullPath(config, artifact, realname);
  3106. }
  3107. std::string cmGeneratorTarget::NormalGetFullPath(
  3108. std::string const& config, cmStateEnums::ArtifactType artifact,
  3109. bool realname) const
  3110. {
  3111. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  3112. if (this->IsAppBundleOnApple()) {
  3113. fpath =
  3114. cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
  3115. }
  3116. // Add the full name of the target.
  3117. switch (artifact) {
  3118. case cmStateEnums::RuntimeBinaryArtifact:
  3119. if (realname) {
  3120. fpath += this->NormalGetRealName(config);
  3121. } else {
  3122. fpath +=
  3123. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
  3124. }
  3125. break;
  3126. case cmStateEnums::ImportLibraryArtifact:
  3127. if (realname) {
  3128. fpath +=
  3129. this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
  3130. } else {
  3131. fpath +=
  3132. this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
  3133. }
  3134. break;
  3135. }
  3136. return fpath;
  3137. }
  3138. std::string cmGeneratorTarget::NormalGetRealName(
  3139. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3140. {
  3141. // This should not be called for imported targets.
  3142. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3143. // enforcement of the limited imported target API.
  3144. if (this->IsImported()) {
  3145. std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
  3146. this->GetName());
  3147. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3148. }
  3149. Names names = this->GetType() == cmStateEnums::EXECUTABLE
  3150. ? this->GetExecutableNames(config)
  3151. : this->GetLibraryNames(config);
  3152. // Compute the real name that will be built.
  3153. return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
  3154. : names.ImportReal;
  3155. }
  3156. cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
  3157. std::string const& config) const
  3158. {
  3159. cmGeneratorTarget::Names targetNames;
  3160. // This should not be called for imported targets.
  3161. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3162. // enforcement of the limited imported target API.
  3163. if (this->IsImported()) {
  3164. std::string msg =
  3165. cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
  3166. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3167. }
  3168. // Check for library version properties.
  3169. cmValue version = this->GetProperty("VERSION");
  3170. cmValue soversion = this->GetProperty("SOVERSION");
  3171. if (!this->HasSOName(config) ||
  3172. this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
  3173. this->IsFrameworkOnApple()) {
  3174. // Versioning is supported only for shared libraries and modules,
  3175. // and then only when the platform supports an soname flag.
  3176. version = nullptr;
  3177. soversion = nullptr;
  3178. }
  3179. if (version && !soversion) {
  3180. // The soversion must be set if the library version is set. Use
  3181. // the library version as the soversion.
  3182. soversion = version;
  3183. }
  3184. if (!version && soversion) {
  3185. // Use the soversion as the library version.
  3186. version = soversion;
  3187. }
  3188. // Get the components of the library name.
  3189. NameComponents const& components = this->GetFullNameInternalComponents(
  3190. config, cmStateEnums::RuntimeBinaryArtifact);
  3191. // The library name.
  3192. targetNames.Base = components.base;
  3193. targetNames.Output =
  3194. cmStrCat(components.prefix, targetNames.Base, components.suffix);
  3195. if (this->IsFrameworkOnApple()) {
  3196. targetNames.Real = components.prefix;
  3197. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3198. targetNames.Real +=
  3199. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3200. }
  3201. targetNames.Real += cmStrCat(targetNames.Base, components.suffix);
  3202. targetNames.SharedObject = targetNames.Real;
  3203. } else if (this->IsArchivedAIXSharedLibrary()) {
  3204. targetNames.SharedObject =
  3205. cmStrCat(components.prefix, targetNames.Base, ".so");
  3206. if (soversion) {
  3207. targetNames.SharedObject += ".";
  3208. targetNames.SharedObject += *soversion;
  3209. }
  3210. targetNames.Real = targetNames.Output;
  3211. } else {
  3212. // The library's soname.
  3213. targetNames.SharedObject = this->ComputeVersionedName(
  3214. components.prefix, targetNames.Base, components.suffix,
  3215. targetNames.Output, soversion);
  3216. // The library's real name on disk.
  3217. targetNames.Real = this->ComputeVersionedName(
  3218. components.prefix, targetNames.Base, components.suffix,
  3219. targetNames.Output, version);
  3220. }
  3221. // The import library names.
  3222. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3223. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3224. NameComponents const& importComponents =
  3225. this->GetFullNameInternalComponents(config,
  3226. cmStateEnums::ImportLibraryArtifact);
  3227. targetNames.ImportOutput = cmStrCat(
  3228. importComponents.prefix, importComponents.base, importComponents.suffix);
  3229. if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
  3230. targetNames.ImportReal = components.prefix;
  3231. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3232. targetNames.ImportReal +=
  3233. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3234. }
  3235. targetNames.ImportReal +=
  3236. cmStrCat(importComponents.base, importComponents.suffix);
  3237. targetNames.ImportLibrary = targetNames.ImportOutput;
  3238. } else {
  3239. // The import library's soname.
  3240. targetNames.ImportLibrary = this->ComputeVersionedName(
  3241. importComponents.prefix, importComponents.base,
  3242. importComponents.suffix, targetNames.ImportOutput, soversion);
  3243. // The import library's real name on disk.
  3244. targetNames.ImportReal = this->ComputeVersionedName(
  3245. importComponents.prefix, importComponents.base,
  3246. importComponents.suffix, targetNames.ImportOutput, version);
  3247. }
  3248. }
  3249. // The program database file name.
  3250. targetNames.PDB = this->GetPDBName(config);
  3251. return targetNames;
  3252. }
  3253. cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
  3254. std::string const& config) const
  3255. {
  3256. cmGeneratorTarget::Names targetNames;
  3257. // This should not be called for imported targets.
  3258. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3259. // enforcement of the limited imported target API.
  3260. if (this->IsImported()) {
  3261. std::string msg = cmStrCat(
  3262. "GetExecutableNames called on imported target: ", this->GetName());
  3263. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3264. }
  3265. // This versioning is supported only for executables and then only
  3266. // when the platform supports symbolic links.
  3267. #if defined(_WIN32) && !defined(__CYGWIN__)
  3268. cmValue version;
  3269. #else
  3270. // Check for executable version properties.
  3271. cmValue version = this->GetProperty("VERSION");
  3272. if (this->GetType() != cmStateEnums::EXECUTABLE ||
  3273. this->Makefile->IsOn("XCODE")) {
  3274. version = nullptr;
  3275. }
  3276. #endif
  3277. // Get the components of the executable name.
  3278. NameComponents const& components = this->GetFullNameInternalComponents(
  3279. config, cmStateEnums::RuntimeBinaryArtifact);
  3280. // The executable name.
  3281. targetNames.Base = components.base;
  3282. if (this->IsArchivedAIXSharedLibrary()) {
  3283. targetNames.Output = components.prefix + targetNames.Base;
  3284. } else {
  3285. targetNames.Output =
  3286. components.prefix + targetNames.Base + components.suffix;
  3287. }
  3288. // The executable's real name on disk.
  3289. #if defined(__CYGWIN__)
  3290. targetNames.Real = components.prefix + targetNames.Base;
  3291. #else
  3292. targetNames.Real = targetNames.Output;
  3293. #endif
  3294. if (version) {
  3295. targetNames.Real += "-";
  3296. targetNames.Real += *version;
  3297. }
  3298. #if defined(__CYGWIN__)
  3299. targetNames.Real += components.suffix;
  3300. #endif
  3301. // The import library name.
  3302. targetNames.ImportLibrary =
  3303. this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
  3304. targetNames.ImportReal = targetNames.ImportLibrary;
  3305. targetNames.ImportOutput = targetNames.ImportLibrary;
  3306. // The program database file name.
  3307. targetNames.PDB = this->GetPDBName(config);
  3308. return targetNames;
  3309. }
  3310. std::string cmGeneratorTarget::GetFullNameInternal(
  3311. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3312. {
  3313. NameComponents const& components =
  3314. this->GetFullNameInternalComponents(config, artifact);
  3315. return components.prefix + components.base + components.suffix;
  3316. }
  3317. std::string cmGeneratorTarget::ImportedGetLocation(
  3318. std::string const& config) const
  3319. {
  3320. assert(this->IsImported());
  3321. return this->Target->ImportedGetFullPath(
  3322. config, cmStateEnums::RuntimeBinaryArtifact);
  3323. }
  3324. std::string cmGeneratorTarget::GetFullNameImported(
  3325. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3326. {
  3327. return cmSystemTools::GetFilenameName(
  3328. this->Target->ImportedGetFullPath(config, artifact));
  3329. }
  3330. cmGeneratorTarget::NameComponents const&
  3331. cmGeneratorTarget::GetFullNameInternalComponents(
  3332. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3333. {
  3334. assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
  3335. artifact == cmStateEnums::ImportLibraryArtifact);
  3336. FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
  3337. ? RuntimeBinaryFullNameCache
  3338. : ImportLibraryFullNameCache;
  3339. auto search = cache.find(config);
  3340. if (search != cache.end()) {
  3341. return search->second;
  3342. }
  3343. // Use just the target name for non-main target types.
  3344. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3345. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3346. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3347. this->GetType() != cmStateEnums::EXECUTABLE) {
  3348. NameComponents components;
  3349. components.base = this->GetName();
  3350. return cache.emplace(config, std::move(components)).first->second;
  3351. }
  3352. bool const isImportedLibraryArtifact =
  3353. (artifact == cmStateEnums::ImportLibraryArtifact);
  3354. // Return an empty name for the import library if this platform
  3355. // does not support import libraries.
  3356. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  3357. return cache.emplace(config, NameComponents()).first->second;
  3358. }
  3359. NameComponents parts;
  3360. std::string& outPrefix = parts.prefix;
  3361. std::string& outBase = parts.base;
  3362. std::string& outSuffix = parts.suffix;
  3363. // retrieve prefix and suffix
  3364. std::string ll = this->GetLinkerLanguage(config);
  3365. cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
  3366. cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
  3367. // The implib option is only allowed for shared libraries, module
  3368. // libraries, and executables.
  3369. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3370. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3371. this->GetType() != cmStateEnums::EXECUTABLE) {
  3372. artifact = cmStateEnums::RuntimeBinaryArtifact;
  3373. }
  3374. // Compute the full name for main target types.
  3375. std::string configPostfix = this->GetFilePostfix(config);
  3376. // frameworks have directory prefix
  3377. std::string fw_prefix;
  3378. if (this->IsFrameworkOnApple()) {
  3379. fw_prefix =
  3380. cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
  3381. targetPrefix = cmValue(fw_prefix);
  3382. if (!isImportedLibraryArtifact) {
  3383. // no suffix
  3384. targetSuffix = nullptr;
  3385. }
  3386. }
  3387. if (this->IsCFBundleOnApple()) {
  3388. fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
  3389. targetPrefix = cmValue(fw_prefix);
  3390. targetSuffix = nullptr;
  3391. }
  3392. // Begin the final name with the prefix.
  3393. outPrefix = targetPrefix ? *targetPrefix : "";
  3394. // Append the target name or property-specified name.
  3395. outBase += this->GetOutputName(config, artifact);
  3396. // Append the per-configuration postfix.
  3397. // When using Xcode, the postfix should be part of the suffix rather than
  3398. // the base, because the suffix ends up being used in Xcode's
  3399. // EXECUTABLE_SUFFIX attribute.
  3400. if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
  3401. configPostfix += *targetSuffix;
  3402. targetSuffix = cmValue(configPostfix);
  3403. } else {
  3404. outBase += configPostfix;
  3405. }
  3406. // Name shared libraries with their version number on some platforms.
  3407. if (cmValue soversion = this->GetProperty("SOVERSION")) {
  3408. cmValue dllProp;
  3409. if (this->IsDLLPlatform()) {
  3410. dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
  3411. }
  3412. if (this->GetType() == cmStateEnums::SHARED_LIBRARY &&
  3413. !isImportedLibraryArtifact &&
  3414. (dllProp.IsOn() ||
  3415. (!dllProp.IsSet() &&
  3416. this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
  3417. outBase += "-";
  3418. outBase += *soversion;
  3419. }
  3420. }
  3421. // Append the suffix.
  3422. outSuffix = targetSuffix ? *targetSuffix : "";
  3423. return cache.emplace(config, std::move(parts)).first->second;
  3424. }
  3425. std::string cmGeneratorTarget::GetLinkerLanguage(
  3426. std::string const& config) const
  3427. {
  3428. return this->GetLinkClosure(config)->LinkerLanguage;
  3429. }
  3430. std::string cmGeneratorTarget::GetLinkerTool(std::string const& config) const
  3431. {
  3432. return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
  3433. }
  3434. std::string cmGeneratorTarget::GetLinkerTool(std::string const& lang,
  3435. std::string const& config) const
  3436. {
  3437. auto linkMode = cmStrCat(
  3438. "CMAKE_", lang, this->IsDeviceLink() ? "_DEVICE_" : "_", "LINK_MODE");
  3439. auto mode = this->Makefile->GetDefinition(linkMode);
  3440. if (!mode || mode != "LINKER"_s) {
  3441. return this->Makefile->GetDefinition("CMAKE_LINKER");
  3442. }
  3443. auto linkerType = this->GetLinkerTypeProperty(lang, config);
  3444. if (linkerType.empty()) {
  3445. linkerType = "DEFAULT";
  3446. }
  3447. auto usingLinker =
  3448. cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
  3449. "LINKER_", linkerType);
  3450. auto linkerTool = this->Makefile->GetDefinition(usingLinker);
  3451. if (!linkerTool) {
  3452. if (this->GetGlobalGenerator()->IsVisualStudio() &&
  3453. linkerType == "DEFAULT"_s) {
  3454. return std::string{};
  3455. }
  3456. // fall-back to generic definition
  3457. linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
  3458. if (linkerType != "DEFAULT"_s) {
  3459. auto isCMakeLinkerType = [](std::string const& type) -> bool {
  3460. return std::all_of(type.cbegin(), type.cend(),
  3461. [](char c) { return std::isupper(c); });
  3462. };
  3463. if (isCMakeLinkerType(linkerType)) {
  3464. this->LocalGenerator->IssueMessage(
  3465. MessageType::FATAL_ERROR,
  3466. cmStrCat("LINKER_TYPE '", linkerType,
  3467. "' is unknown or not supported by this toolchain."));
  3468. } else {
  3469. this->LocalGenerator->IssueMessage(
  3470. MessageType::FATAL_ERROR,
  3471. cmStrCat("LINKER_TYPE '", linkerType,
  3472. "' is unknown. Did you forget to define the '", usingLinker,
  3473. "' variable?"));
  3474. }
  3475. }
  3476. }
  3477. return linkerTool;
  3478. }
  3479. bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
  3480. std::string const& config) const
  3481. {
  3482. // FIXME(#25486): Account for the LINKER_TYPE target property.
  3483. // Also factor out the hard-coded list below into a platform
  3484. // information table based on the linker id.
  3485. std::string ll = this->GetLinkerLanguage(config);
  3486. std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
  3487. cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
  3488. // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
  3489. // recursively by default. The Solaris linker has similar behavior.
  3490. return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
  3491. }
  3492. std::string cmGeneratorTarget::GetPDBOutputName(
  3493. std::string const& config) const
  3494. {
  3495. // Lookup/compute/cache the pdb output name for this configuration.
  3496. auto i = this->PdbOutputNameMap.find(config);
  3497. if (i == this->PdbOutputNameMap.end()) {
  3498. // Add empty name in map to detect potential recursion.
  3499. PdbOutputNameMapType::value_type entry(config, "");
  3500. i = this->PdbOutputNameMap.insert(entry).first;
  3501. // Compute output name.
  3502. std::vector<std::string> props;
  3503. std::string configUpper = cmSystemTools::UpperCase(config);
  3504. if (!configUpper.empty()) {
  3505. // PDB_NAME_<CONFIG>
  3506. props.push_back("PDB_NAME_" + configUpper);
  3507. }
  3508. // PDB_NAME
  3509. props.emplace_back("PDB_NAME");
  3510. std::string outName;
  3511. for (std::string const& p : props) {
  3512. if (cmValue outNameProp = this->GetProperty(p)) {
  3513. outName = *outNameProp;
  3514. break;
  3515. }
  3516. }
  3517. // Now evaluate genex and update the previously-prepared map entry.
  3518. if (outName.empty()) {
  3519. i->second = cmStrCat(
  3520. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact),
  3521. this->GetPolicyStatusCMP0202() != cmPolicies::NEW
  3522. ? this->GetFilePostfix(config)
  3523. : "");
  3524. } else {
  3525. i->second =
  3526. cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
  3527. }
  3528. } else if (i->second.empty()) {
  3529. // An empty map entry indicates we have been called recursively
  3530. // from the above block.
  3531. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  3532. MessageType::FATAL_ERROR,
  3533. "Target '" + this->GetName() + "' PDB_NAME depends on itself.",
  3534. this->GetBacktrace());
  3535. }
  3536. return i->second;
  3537. }
  3538. std::string cmGeneratorTarget::GetPDBName(std::string const& config) const
  3539. {
  3540. NameComponents const& parts = this->GetFullNameInternalComponents(
  3541. config, cmStateEnums::RuntimeBinaryArtifact);
  3542. std::string base = this->GetPDBOutputName(config);
  3543. return cmStrCat(parts.prefix, base,
  3544. this->GetPolicyStatusCMP0202() == cmPolicies::NEW
  3545. ? this->GetFilePostfix(config)
  3546. : "",
  3547. ".pdb");
  3548. }
  3549. std::string cmGeneratorTarget::GetObjectDirectory(
  3550. std::string const& config) const
  3551. {
  3552. std::string obj_dir =
  3553. this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
  3554. #if defined(__APPLE__)
  3555. // Replace Xcode's placeholder for the object file directory since
  3556. // installation and export scripts need to know the real directory.
  3557. // Xcode has build-time settings (e.g. for sanitizers) that affect this,
  3558. // but we use the default here. Users that want to enable sanitizers
  3559. // will do so at the cost of object library installation and export.
  3560. cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
  3561. "Objects-normal");
  3562. #endif
  3563. return obj_dir;
  3564. }
  3565. void cmGeneratorTarget::GetTargetObjectNames(
  3566. std::string const& config, std::vector<std::string>& objects) const
  3567. {
  3568. this->GetTargetObjectLocations(
  3569. config,
  3570. [&objects](cmObjectLocation const& buildLoc, cmObjectLocation const&) {
  3571. objects.push_back(buildLoc.GetPath());
  3572. });
  3573. }
  3574. void cmGeneratorTarget::GetTargetObjectLocations(
  3575. std::string const& config,
  3576. std::function<void(cmObjectLocation const&, cmObjectLocation const&)> cb)
  3577. const
  3578. {
  3579. std::vector<cmSourceFile const*> objectSources;
  3580. this->GetObjectSources(objectSources, config);
  3581. std::map<cmSourceFile const*, cmObjectLocations> mapping;
  3582. for (cmSourceFile const* sf : objectSources) {
  3583. mapping[sf];
  3584. }
  3585. this->LocalGenerator->ComputeObjectFilenames(mapping, config, this);
  3586. auto const buildUseShortPaths = this->GetUseShortObjectNames()
  3587. ? cmObjectLocations::UseShortPath::Yes
  3588. : cmObjectLocations::UseShortPath::No;
  3589. auto const installUseShortPaths = this->GetUseShortObjectNamesForInstall();
  3590. for (cmSourceFile const* src : objectSources) {
  3591. // Find the object file name corresponding to this source file.
  3592. auto map_it = mapping.find(src);
  3593. auto const& buildLoc = map_it->second.GetLocation(buildUseShortPaths);
  3594. auto const& installLoc =
  3595. map_it->second.GetInstallLocation(installUseShortPaths, config);
  3596. // It must exist because we populated the mapping just above.
  3597. assert(!buildLoc.GetPath().empty());
  3598. assert(!installLoc.GetPath().empty());
  3599. cb(buildLoc, installLoc);
  3600. }
  3601. // We need to compute the relative path from the root of
  3602. // of the object directory to handle subdirectory paths
  3603. std::string rootObjectDir = this->GetObjectDirectory(config);
  3604. rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
  3605. auto ispcObjects = this->GetGeneratedISPCObjects(config);
  3606. for (std::string const& output : ispcObjects) {
  3607. auto relativePathFromObjectDir = output.substr(rootObjectDir.size());
  3608. cmObjectLocation ispcLoc(relativePathFromObjectDir);
  3609. // FIXME: apply short path to this object if needed.
  3610. cb(ispcLoc, ispcLoc);
  3611. }
  3612. }
  3613. bool cmGeneratorTarget::StrictTargetComparison::operator()(
  3614. cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
  3615. {
  3616. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  3617. if (nameResult == 0) {
  3618. return strcmp(
  3619. t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
  3620. t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
  3621. }
  3622. return nameResult < 0;
  3623. }
  3624. struct cmGeneratorTarget::SourceFileFlags
  3625. cmGeneratorTarget::GetTargetSourceFileFlags(cmSourceFile const* sf) const
  3626. {
  3627. struct SourceFileFlags flags;
  3628. this->ConstructSourceFileFlags();
  3629. auto si = this->SourceFlagsMap.find(sf);
  3630. if (si != this->SourceFlagsMap.end()) {
  3631. flags = si->second;
  3632. } else {
  3633. // Handle the MACOSX_PACKAGE_LOCATION property on source files that
  3634. // were not listed in one of the other lists.
  3635. if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
  3636. flags.MacFolder = location->c_str();
  3637. bool const stripResources =
  3638. this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
  3639. if (*location == "Resources") {
  3640. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3641. if (stripResources) {
  3642. flags.MacFolder = "";
  3643. }
  3644. } else if (cmHasLiteralPrefix(*location, "Resources/")) {
  3645. flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
  3646. if (stripResources) {
  3647. flags.MacFolder += cmStrLen("Resources/");
  3648. }
  3649. } else {
  3650. flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
  3651. }
  3652. }
  3653. }
  3654. return flags;
  3655. }
  3656. void cmGeneratorTarget::ConstructSourceFileFlags() const
  3657. {
  3658. if (this->SourceFileFlagsConstructed) {
  3659. return;
  3660. }
  3661. this->SourceFileFlagsConstructed = true;
  3662. // Process public headers to mark the source files.
  3663. if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
  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 = "Headers";
  3669. flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
  3670. }
  3671. }
  3672. }
  3673. // Process private headers after public headers so that they take
  3674. // precedence if a file is listed in both.
  3675. if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
  3676. cmList relFiles{ *files };
  3677. for (auto const& relFile : relFiles) {
  3678. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3679. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3680. flags.MacFolder = "PrivateHeaders";
  3681. flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
  3682. }
  3683. }
  3684. }
  3685. // Mark sources listed as resources.
  3686. if (cmValue files = this->GetProperty("RESOURCE")) {
  3687. cmList relFiles{ *files };
  3688. for (auto const& relFile : relFiles) {
  3689. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3690. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3691. flags.MacFolder = "";
  3692. if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
  3693. flags.MacFolder = "Resources";
  3694. }
  3695. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3696. }
  3697. }
  3698. }
  3699. }
  3700. bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
  3701. {
  3702. bool previous = this->DeviceLink;
  3703. this->DeviceLink = deviceLink;
  3704. return previous;
  3705. }
  3706. void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
  3707. {
  3708. int patch;
  3709. this->GetTargetVersion("VERSION", major, minor, patch);
  3710. }
  3711. void cmGeneratorTarget::GetTargetVersionFallback(
  3712. std::string const& property, std::string const& fallback_property,
  3713. int& major, int& minor, int& patch) const
  3714. {
  3715. if (this->GetProperty(property)) {
  3716. this->GetTargetVersion(property, major, minor, patch);
  3717. } else {
  3718. this->GetTargetVersion(fallback_property, major, minor, patch);
  3719. }
  3720. }
  3721. void cmGeneratorTarget::GetTargetVersion(std::string const& property,
  3722. int& major, int& minor,
  3723. int& patch) const
  3724. {
  3725. // Set the default values.
  3726. major = 0;
  3727. minor = 0;
  3728. patch = 0;
  3729. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3730. if (cmValue version = this->GetProperty(property)) {
  3731. // Try to parse the version number and store the results that were
  3732. // successfully parsed.
  3733. int parsed_major;
  3734. int parsed_minor;
  3735. int parsed_patch;
  3736. switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
  3737. &parsed_patch)) {
  3738. case 3:
  3739. patch = parsed_patch;
  3740. CM_FALLTHROUGH;
  3741. case 2:
  3742. minor = parsed_minor;
  3743. CM_FALLTHROUGH;
  3744. case 1:
  3745. major = parsed_major;
  3746. CM_FALLTHROUGH;
  3747. default:
  3748. break;
  3749. }
  3750. }
  3751. }
  3752. std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
  3753. std::string const& lang, std::string const& config) const
  3754. {
  3755. // This is activated by the presence of a default selection whether or
  3756. // not it is overridden by a property.
  3757. cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
  3758. cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
  3759. if (!cmNonempty(runtimeLibraryDefault)) {
  3760. return std::string();
  3761. }
  3762. cmValue runtimeLibraryValue =
  3763. this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
  3764. if (!runtimeLibraryValue) {
  3765. runtimeLibraryValue = runtimeLibraryDefault;
  3766. }
  3767. return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
  3768. *runtimeLibraryValue, this->LocalGenerator, config, this));
  3769. }
  3770. std::string cmGeneratorTarget::GetFortranModuleDirectory(
  3771. std::string const& working_dir) const
  3772. {
  3773. if (!this->FortranModuleDirectoryCreated) {
  3774. this->FortranModuleDirectory =
  3775. this->CreateFortranModuleDirectory(working_dir);
  3776. this->FortranModuleDirectoryCreated = true;
  3777. }
  3778. return this->FortranModuleDirectory;
  3779. }
  3780. bool cmGeneratorTarget::IsFortranBuildingIntrinsicModules() const
  3781. {
  3782. // ATTENTION Before 4.0 the property name was misspelled.
  3783. // Check the correct name first and than the old name.
  3784. if (cmValue prop = this->GetProperty("Fortran_BUILDING_INTRINSIC_MODULES")) {
  3785. return prop.IsOn();
  3786. }
  3787. if (cmValue prop =
  3788. this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
  3789. return prop.IsOn();
  3790. }
  3791. return false;
  3792. }
  3793. std::string cmGeneratorTarget::CreateFortranModuleDirectory(
  3794. std::string const& working_dir) const
  3795. {
  3796. std::string mod_dir;
  3797. std::string target_mod_dir;
  3798. if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
  3799. target_mod_dir = *prop;
  3800. } else {
  3801. std::string const& default_mod_dir =
  3802. this->LocalGenerator->GetCurrentBinaryDirectory();
  3803. if (default_mod_dir != working_dir) {
  3804. target_mod_dir = default_mod_dir;
  3805. }
  3806. }
  3807. cmValue moddir_flag =
  3808. this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
  3809. if (!target_mod_dir.empty() && moddir_flag) {
  3810. // Compute the full path to the module directory.
  3811. if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
  3812. // Already a full path.
  3813. mod_dir = target_mod_dir;
  3814. } else {
  3815. // Interpret relative to the current output directory.
  3816. mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  3817. '/', target_mod_dir);
  3818. }
  3819. // Make sure the module output directory exists.
  3820. cmSystemTools::MakeDirectory(mod_dir);
  3821. }
  3822. return mod_dir;
  3823. }
  3824. void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
  3825. std::string const& config)
  3826. {
  3827. std::string config_upper;
  3828. if (!config.empty()) {
  3829. config_upper = cmSystemTools::UpperCase(config);
  3830. }
  3831. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3832. if (iter == this->ISPCGeneratedHeaders.end()) {
  3833. std::vector<std::string> headers;
  3834. headers.emplace_back(header);
  3835. this->ISPCGeneratedHeaders.insert({ config_upper, headers });
  3836. } else {
  3837. iter->second.emplace_back(header);
  3838. }
  3839. }
  3840. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
  3841. std::string const& config) const
  3842. {
  3843. std::string config_upper;
  3844. if (!config.empty()) {
  3845. config_upper = cmSystemTools::UpperCase(config);
  3846. }
  3847. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3848. if (iter == this->ISPCGeneratedHeaders.end()) {
  3849. return std::vector<std::string>{};
  3850. }
  3851. return iter->second;
  3852. }
  3853. void cmGeneratorTarget::AddISPCGeneratedObject(std::vector<std::string>&& objs,
  3854. std::string const& config)
  3855. {
  3856. std::string config_upper;
  3857. if (!config.empty()) {
  3858. config_upper = cmSystemTools::UpperCase(config);
  3859. }
  3860. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3861. if (iter == this->ISPCGeneratedObjects.end()) {
  3862. this->ISPCGeneratedObjects.insert({ config_upper, objs });
  3863. } else {
  3864. iter->second.insert(iter->second.end(), objs.begin(), objs.end());
  3865. }
  3866. }
  3867. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCObjects(
  3868. std::string const& config) const
  3869. {
  3870. std::string config_upper;
  3871. if (!config.empty()) {
  3872. config_upper = cmSystemTools::UpperCase(config);
  3873. }
  3874. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3875. if (iter == this->ISPCGeneratedObjects.end()) {
  3876. return std::vector<std::string>{};
  3877. }
  3878. return iter->second;
  3879. }
  3880. std::string cmGeneratorTarget::GetFrameworkVersion() const
  3881. {
  3882. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3883. if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
  3884. return *fversion;
  3885. }
  3886. if (cmValue tversion = this->GetProperty("VERSION")) {
  3887. return *tversion;
  3888. }
  3889. return "A";
  3890. }
  3891. std::string cmGeneratorTarget::ComputeVersionedName(std::string const& prefix,
  3892. std::string const& base,
  3893. std::string const& suffix,
  3894. std::string const& name,
  3895. cmValue version) const
  3896. {
  3897. std::string vName = this->IsApple() ? (prefix + base) : name;
  3898. if (version) {
  3899. vName += ".";
  3900. vName += *version;
  3901. }
  3902. vName += this->IsApple() ? suffix : std::string();
  3903. return vName;
  3904. }
  3905. std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
  3906. {
  3907. return this->Target->GetProperties().GetKeys();
  3908. }
  3909. void cmGeneratorTarget::ReportPropertyOrigin(
  3910. std::string const& p, std::string const& result, std::string const& report,
  3911. std::string const& compatibilityType) const
  3912. {
  3913. cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
  3914. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3915. bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
  3916. cm::contains(debugProperties, p);
  3917. this->DebugCompatiblePropertiesDone[p] = true;
  3918. if (!debugOrigin) {
  3919. return;
  3920. }
  3921. std::string areport =
  3922. cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
  3923. this->GetName(), "\" (result: \"", result, "\"):\n", report);
  3924. this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
  3925. areport);
  3926. }
  3927. std::string cmGeneratorTarget::GetDirectory(
  3928. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3929. {
  3930. if (this->IsImported()) {
  3931. auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
  3932. if (this->IsFrameworkOnApple()) {
  3933. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  3934. fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
  3935. if (fwDescriptor) {
  3936. return fwDescriptor->Directory;
  3937. }
  3938. }
  3939. // Return the directory from which the target is imported.
  3940. return cmSystemTools::GetFilenamePath(fullPath);
  3941. }
  3942. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  3943. // Return the directory in which the target will be built.
  3944. switch (artifact) {
  3945. case cmStateEnums::RuntimeBinaryArtifact:
  3946. return info->OutDir;
  3947. case cmStateEnums::ImportLibraryArtifact:
  3948. return info->ImpDir;
  3949. }
  3950. }
  3951. return "";
  3952. }
  3953. bool cmGeneratorTarget::UsesDefaultOutputDir(
  3954. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3955. {
  3956. std::string dir;
  3957. return this->ComputeOutputDir(config, artifact, dir);
  3958. }
  3959. cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
  3960. std::string const& config) const
  3961. {
  3962. // There is no output information for imported targets.
  3963. if (this->IsImported()) {
  3964. return nullptr;
  3965. }
  3966. // Synthetic targets don't have output.
  3967. if (this->IsSynthetic()) {
  3968. return nullptr;
  3969. }
  3970. // Only libraries and executables have well-defined output files.
  3971. if (!this->HaveWellDefinedOutputFiles()) {
  3972. std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
  3973. this->GetName(), " which has type ",
  3974. cmState::GetTargetTypeName(this->GetType()));
  3975. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3976. return nullptr;
  3977. }
  3978. // Lookup/compute/cache the output information for this configuration.
  3979. std::string config_upper;
  3980. if (!config.empty()) {
  3981. config_upper = cmSystemTools::UpperCase(config);
  3982. }
  3983. auto i = this->OutputInfoMap.find(config_upper);
  3984. if (i == this->OutputInfoMap.end()) {
  3985. // Add empty info in map to detect potential recursion.
  3986. OutputInfo info;
  3987. OutputInfoMapType::value_type entry(config_upper, info);
  3988. i = this->OutputInfoMap.insert(entry).first;
  3989. // Compute output directories.
  3990. this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
  3991. info.OutDir);
  3992. this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
  3993. info.ImpDir);
  3994. if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
  3995. info.PdbDir = info.OutDir;
  3996. }
  3997. // Now update the previously-prepared map entry.
  3998. i->second = info;
  3999. } else if (i->second.empty()) {
  4000. // An empty map entry indicates we have been called recursively
  4001. // from the above block.
  4002. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  4003. MessageType::FATAL_ERROR,
  4004. "Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
  4005. this->GetBacktrace());
  4006. return nullptr;
  4007. }
  4008. return &i->second;
  4009. }
  4010. bool cmGeneratorTarget::ComputeOutputDir(std::string const& config,
  4011. cmStateEnums::ArtifactType artifact,
  4012. std::string& out) const
  4013. {
  4014. bool usesDefaultOutputDir = false;
  4015. std::string conf = config;
  4016. // Look for a target property defining the target output directory
  4017. // based on the target type.
  4018. std::string targetTypeName = this->GetOutputTargetType(artifact);
  4019. std::string propertyName;
  4020. if (!targetTypeName.empty()) {
  4021. propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
  4022. }
  4023. // Check for a per-configuration output directory target property.
  4024. std::string configUpper = cmSystemTools::UpperCase(conf);
  4025. std::string configProp;
  4026. if (!targetTypeName.empty()) {
  4027. configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
  4028. }
  4029. // Select an output directory.
  4030. if (cmValue config_outdir = this->GetProperty(configProp)) {
  4031. // Use the user-specified per-configuration output directory.
  4032. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  4033. config, this);
  4034. // Skip per-configuration subdirectory.
  4035. conf.clear();
  4036. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  4037. // Use the user-specified output directory.
  4038. out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
  4039. config, this);
  4040. // Skip per-configuration subdirectory if the value contained a
  4041. // generator expression.
  4042. if (out != *outdir) {
  4043. conf.clear();
  4044. }
  4045. } else if (this->GetType() == cmStateEnums::EXECUTABLE) {
  4046. // Lookup the output path for executables.
  4047. out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
  4048. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4049. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4050. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  4051. // Lookup the output path for libraries.
  4052. out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
  4053. }
  4054. if (out.empty()) {
  4055. // Default to the current output directory.
  4056. usesDefaultOutputDir = true;
  4057. out = ".";
  4058. }
  4059. // Convert the output path to a full path in case it is
  4060. // specified as a relative path. Treat a relative path as
  4061. // relative to the current output directory for this makefile.
  4062. out = (cmSystemTools::CollapseFullPath(
  4063. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  4064. // The generator may add the configuration's subdirectory.
  4065. if (!conf.empty()) {
  4066. bool useEPN =
  4067. this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
  4068. std::string suffix =
  4069. usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
  4070. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  4071. "/", conf, suffix, out);
  4072. }
  4073. return usesDefaultOutputDir;
  4074. }
  4075. bool cmGeneratorTarget::ComputePDBOutputDir(std::string const& kind,
  4076. std::string const& config,
  4077. std::string& out) const
  4078. {
  4079. // Look for a target property defining the target output directory
  4080. // based on the target type.
  4081. std::string propertyName;
  4082. if (!kind.empty()) {
  4083. propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
  4084. }
  4085. std::string conf = config;
  4086. // Check for a per-configuration output directory target property.
  4087. std::string configUpper = cmSystemTools::UpperCase(conf);
  4088. std::string configProp;
  4089. if (!kind.empty()) {
  4090. configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
  4091. }
  4092. // Select an output directory.
  4093. if (cmValue config_outdir = this->GetProperty(configProp)) {
  4094. // Use the user-specified per-configuration output directory.
  4095. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  4096. config);
  4097. // Skip per-configuration subdirectory.
  4098. conf.clear();
  4099. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  4100. // Use the user-specified output directory.
  4101. out =
  4102. cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
  4103. // Skip per-configuration subdirectory if the value contained a
  4104. // generator expression.
  4105. if (out != *outdir) {
  4106. conf.clear();
  4107. }
  4108. }
  4109. if (out.empty()) {
  4110. // Compile output should always have a path.
  4111. if (kind == "COMPILE_PDB"_s) {
  4112. out = this->GetSupportDirectory();
  4113. } else {
  4114. return false;
  4115. }
  4116. }
  4117. // Convert the output path to a full path in case it is
  4118. // specified as a relative path. Treat a relative path as
  4119. // relative to the current output directory for this makefile.
  4120. out = (cmSystemTools::CollapseFullPath(
  4121. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  4122. // The generator may add the configuration's subdirectory.
  4123. if (!conf.empty()) {
  4124. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  4125. "/", conf, "", out);
  4126. }
  4127. return true;
  4128. }
  4129. bool cmGeneratorTarget::HaveInstallTreeRPATH(std::string const& config) const
  4130. {
  4131. std::string install_rpath;
  4132. this->GetInstallRPATH(config, install_rpath);
  4133. return !install_rpath.empty() &&
  4134. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  4135. }
  4136. bool cmGeneratorTarget::GetBuildRPATH(std::string const& config,
  4137. std::string& rpath) const
  4138. {
  4139. return this->GetRPATH(config, "BUILD_RPATH", rpath);
  4140. }
  4141. bool cmGeneratorTarget::GetInstallRPATH(std::string const& config,
  4142. std::string& rpath) const
  4143. {
  4144. return this->GetRPATH(config, "INSTALL_RPATH", rpath);
  4145. }
  4146. bool cmGeneratorTarget::GetRPATH(std::string const& config,
  4147. std::string const& prop,
  4148. std::string& rpath) const
  4149. {
  4150. cmValue value = this->GetProperty(prop);
  4151. if (!value) {
  4152. return false;
  4153. }
  4154. rpath =
  4155. cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
  4156. return true;
  4157. }
  4158. cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
  4159. std::string const& config) const
  4160. {
  4161. // There is no imported information for non-imported targets.
  4162. if (!this->IsImported()) {
  4163. return nullptr;
  4164. }
  4165. // Lookup/compute/cache the import information for this
  4166. // configuration.
  4167. std::string config_upper;
  4168. if (!config.empty()) {
  4169. config_upper = cmSystemTools::UpperCase(config);
  4170. } else {
  4171. config_upper = "NOCONFIG";
  4172. }
  4173. auto i = this->ImportInfoMap.find(config_upper);
  4174. if (i == this->ImportInfoMap.end()) {
  4175. ImportInfo info;
  4176. this->ComputeImportInfo(config_upper, info);
  4177. ImportInfoMapType::value_type entry(config_upper, info);
  4178. i = this->ImportInfoMap.insert(entry).first;
  4179. }
  4180. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  4181. return &i->second;
  4182. }
  4183. // If the location is empty then the target is not available for
  4184. // this configuration.
  4185. if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
  4186. return nullptr;
  4187. }
  4188. // Return the import information.
  4189. return &i->second;
  4190. }
  4191. void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
  4192. ImportInfo& info) const
  4193. {
  4194. // This method finds information about an imported target from its
  4195. // properties. The "IMPORTED_" namespace is reserved for properties
  4196. // defined by the project exporting the target.
  4197. // Initialize members.
  4198. info.NoSOName = false;
  4199. cmValue loc = nullptr;
  4200. cmValue imp = nullptr;
  4201. std::string suffix;
  4202. if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
  4203. return;
  4204. }
  4205. // Get the link interface.
  4206. {
  4207. // Use the INTERFACE_LINK_LIBRARIES special representation directly
  4208. // to get backtraces.
  4209. cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
  4210. if (!entries.empty()) {
  4211. info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
  4212. for (BT<std::string> const& entry : entries) {
  4213. info.Libraries.emplace_back(entry);
  4214. }
  4215. } else if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  4216. std::string linkProp =
  4217. cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
  4218. cmValue propertyLibs = this->GetProperty(linkProp);
  4219. if (!propertyLibs) {
  4220. linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
  4221. propertyLibs = this->GetProperty(linkProp);
  4222. }
  4223. if (propertyLibs) {
  4224. info.LibrariesProp = linkProp;
  4225. info.Libraries.emplace_back(*propertyLibs);
  4226. }
  4227. }
  4228. }
  4229. for (BT<std::string> const& entry :
  4230. this->Target->GetLinkInterfaceDirectEntries()) {
  4231. info.LibrariesHeadInclude.emplace_back(entry);
  4232. }
  4233. for (BT<std::string> const& entry :
  4234. this->Target->GetLinkInterfaceDirectExcludeEntries()) {
  4235. info.LibrariesHeadExclude.emplace_back(entry);
  4236. }
  4237. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  4238. if (loc) {
  4239. info.LibName = *loc;
  4240. }
  4241. return;
  4242. }
  4243. // A provided configuration has been chosen. Load the
  4244. // configuration's properties.
  4245. // Get the location.
  4246. if (loc) {
  4247. info.Location = *loc;
  4248. } else {
  4249. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  4250. if (cmValue config_location = this->GetProperty(impProp)) {
  4251. info.Location = *config_location;
  4252. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  4253. info.Location = *location;
  4254. }
  4255. }
  4256. // Get the soname.
  4257. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4258. std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
  4259. if (cmValue config_soname = this->GetProperty(soProp)) {
  4260. info.SOName = *config_soname;
  4261. } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
  4262. info.SOName = *soname;
  4263. }
  4264. }
  4265. // Get the "no-soname" mark.
  4266. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4267. std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
  4268. if (cmValue config_no_soname = this->GetProperty(soProp)) {
  4269. info.NoSOName = config_no_soname.IsOn();
  4270. } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
  4271. info.NoSOName = no_soname.IsOn();
  4272. }
  4273. }
  4274. // Get the import library.
  4275. if (imp) {
  4276. info.ImportLibrary = *imp;
  4277. } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4278. this->IsExecutableWithExports()) {
  4279. std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
  4280. if (cmValue config_implib = this->GetProperty(impProp)) {
  4281. info.ImportLibrary = *config_implib;
  4282. } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
  4283. info.ImportLibrary = *implib;
  4284. }
  4285. }
  4286. // Get the link dependencies.
  4287. {
  4288. std::string linkProp =
  4289. cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
  4290. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4291. info.SharedDeps = *config_libs;
  4292. } else if (cmValue libs =
  4293. this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
  4294. info.SharedDeps = *libs;
  4295. }
  4296. }
  4297. // Get the link languages.
  4298. if (this->LinkLanguagePropagatesToDependents()) {
  4299. std::string linkProp =
  4300. cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
  4301. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4302. info.Languages = *config_libs;
  4303. } else if (cmValue libs =
  4304. this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
  4305. info.Languages = *libs;
  4306. }
  4307. }
  4308. // Get information if target is managed assembly.
  4309. {
  4310. std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
  4311. if (cmValue pc = this->GetProperty(linkProp + suffix)) {
  4312. info.Managed = this->CheckManagedType(*pc);
  4313. } else if (cmValue p = this->GetProperty(linkProp)) {
  4314. info.Managed = this->CheckManagedType(*p);
  4315. }
  4316. }
  4317. // Get the cyclic repetition count.
  4318. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4319. std::string linkProp =
  4320. cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
  4321. if (cmValue config_reps = this->GetProperty(linkProp)) {
  4322. sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
  4323. } else if (cmValue reps =
  4324. this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
  4325. sscanf(reps->c_str(), "%u", &info.Multiplicity);
  4326. }
  4327. }
  4328. }
  4329. bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
  4330. std::vector<cmSourceFile*>& files) const
  4331. {
  4332. std::vector<std::string> const& configs =
  4333. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4334. auto it = configs.begin();
  4335. std::string const& firstConfig = *it;
  4336. this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
  4337. for (; it != configs.end(); ++it) {
  4338. std::vector<cmSourceFile*> configFiles;
  4339. this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
  4340. if (configFiles != files) {
  4341. std::string firstConfigFiles;
  4342. char const* sep = "";
  4343. for (cmSourceFile* f : files) {
  4344. firstConfigFiles += sep;
  4345. firstConfigFiles += f->ResolveFullPath();
  4346. sep = "\n ";
  4347. }
  4348. std::string thisConfigFiles;
  4349. sep = "";
  4350. for (cmSourceFile* f : configFiles) {
  4351. thisConfigFiles += sep;
  4352. thisConfigFiles += f->ResolveFullPath();
  4353. sep = "\n ";
  4354. }
  4355. std::ostringstream e;
  4356. /* clang-format off */
  4357. e << "Target \"" << this->GetName()
  4358. << "\" has source files which vary by "
  4359. "configuration. This is not supported by the \""
  4360. << this->GlobalGenerator->GetName()
  4361. << "\" generator.\n"
  4362. "Config \"" << firstConfig << "\":\n"
  4363. " " << firstConfigFiles << "\n"
  4364. "Config \"" << *it << "\":\n"
  4365. " " << thisConfigFiles << "\n";
  4366. /* clang-format on */
  4367. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4368. return false;
  4369. }
  4370. }
  4371. return true;
  4372. }
  4373. void cmGeneratorTarget::GetObjectLibrariesInSources(
  4374. std::vector<cmGeneratorTarget*>& objlibs) const
  4375. {
  4376. // FIXME: This searches SOURCES for TARGET_OBJECTS for backwards
  4377. // compatibility with the OLD behavior of CMP0026 since this
  4378. // could be called at configure time. CMP0026 has been removed,
  4379. // so this should now be called only at generate time.
  4380. // Therefore we should be able to improve the implementation
  4381. // with generate-time information.
  4382. cmBTStringRange rng = this->Target->GetSourceEntries();
  4383. for (auto const& entry : rng) {
  4384. cmList files{ entry.Value };
  4385. for (auto const& li : files) {
  4386. if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
  4387. std::string objLibName = li.substr(17, li.size() - 18);
  4388. if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
  4389. continue;
  4390. }
  4391. cmGeneratorTarget* objLib =
  4392. this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
  4393. if (objLib) {
  4394. objlibs.push_back(objLib);
  4395. }
  4396. }
  4397. }
  4398. }
  4399. }
  4400. std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
  4401. {
  4402. // Strip whitespace off the library names because we used to do this
  4403. // in case variables were expanded at generate time. We no longer
  4404. // do the expansion but users link to libraries like " ${VAR} ".
  4405. std::string lib = item;
  4406. std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
  4407. if (pos != std::string::npos) {
  4408. lib = lib.substr(pos);
  4409. }
  4410. pos = lib.find_last_not_of(" \t\r\n");
  4411. if (pos != std::string::npos) {
  4412. lib = lib.substr(0, pos + 1);
  4413. }
  4414. if (lib != item) {
  4415. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  4416. std::ostringstream e;
  4417. e << "Target \"" << this->GetName() << "\" links to item \"" << item
  4418. << "\" which has leading or trailing whitespace. "
  4419. << "This is now an error according to policy CMP0004.";
  4420. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(), this->GetBacktrace());
  4421. }
  4422. return lib;
  4423. }
  4424. bool cmGeneratorTarget::IsDeprecated() const
  4425. {
  4426. cmValue deprecation = this->GetProperty("DEPRECATION");
  4427. return cmNonempty(deprecation);
  4428. }
  4429. std::string cmGeneratorTarget::GetDeprecation() const
  4430. {
  4431. // find DEPRECATION property
  4432. if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
  4433. return *deprecation;
  4434. }
  4435. return std::string();
  4436. }
  4437. void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
  4438. std::string const& config) const
  4439. {
  4440. // Targets that do not compile anything have no languages.
  4441. if (!this->CanCompileSources()) {
  4442. return;
  4443. }
  4444. std::vector<cmSourceFile*> sourceFiles;
  4445. this->GetSourceFiles(sourceFiles, config);
  4446. for (cmSourceFile* src : sourceFiles) {
  4447. std::string const& lang = src->GetOrDetermineLanguage();
  4448. if (!lang.empty()) {
  4449. languages.insert(lang);
  4450. }
  4451. }
  4452. std::set<cmGeneratorTarget const*> objectLibraries =
  4453. this->GetSourceObjectLibraries(config);
  4454. for (cmGeneratorTarget const* objLib : objectLibraries) {
  4455. objLib->GetLanguages(languages, config);
  4456. }
  4457. }
  4458. std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
  4459. std::string const& config) const
  4460. {
  4461. std::set<cmGeneratorTarget const*> objectLibraries;
  4462. std::vector<cmSourceFile const*> externalObjects;
  4463. this->GetExternalObjects(externalObjects, config);
  4464. for (cmSourceFile const* extObj : externalObjects) {
  4465. std::string objLib = extObj->GetObjectLibrary();
  4466. if (cmGeneratorTarget* tgt =
  4467. this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
  4468. objectLibraries.insert(tgt);
  4469. }
  4470. }
  4471. return objectLibraries;
  4472. }
  4473. bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
  4474. std::string const& config) const
  4475. {
  4476. std::set<std::string> languages;
  4477. this->GetLanguages(languages, config);
  4478. return languages.count(language);
  4479. }
  4480. bool cmGeneratorTarget::IsCSharpOnly() const
  4481. {
  4482. // Only certain target types may compile CSharp.
  4483. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4484. this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4485. this->GetType() != cmStateEnums::EXECUTABLE) {
  4486. return false;
  4487. }
  4488. std::set<std::string> languages = this->GetAllConfigCompileLanguages();
  4489. // Consider an explicit linker language property, but *not* the
  4490. // computed linker language that may depend on linked targets.
  4491. cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
  4492. if (cmNonempty(linkLang)) {
  4493. languages.insert(*linkLang);
  4494. }
  4495. return languages.size() == 1 && languages.count("CSharp") > 0;
  4496. }
  4497. bool cmGeneratorTarget::IsDotNetSdkTarget() const
  4498. {
  4499. return !this->GetProperty("DOTNET_SDK").IsEmpty();
  4500. }
  4501. void cmGeneratorTarget::ComputeLinkImplementationLanguages(
  4502. std::string const& config, cmOptionalLinkImplementation& impl) const
  4503. {
  4504. // This target needs runtime libraries for its source languages.
  4505. std::set<std::string> languages;
  4506. // Get languages used in our source files.
  4507. this->GetLanguages(languages, config);
  4508. // Copy the set of languages to the link implementation.
  4509. impl.Languages.insert(impl.Languages.begin(), languages.begin(),
  4510. languages.end());
  4511. }
  4512. bool cmGeneratorTarget::HaveBuildTreeRPATH(std::string const& config) const
  4513. {
  4514. if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
  4515. return false;
  4516. }
  4517. std::string build_rpath;
  4518. if (this->GetBuildRPATH(config, build_rpath)) {
  4519. return true;
  4520. }
  4521. if (cmLinkImplementationLibraries const* impl =
  4522. this->GetLinkImplementationLibraries(config, UseTo::Link)) {
  4523. return !impl->Libraries.empty();
  4524. }
  4525. return false;
  4526. }
  4527. bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
  4528. std::string const& p) const
  4529. {
  4530. return cm::contains(this->LinkImplicitNullProperties, p);
  4531. }
  4532. bool cmGeneratorTarget::ApplyCXXStdTargets()
  4533. {
  4534. cmStandardLevelResolver standardResolver(this->Makefile);
  4535. cmStandardLevel const cxxStd23 =
  4536. *standardResolver.LanguageStandardLevel("CXX", "23");
  4537. std::vector<std::string> const& configs =
  4538. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4539. auto std_prop = this->GetProperty("CXX_MODULE_STD");
  4540. if (!std_prop) {
  4541. // TODO(cxxmodules): Add a target policy to flip the default here. Set
  4542. // `std_prop` based on it.
  4543. return true;
  4544. }
  4545. std::string std_prop_value;
  4546. if (std_prop) {
  4547. // Evaluate generator expressions.
  4548. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  4549. auto cge = ge.Parse(*std_prop);
  4550. if (!cge) {
  4551. this->Makefile->IssueMessage(
  4552. MessageType::FATAL_ERROR,
  4553. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4554. this->GetName(), "\" is not a valid generator expression."));
  4555. return false;
  4556. }
  4557. // But do not allow context-sensitive queries. Whether a target uses
  4558. // `import std` should not depend on configuration or properties of the
  4559. // consumer (head target). The link language also shouldn't matter, so ban
  4560. // it as well.
  4561. if (cge->GetHadHeadSensitiveCondition()) {
  4562. // Not reachable; all target-sensitive genexes actually fail to parse.
  4563. this->Makefile->IssueMessage(
  4564. MessageType::FATAL_ERROR,
  4565. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4566. this->GetName(),
  4567. "\" contains a condition that queries the "
  4568. "consuming target which is not supported."));
  4569. return false;
  4570. }
  4571. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  4572. // Not reachable; all link language genexes actually fail to parse.
  4573. this->Makefile->IssueMessage(
  4574. MessageType::FATAL_ERROR,
  4575. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4576. this->GetName(),
  4577. "\" contains a condition that queries the "
  4578. "link language which is not supported."));
  4579. return false;
  4580. }
  4581. std_prop_value = cge->Evaluate(this->LocalGenerator, "");
  4582. if (cge->GetHadContextSensitiveCondition()) {
  4583. this->Makefile->IssueMessage(
  4584. MessageType::FATAL_ERROR,
  4585. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4586. this->GetName(),
  4587. "\" contains a context-sensitive condition "
  4588. "that is not supported."));
  4589. return false;
  4590. }
  4591. }
  4592. auto use_std = cmIsOn(std_prop_value);
  4593. // If we have a value and it is not true, there's nothing to do.
  4594. if (std_prop && !use_std) {
  4595. return true;
  4596. }
  4597. for (auto const& config : configs) {
  4598. if (this->HaveCxxModuleSupport(config) != Cxx20SupportLevel::Supported) {
  4599. continue;
  4600. }
  4601. cm::optional<cmStandardLevel> explicitLevel =
  4602. this->GetExplicitStandardLevel("CXX", config);
  4603. if (!explicitLevel || *explicitLevel < cxxStd23) {
  4604. continue;
  4605. }
  4606. auto const stdLevel =
  4607. standardResolver.GetLevelString("CXX", *explicitLevel);
  4608. auto const targetName = cmStrCat("__CMAKE::CXX", stdLevel);
  4609. if (!this->Makefile->FindTargetToUse(targetName)) {
  4610. auto basicReason = this->Makefile->GetDefinition(cmStrCat(
  4611. "CMAKE_CXX", stdLevel, "_COMPILER_IMPORT_STD_NOT_FOUND_MESSAGE"));
  4612. std::string reason;
  4613. if (!basicReason.IsEmpty()) {
  4614. reason = cmStrCat(" Reason:\n ", basicReason);
  4615. }
  4616. this->Makefile->IssueMessage(
  4617. MessageType::FATAL_ERROR,
  4618. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4619. this->GetName(), "\" requires that the \"", targetName,
  4620. "\" target exist, but it was not provided by the toolchain.",
  4621. reason));
  4622. break;
  4623. }
  4624. // Check the experimental feature here as well. A toolchain may have
  4625. // provided the target and skipped the check in the toolchain preparation
  4626. // logic.
  4627. if (!cmExperimental::HasSupportEnabled(
  4628. *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
  4629. break;
  4630. }
  4631. this->Target->AppendProperty(
  4632. "LINK_LIBRARIES",
  4633. cmStrCat("$<BUILD_LOCAL_INTERFACE:$<$<CONFIG:", config, ">:", targetName,
  4634. ">>"));
  4635. }
  4636. return true;
  4637. }
  4638. bool cmGeneratorTarget::DiscoverSyntheticTargets(cmSyntheticTargetCache& cache,
  4639. std::string const& config)
  4640. {
  4641. std::vector<std::string> allConfigs =
  4642. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4643. cmOptionalLinkImplementation impl;
  4644. this->ComputeLinkImplementationLibraries(config, impl, UseTo::Link);
  4645. cmCxxModuleUsageEffects usage(this);
  4646. auto& SyntheticDeps = this->Configs[config].SyntheticDeps;
  4647. for (auto const& entry : impl.Libraries) {
  4648. auto const* gt = entry.Target;
  4649. if (!gt || !gt->IsImported()) {
  4650. continue;
  4651. }
  4652. if (gt->HaveCxx20ModuleSources()) {
  4653. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  4654. constexpr size_t HASH_TRUNCATION = 12;
  4655. auto dirhash = hasher.HashString(
  4656. gt->GetLocalGenerator()->GetCurrentBinaryDirectory());
  4657. std::string safeName = gt->GetName();
  4658. cmSystemTools::ReplaceString(safeName, ":", "_");
  4659. auto targetIdent =
  4660. hasher.HashString(cmStrCat("@d_", dirhash, "@u_", usage.GetHash()));
  4661. std::string targetName =
  4662. cmStrCat(safeName, "@synth_", targetIdent.substr(0, HASH_TRUNCATION));
  4663. // Check the cache to see if this instance of the imported target has
  4664. // already been created.
  4665. auto cached = cache.CxxModuleTargets.find(targetName);
  4666. cmGeneratorTarget const* synthDep = nullptr;
  4667. if (cached == cache.CxxModuleTargets.end()) {
  4668. auto const* model = gt->Target;
  4669. auto* mf = gt->Makefile;
  4670. auto* lg = gt->GetLocalGenerator();
  4671. auto* tgt = mf->AddSynthesizedTarget(cmStateEnums::INTERFACE_LIBRARY,
  4672. targetName);
  4673. // Copy relevant information from the existing IMPORTED target.
  4674. // Copy policies to the target.
  4675. tgt->CopyPolicyStatuses(model);
  4676. // Copy file sets.
  4677. {
  4678. auto fsNames = model->GetAllFileSetNames();
  4679. for (auto const& fsName : fsNames) {
  4680. auto const* fs = model->GetFileSet(fsName);
  4681. if (!fs) {
  4682. mf->IssueMessage(MessageType::INTERNAL_ERROR,
  4683. cmStrCat("Failed to find file set named '",
  4684. fsName, "' on target '",
  4685. tgt->GetName(), '\''));
  4686. continue;
  4687. }
  4688. auto* newFs = tgt
  4689. ->GetOrCreateFileSet(fs->GetName(), fs->GetType(),
  4690. fs->GetVisibility())
  4691. .first;
  4692. newFs->CopyEntries(fs);
  4693. }
  4694. }
  4695. // Copy imported C++ module properties.
  4696. tgt->CopyImportedCxxModulesEntries(model);
  4697. // Copy other properties which may affect the C++ module BMI
  4698. // generation.
  4699. tgt->CopyImportedCxxModulesProperties(model);
  4700. tgt->AddLinkLibrary(*mf,
  4701. cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
  4702. GENERAL_LibraryType);
  4703. // Apply usage requirements to the target.
  4704. usage.ApplyToTarget(tgt);
  4705. // Create the generator target and attach it to the local generator.
  4706. auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
  4707. synthDep = gtp.get();
  4708. cache.CxxModuleTargets[targetName] = synthDep;
  4709. // See `localGen->ComputeTargetCompileFeatures()` call in
  4710. // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
  4711. // this.
  4712. for (auto const& innerConfig : allConfigs) {
  4713. gtp->ComputeCompileFeatures(innerConfig);
  4714. }
  4715. // See `cmGlobalGenerator::ApplyCXXStdTargets` in
  4716. // `cmGlobalGenerator::Compute` for non-synthetic target resolutions.
  4717. gtp->ApplyCXXStdTargets();
  4718. gtp->DiscoverSyntheticTargets(cache, config);
  4719. lg->AddGeneratorTarget(std::move(gtp));
  4720. } else {
  4721. synthDep = cached->second;
  4722. }
  4723. SyntheticDeps[gt].push_back(synthDep);
  4724. }
  4725. }
  4726. return true;
  4727. }
  4728. bool cmGeneratorTarget::HasPackageReferences() const
  4729. {
  4730. return this->IsInBuildSystem() &&
  4731. !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
  4732. }
  4733. std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
  4734. {
  4735. cmList packageReferences;
  4736. if (this->IsInBuildSystem()) {
  4737. if (cmValue vsPackageReferences =
  4738. this->GetProperty("VS_PACKAGE_REFERENCES")) {
  4739. packageReferences.assign(*vsPackageReferences);
  4740. }
  4741. }
  4742. return std::move(packageReferences.data());
  4743. }
  4744. std::string cmGeneratorTarget::GetPDBDirectory(std::string const& config) const
  4745. {
  4746. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  4747. // Return the directory in which the target will be built.
  4748. return info->PdbDir;
  4749. }
  4750. return "";
  4751. }
  4752. bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
  4753. {
  4754. return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
  4755. }
  4756. bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
  4757. std::string const& gnuName,
  4758. std::string& out,
  4759. char const* newExt) const
  4760. {
  4761. if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
  4762. gnuName.substr(gnuName.size() - 6) == ".dll.a") {
  4763. out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
  4764. newExt ? newExt : ".lib");
  4765. return true;
  4766. }
  4767. return false;
  4768. }
  4769. bool cmGeneratorTarget::HasContextDependentSources() const
  4770. {
  4771. return this->SourcesAreContextDependent == Tribool::True;
  4772. }
  4773. bool cmGeneratorTarget::IsExecutableWithExports() const
  4774. {
  4775. return this->Target->IsExecutableWithExports();
  4776. }
  4777. bool cmGeneratorTarget::IsSharedLibraryWithExports() const
  4778. {
  4779. return this->Target->IsSharedLibraryWithExports();
  4780. }
  4781. bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
  4782. {
  4783. bool generate_Stubs = true;
  4784. if (this->GetGlobalGenerator()->IsXcode()) {
  4785. // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
  4786. // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
  4787. if (cmValue propGenStubs =
  4788. this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4789. generate_Stubs = propGenStubs == "YES";
  4790. } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
  4791. "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4792. generate_Stubs = varGenStubs == "YES";
  4793. }
  4794. }
  4795. return (this->IsDLLPlatform() &&
  4796. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4797. this->IsExecutableWithExports()) &&
  4798. // Assemblies which have only managed code do not have
  4799. // import libraries.
  4800. this->GetManagedType(config) != ManagedType::Managed) ||
  4801. (this->IsAIX() && this->IsExecutableWithExports()) ||
  4802. (this->Makefile->PlatformSupportsAppleTextStubs() &&
  4803. this->IsSharedLibraryWithExports() && generate_Stubs);
  4804. }
  4805. bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
  4806. {
  4807. return this->HasImportLibrary(config) ||
  4808. // On DLL platforms we always generate the import library name
  4809. // just in case the sources have export markup.
  4810. (this->IsDLLPlatform() &&
  4811. (this->GetType() == cmStateEnums::EXECUTABLE ||
  4812. this->GetType() == cmStateEnums::MODULE_LIBRARY));
  4813. }
  4814. bool cmGeneratorTarget::GetUseShortObjectNames(
  4815. cmStateEnums::IntermediateDirKind kind) const
  4816. {
  4817. return this->LocalGenerator->UseShortObjectNames(kind);
  4818. }
  4819. cmObjectLocations::UseShortPath
  4820. cmGeneratorTarget::GetUseShortObjectNamesForInstall() const
  4821. {
  4822. auto prop = this->Target->GetProperty("INSTALL_OBJECT_NAME_STRATEGY");
  4823. if (prop == "SHORT"_s) {
  4824. return cmObjectLocations::UseShortPath::Yes;
  4825. }
  4826. if (prop == "FULL"_s) {
  4827. return cmObjectLocations::UseShortPath::No;
  4828. }
  4829. if (prop.IsSet()) {
  4830. this->Makefile->IssueMessage(
  4831. MessageType::FATAL_ERROR,
  4832. cmStrCat("Property INSTALL_OBJECT_NAME_STRATEGY of target \"",
  4833. this->GetName(), "\" set to the unsupported strategy ", prop));
  4834. }
  4835. return cmObjectLocations::UseShortPath::No;
  4836. }
  4837. std::string cmGeneratorTarget::GetSupportDirectory(
  4838. cmStateEnums::IntermediateDirKind kind) const
  4839. {
  4840. cmLocalGenerator* lg = this->GetLocalGenerator();
  4841. return cmStrCat(lg->GetObjectOutputRoot(kind), '/',
  4842. lg->GetTargetDirectory(this, kind));
  4843. }
  4844. std::string cmGeneratorTarget::GetCMFSupportDirectory(
  4845. cmStateEnums::IntermediateDirKind kind) const
  4846. {
  4847. cmLocalGenerator* lg = this->GetLocalGenerator();
  4848. if (!lg->AlwaysUsesCMFPaths()) {
  4849. return cmStrCat(lg->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  4850. lg->GetTargetDirectory(this, kind));
  4851. }
  4852. return cmStrCat(lg->GetObjectOutputRoot(kind), '/',
  4853. lg->GetTargetDirectory(this, kind));
  4854. }
  4855. bool cmGeneratorTarget::IsLinkable() const
  4856. {
  4857. return (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4858. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4859. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  4860. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY ||
  4861. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4862. this->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  4863. this->IsExecutableWithExports());
  4864. }
  4865. bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
  4866. {
  4867. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  4868. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4869. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  4870. return false;
  4871. }
  4872. if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
  4873. // Do not use the linker dependency file because it includes shared
  4874. // libraries as well
  4875. return false;
  4876. }
  4877. std::string const depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
  4878. auto linkLanguage = this->GetLinkerLanguage(config);
  4879. std::string const langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
  4880. "_LINK_DEPENDS_USE_LINKER") };
  4881. return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
  4882. this->Makefile->IsOn(depsUseLinker)) &&
  4883. this->Makefile->IsOn(langDepsUseLinker);
  4884. }
  4885. bool cmGeneratorTarget::IsFrameworkOnApple() const
  4886. {
  4887. return this->Target->IsFrameworkOnApple();
  4888. }
  4889. bool cmGeneratorTarget::IsArchivedAIXSharedLibrary() const
  4890. {
  4891. return this->Target->IsArchivedAIXSharedLibrary();
  4892. }
  4893. bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
  4894. std::string const& config) const
  4895. {
  4896. if (this->IsApple() && this->IsImported() &&
  4897. (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4898. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4899. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) {
  4900. std::string cfg = config;
  4901. if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
  4902. // FIXME(#25515): Remove the need for this workaround.
  4903. // The Xcode generator queries include directories without any
  4904. // specific configuration. Pick one in case this target does
  4905. // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
  4906. cfg =
  4907. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
  4908. }
  4909. return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
  4910. }
  4911. return false;
  4912. }
  4913. bool cmGeneratorTarget::IsAppBundleOnApple() const
  4914. {
  4915. return this->Target->IsAppBundleOnApple();
  4916. }
  4917. bool cmGeneratorTarget::IsXCTestOnApple() const
  4918. {
  4919. return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
  4920. }
  4921. bool cmGeneratorTarget::IsCFBundleOnApple() const
  4922. {
  4923. return (this->GetType() == cmStateEnums::MODULE_LIBRARY && this->IsApple() &&
  4924. this->GetPropertyAsBool("BUNDLE"));
  4925. }
  4926. cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
  4927. std::string const& propval) const
  4928. {
  4929. // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
  4930. // or only C++/CLI) does only depend on whether the property is an empty
  4931. // string or contains any value at all. In Visual Studio generators
  4932. // this propval is prepended with /clr[:] which results in:
  4933. //
  4934. // 1. propval does not exist: no /clr flag, unmanaged target, has import
  4935. // lib
  4936. // 2. empty propval: add /clr as flag, mixed unmanaged/managed
  4937. // target, has import lib
  4938. // 3. netcore propval: add /clr:netcore as flag, mixed
  4939. // unmanaged/managed target, has import lib.
  4940. // 4. any value (safe,pure): add /clr:[propval] as flag, target with
  4941. // managed code only, no import lib
  4942. if (propval.empty() || propval == "netcore") {
  4943. return ManagedType::Mixed;
  4944. }
  4945. return ManagedType::Managed;
  4946. }
  4947. cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
  4948. std::string const& config) const
  4949. {
  4950. // Only libraries and executables can be managed targets.
  4951. if (this->GetType() > cmStateEnums::SHARED_LIBRARY) {
  4952. return ManagedType::Undefined;
  4953. }
  4954. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4955. return ManagedType::Native;
  4956. }
  4957. // Check imported target.
  4958. if (this->IsImported()) {
  4959. if (cmGeneratorTarget::ImportInfo const* info =
  4960. this->GetImportInfo(config)) {
  4961. return info->Managed;
  4962. }
  4963. return ManagedType::Undefined;
  4964. }
  4965. // Check for explicitly set clr target property.
  4966. if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  4967. return this->CheckManagedType(*clr);
  4968. }
  4969. // C# targets are always managed. This language specific check
  4970. // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
  4971. // has to be set manually for C# targets.
  4972. return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
  4973. }
  4974. bool cmGeneratorTarget::AddHeaderSetVerification()
  4975. {
  4976. if (!this->GetPropertyAsBool("VERIFY_INTERFACE_HEADER_SETS")) {
  4977. return true;
  4978. }
  4979. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4980. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4981. this->GetType() != cmStateEnums::UNKNOWN_LIBRARY &&
  4982. this->GetType() != cmStateEnums::OBJECT_LIBRARY &&
  4983. this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4984. !this->IsExecutableWithExports()) {
  4985. return true;
  4986. }
  4987. auto verifyValue = this->GetProperty("INTERFACE_HEADER_SETS_TO_VERIFY");
  4988. bool const all = verifyValue.IsEmpty();
  4989. std::set<std::string> verifySet;
  4990. if (!all) {
  4991. cmList verifyList{ verifyValue };
  4992. verifySet.insert(verifyList.begin(), verifyList.end());
  4993. }
  4994. cmTarget* verifyTarget = nullptr;
  4995. cmTarget* allVerifyTarget =
  4996. this->GlobalGenerator->GetMakefiles().front()->FindTargetToUse(
  4997. "all_verify_interface_header_sets",
  4998. { cmStateEnums::TargetDomain::NATIVE });
  4999. auto interfaceFileSetEntries = this->Target->GetInterfaceHeaderSetsEntries();
  5000. std::set<cmFileSet*> fileSets;
  5001. for (auto const& entry : interfaceFileSetEntries) {
  5002. for (auto const& name : cmList{ entry.Value }) {
  5003. if (all || verifySet.count(name)) {
  5004. fileSets.insert(this->Target->GetFileSet(name));
  5005. verifySet.erase(name);
  5006. }
  5007. }
  5008. }
  5009. if (!verifySet.empty()) {
  5010. this->Makefile->IssueMessage(
  5011. MessageType::FATAL_ERROR,
  5012. cmStrCat("Property INTERFACE_HEADER_SETS_TO_VERIFY of target \"",
  5013. this->GetName(),
  5014. "\" contained the following header sets that are nonexistent "
  5015. "or not INTERFACE:\n ",
  5016. cmJoin(verifySet, "\n ")));
  5017. return false;
  5018. }
  5019. cm::optional<std::set<std::string>> languages;
  5020. for (auto* fileSet : fileSets) {
  5021. auto dirCges = fileSet->CompileDirectoryEntries();
  5022. auto fileCges = fileSet->CompileFileEntries();
  5023. static auto const contextSensitive =
  5024. [](std::unique_ptr<cmCompiledGeneratorExpression> const& cge) {
  5025. return cge->GetHadContextSensitiveCondition();
  5026. };
  5027. bool dirCgesContextSensitive = false;
  5028. bool fileCgesContextSensitive = false;
  5029. std::vector<std::string> dirs;
  5030. std::map<std::string, std::vector<std::string>> filesPerDir;
  5031. bool first = true;
  5032. for (auto const& config : this->Makefile->GetGeneratorConfigs(
  5033. cmMakefile::GeneratorConfigQuery::IncludeEmptyConfig)) {
  5034. cm::GenEx::Context context(this->LocalGenerator, config);
  5035. if (first || dirCgesContextSensitive) {
  5036. dirs = fileSet->EvaluateDirectoryEntries(dirCges, context, this);
  5037. dirCgesContextSensitive =
  5038. std::any_of(dirCges.begin(), dirCges.end(), contextSensitive);
  5039. }
  5040. if (first || fileCgesContextSensitive) {
  5041. filesPerDir.clear();
  5042. for (auto const& fileCge : fileCges) {
  5043. fileSet->EvaluateFileEntry(dirs, filesPerDir, fileCge, context,
  5044. this);
  5045. if (fileCge->GetHadContextSensitiveCondition()) {
  5046. fileCgesContextSensitive = true;
  5047. }
  5048. }
  5049. }
  5050. for (auto const& files : filesPerDir) {
  5051. for (auto const& file : files.second) {
  5052. std::string filename = this->GenerateHeaderSetVerificationFile(
  5053. *this->Makefile->GetOrCreateSource(file), files.first, languages);
  5054. if (filename.empty()) {
  5055. continue;
  5056. }
  5057. if (!verifyTarget) {
  5058. {
  5059. cmMakefile::PolicyPushPop polScope(this->Makefile);
  5060. this->Makefile->SetPolicy(cmPolicies::CMP0119, cmPolicies::NEW);
  5061. verifyTarget = this->Makefile->AddLibrary(
  5062. cmStrCat(this->GetName(), "_verify_interface_header_sets"),
  5063. cmStateEnums::OBJECT_LIBRARY, {}, true);
  5064. }
  5065. verifyTarget->AddLinkLibrary(
  5066. *this->Makefile, this->GetName(),
  5067. cmTargetLinkLibraryType::GENERAL_LibraryType);
  5068. verifyTarget->SetProperty("AUTOMOC", "OFF");
  5069. verifyTarget->SetProperty("AUTORCC", "OFF");
  5070. verifyTarget->SetProperty("AUTOUIC", "OFF");
  5071. verifyTarget->SetProperty("DISABLE_PRECOMPILE_HEADERS", "ON");
  5072. verifyTarget->SetProperty("UNITY_BUILD", "OFF");
  5073. verifyTarget->SetProperty("CXX_SCAN_FOR_MODULES", "OFF");
  5074. verifyTarget->FinalizeTargetConfiguration(
  5075. this->Makefile->GetCompileDefinitionsEntries());
  5076. if (!allVerifyTarget) {
  5077. allVerifyTarget = this->GlobalGenerator->GetMakefiles()
  5078. .front()
  5079. ->AddNewUtilityTarget(
  5080. "all_verify_interface_header_sets", true);
  5081. }
  5082. allVerifyTarget->AddUtility(verifyTarget->GetName(), false);
  5083. }
  5084. if (fileCgesContextSensitive) {
  5085. filename = cmStrCat("$<$<CONFIG:", config, ">:", filename, '>');
  5086. }
  5087. verifyTarget->AddSource(filename);
  5088. }
  5089. }
  5090. if (!dirCgesContextSensitive && !fileCgesContextSensitive) {
  5091. break;
  5092. }
  5093. first = false;
  5094. }
  5095. }
  5096. if (verifyTarget) {
  5097. this->LocalGenerator->AddGeneratorTarget(
  5098. cm::make_unique<cmGeneratorTarget>(verifyTarget, this->LocalGenerator));
  5099. }
  5100. return true;
  5101. }
  5102. std::string cmGeneratorTarget::GenerateHeaderSetVerificationFile(
  5103. cmSourceFile& source, std::string const& dir,
  5104. cm::optional<std::set<std::string>>& languages) const
  5105. {
  5106. std::string extension;
  5107. std::string language = source.GetOrDetermineLanguage();
  5108. if (source.GetPropertyAsBool("SKIP_LINTING")) {
  5109. return std::string{};
  5110. }
  5111. if (language.empty()) {
  5112. if (!languages) {
  5113. languages.emplace();
  5114. for (auto const& tgtSource : this->GetAllConfigSources()) {
  5115. auto const& tgtSourceLanguage =
  5116. tgtSource.Source->GetOrDetermineLanguage();
  5117. if (tgtSourceLanguage == "CXX") {
  5118. languages->insert("CXX");
  5119. break; // C++ overrides everything else, so we don't need to keep
  5120. // checking.
  5121. }
  5122. if (tgtSourceLanguage == "C") {
  5123. languages->insert("C");
  5124. }
  5125. }
  5126. if (languages->empty()) {
  5127. std::vector<std::string> languagesVector;
  5128. this->GlobalGenerator->GetEnabledLanguages(languagesVector);
  5129. languages->insert(languagesVector.begin(), languagesVector.end());
  5130. }
  5131. }
  5132. if (languages->count("CXX")) {
  5133. language = "CXX";
  5134. } else if (languages->count("C")) {
  5135. language = "C";
  5136. }
  5137. }
  5138. if (language == "C") {
  5139. extension = ".c";
  5140. } else if (language == "CXX") {
  5141. extension = ".cxx";
  5142. } else {
  5143. return "";
  5144. }
  5145. std::string headerFilename = dir;
  5146. if (!headerFilename.empty()) {
  5147. headerFilename += '/';
  5148. }
  5149. headerFilename += source.GetLocation().GetName();
  5150. auto filename = cmStrCat(
  5151. this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->GetName(),
  5152. "_verify_interface_header_sets/", headerFilename, extension);
  5153. auto* verificationSource = this->Makefile->GetOrCreateSource(filename);
  5154. source.SetSpecialSourceType(
  5155. cmSourceFile::SpecialSourceType::HeaderSetVerificationSource);
  5156. verificationSource->SetProperty("LANGUAGE", language);
  5157. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(filename));
  5158. cmGeneratedFileStream fout(filename);
  5159. fout.SetCopyIfDifferent(true);
  5160. // The IWYU "associated" pragma tells include-what-you-use to
  5161. // consider the headerFile as part of the entire language
  5162. // unit within include-what-you-use and as a result allows
  5163. // one to get IWYU advice for headers.
  5164. // Also suppress clang-tidy include checks in generated code.
  5165. fout
  5166. << "/* NOLINTNEXTLINE(misc-header-include-cycle,misc-include-cleaner) */\n"
  5167. << "#include <" << headerFilename << "> /* IWYU pragma: associated */\n";
  5168. fout.close();
  5169. return filename;
  5170. }
  5171. std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
  5172. std::string const& config) const
  5173. {
  5174. if (!(this->IsApple() && this->IsImported() &&
  5175. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  5176. this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  5177. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY))) {
  5178. return {};
  5179. }
  5180. std::string desiredConfig = config;
  5181. if (config.empty()) {
  5182. desiredConfig = "NOCONFIG";
  5183. }
  5184. std::string result;
  5185. cmValue loc = nullptr;
  5186. cmValue imp = nullptr;
  5187. std::string suffix;
  5188. if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
  5189. if (loc) {
  5190. result = *loc;
  5191. } else {
  5192. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  5193. if (cmValue configLocation = this->GetProperty(impProp)) {
  5194. result = *configLocation;
  5195. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  5196. result = *location;
  5197. }
  5198. }
  5199. if (cmSystemTools::IsPathToXcFramework(result)) {
  5200. return result;
  5201. }
  5202. }
  5203. return {};
  5204. }
  5205. bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
  5206. {
  5207. auto sources = this->GetSourceFiles(config);
  5208. bool const have_direct = std::any_of(
  5209. sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
  5210. return sf.Value->GetLanguage() == "Fortran"_s;
  5211. });
  5212. bool have_via_target_objects = false;
  5213. if (!have_direct) {
  5214. auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
  5215. have_via_target_objects =
  5216. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  5217. [&config](cmGeneratorTarget const* tgt) -> bool {
  5218. return tgt->HaveFortranSources(config);
  5219. });
  5220. }
  5221. return have_direct || have_via_target_objects;
  5222. }
  5223. bool cmGeneratorTarget::HaveFortranSources() const
  5224. {
  5225. auto sources = this->GetAllConfigSources();
  5226. bool const have_direct = std::any_of(
  5227. sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
  5228. return sf.Source->GetLanguage() == "Fortran"_s;
  5229. });
  5230. bool have_via_target_objects = false;
  5231. if (!have_direct) {
  5232. std::vector<std::string> configs =
  5233. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  5234. for (auto const& config : configs) {
  5235. auto const sourceObjectLibraries =
  5236. this->GetSourceObjectLibraries(config);
  5237. have_via_target_objects =
  5238. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  5239. [&config](cmGeneratorTarget const* tgt) -> bool {
  5240. return tgt->HaveFortranSources(config);
  5241. });
  5242. if (have_via_target_objects) {
  5243. break;
  5244. }
  5245. }
  5246. }
  5247. return have_direct || have_via_target_objects;
  5248. }
  5249. bool cmGeneratorTarget::HaveCxx20ModuleSources(std::string* errorMessage) const
  5250. {
  5251. auto const& fs_names = this->Target->GetAllFileSetNames();
  5252. return std::any_of(
  5253. fs_names.begin(), fs_names.end(),
  5254. [this, errorMessage](std::string const& name) -> bool {
  5255. auto const* file_set = this->Target->GetFileSet(name);
  5256. if (!file_set) {
  5257. auto message = cmStrCat("Target \"", this->Target->GetName(),
  5258. "\" is tracked to have file set \"", name,
  5259. "\", but it was not found.");
  5260. if (errorMessage) {
  5261. *errorMessage = std::move(message);
  5262. } else {
  5263. this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
  5264. }
  5265. return false;
  5266. }
  5267. auto const& fs_type = file_set->GetType();
  5268. return fs_type == "CXX_MODULES"_s;
  5269. });
  5270. }
  5271. cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
  5272. std::string const& config) const
  5273. {
  5274. auto const* state = this->Makefile->GetState();
  5275. if (!state->GetLanguageEnabled("CXX")) {
  5276. return Cxx20SupportLevel::MissingCxx;
  5277. }
  5278. cmValue standardDefault =
  5279. this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  5280. if (!standardDefault || standardDefault->empty()) {
  5281. // We do not know any meaningful C++ standard levels for this compiler.
  5282. return Cxx20SupportLevel::NoCxx20;
  5283. }
  5284. cmStandardLevelResolver standardResolver(this->Makefile);
  5285. cmStandardLevel const cxxStd20 =
  5286. *standardResolver.LanguageStandardLevel("CXX", "20");
  5287. cm::optional<cmStandardLevel> explicitLevel =
  5288. this->GetExplicitStandardLevel("CXX", config);
  5289. if (!explicitLevel || *explicitLevel < cxxStd20) {
  5290. return Cxx20SupportLevel::NoCxx20;
  5291. }
  5292. cmValue scandepRule =
  5293. this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
  5294. if (!scandepRule) {
  5295. return Cxx20SupportLevel::MissingRule;
  5296. }
  5297. return Cxx20SupportLevel::Supported;
  5298. }
  5299. void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
  5300. {
  5301. bool haveScannableSources = false;
  5302. // Check for `CXX_MODULE*` file sets and a lack of support.
  5303. if (this->HaveCxx20ModuleSources()) {
  5304. haveScannableSources = true;
  5305. }
  5306. if (!haveScannableSources) {
  5307. // Check to see if there are regular sources that have requested scanning.
  5308. auto sources = this->GetSourceFiles(config);
  5309. for (auto const& source : sources) {
  5310. auto const* sf = source.Value;
  5311. auto const& lang = sf->GetLanguage();
  5312. if (lang != "CXX"_s) {
  5313. continue;
  5314. }
  5315. // Ignore sources which do not need dyndep.
  5316. if (this->NeedDyndepForSource(lang, config, sf)) {
  5317. haveScannableSources = true;
  5318. }
  5319. }
  5320. }
  5321. // If there isn't anything scannable, ignore it.
  5322. if (!haveScannableSources) {
  5323. return;
  5324. }
  5325. // If the generator doesn't support modules at all, error that we have
  5326. // sources that require the support.
  5327. if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5328. cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
  5329. this->Makefile->IssueMessage(
  5330. MessageType::FATAL_ERROR,
  5331. cmStrCat("The target named \"", this->GetName(),
  5332. "\" has C++ sources that may use modules, but modules are not "
  5333. "supported by this generator:\n ",
  5334. this->GetGlobalGenerator()->GetName(),
  5335. "\n"
  5336. "Modules are supported only by Ninja, Ninja Multi-Config, "
  5337. "and Visual Studio generators for VS 17.4 and newer. "
  5338. "See the cmake-cxxmodules(7) manual for details. "
  5339. "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
  5340. "disable scanning."));
  5341. return;
  5342. }
  5343. switch (this->HaveCxxModuleSupport(config)) {
  5344. case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
  5345. this->Makefile->IssueMessage(
  5346. MessageType::FATAL_ERROR,
  5347. cmStrCat("The target named \"", this->GetName(),
  5348. "\" has C++ sources that use modules, but the \"CXX\" "
  5349. "language has not been enabled."));
  5350. break;
  5351. case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
  5352. cmStandardLevelResolver standardResolver(this->Makefile);
  5353. auto effStandard =
  5354. standardResolver.GetEffectiveStandard(this, "CXX", config);
  5355. if (effStandard.empty()) {
  5356. effStandard = "; no C++ standard found";
  5357. } else {
  5358. effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
  5359. }
  5360. this->Makefile->IssueMessage(
  5361. MessageType::FATAL_ERROR,
  5362. cmStrCat(
  5363. "The target named \"", this->GetName(),
  5364. "\" has C++ sources that use modules, but does not include "
  5365. "\"cxx_std_20\" (or newer) among its `target_compile_features`",
  5366. effStandard, '.'));
  5367. } break;
  5368. case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
  5369. this->Makefile->IssueMessage(
  5370. MessageType::FATAL_ERROR,
  5371. cmStrCat("The target named \"", this->GetName(),
  5372. "\" has C++ sources that may use modules, but the compiler "
  5373. "does not provide a way to discover the import graph "
  5374. "dependencies. See the cmake-cxxmodules(7) manual for "
  5375. "details. Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
  5376. "enable or disable scanning."));
  5377. } break;
  5378. case cmGeneratorTarget::Cxx20SupportLevel::Supported:
  5379. // All is well.
  5380. break;
  5381. }
  5382. }
  5383. bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
  5384. std::string const& config) const
  5385. {
  5386. if (lang != "CXX"_s) {
  5387. return false;
  5388. }
  5389. return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
  5390. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5391. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5392. }
  5393. bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
  5394. std::string const& config) const
  5395. {
  5396. return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
  5397. }
  5398. cmFileSet const* cmGeneratorTarget::GetFileSetForSource(
  5399. std::string const& config, cmSourceFile const* sf) const
  5400. {
  5401. this->BuildFileSetInfoCache(config);
  5402. auto const& path = sf->GetFullPath();
  5403. auto const& per_config = this->Configs[config];
  5404. auto const fsit = per_config.FileSetCache.find(path);
  5405. if (fsit == per_config.FileSetCache.end()) {
  5406. return nullptr;
  5407. }
  5408. return fsit->second;
  5409. }
  5410. bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
  5411. std::string const& config,
  5412. cmSourceFile const* sf) const
  5413. {
  5414. // Fortran always needs to be scanned.
  5415. if (lang == "Fortran"_s) {
  5416. return true;
  5417. }
  5418. // Only C++ code needs scanned otherwise.
  5419. if (lang != "CXX"_s) {
  5420. return false;
  5421. }
  5422. // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
  5423. // enforced elsewhere).
  5424. auto const* fs = this->GetFileSetForSource(config, sf);
  5425. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  5426. return true;
  5427. }
  5428. auto targetDyndep = this->NeedCxxDyndep(config);
  5429. if (targetDyndep == CxxModuleSupport::Unavailable) {
  5430. return false;
  5431. }
  5432. auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
  5433. if (sfProp.IsSet()) {
  5434. return sfProp.IsOn();
  5435. }
  5436. return targetDyndep == CxxModuleSupport::Enabled;
  5437. }
  5438. cmGeneratorTarget::CxxModuleSupport cmGeneratorTarget::NeedCxxDyndep(
  5439. std::string const& config) const
  5440. {
  5441. bool haveRule = false;
  5442. switch (this->HaveCxxModuleSupport(config)) {
  5443. case Cxx20SupportLevel::MissingCxx:
  5444. case Cxx20SupportLevel::NoCxx20:
  5445. return CxxModuleSupport::Unavailable;
  5446. case Cxx20SupportLevel::MissingRule:
  5447. break;
  5448. case Cxx20SupportLevel::Supported:
  5449. haveRule = true;
  5450. break;
  5451. }
  5452. bool haveGeneratorSupport =
  5453. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5454. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5455. auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
  5456. if (tgtProp.IsSet()) {
  5457. return tgtProp.IsOn() ? CxxModuleSupport::Enabled
  5458. : CxxModuleSupport::Disabled;
  5459. }
  5460. CxxModuleSupport policyAnswer = CxxModuleSupport::Unavailable;
  5461. switch (this->GetPolicyStatusCMP0155()) {
  5462. case cmPolicies::WARN:
  5463. case cmPolicies::OLD:
  5464. // The OLD behavior is to not scan the source.
  5465. policyAnswer = CxxModuleSupport::Disabled;
  5466. break;
  5467. case cmPolicies::NEW:
  5468. // The NEW behavior is to scan the source if the compiler supports
  5469. // scanning and the generator supports it.
  5470. if (haveRule && haveGeneratorSupport) {
  5471. policyAnswer = CxxModuleSupport::Enabled;
  5472. } else {
  5473. policyAnswer = CxxModuleSupport::Disabled;
  5474. }
  5475. break;
  5476. }
  5477. return policyAnswer;
  5478. }
  5479. std::string cmGeneratorTarget::BuildDatabasePath(
  5480. std::string const& lang, std::string const& config) const
  5481. {
  5482. // Check to see if the target wants it.
  5483. if (!this->GetPropertyAsBool("EXPORT_BUILD_DATABASE")) {
  5484. return {};
  5485. }
  5486. if (!cmExperimental::HasSupportEnabled(
  5487. *this->Makefile, cmExperimental::Feature::ExportBuildDatabase)) {
  5488. return {};
  5489. }
  5490. // Check to see if the generator supports it.
  5491. if (!this->GetGlobalGenerator()->SupportsBuildDatabase()) {
  5492. return {};
  5493. }
  5494. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  5495. return cmStrCat(this->GetSupportDirectory(), '/', config, '/', lang,
  5496. "_build_database.json");
  5497. }
  5498. return cmStrCat(this->GetSupportDirectory(), '/', lang,
  5499. "_build_database.json");
  5500. }
  5501. void cmGeneratorTarget::BuildFileSetInfoCache(std::string const& config) const
  5502. {
  5503. auto& per_config = this->Configs[config];
  5504. if (per_config.BuiltFileSetCache) {
  5505. return;
  5506. }
  5507. auto const* tgt = this->Target;
  5508. for (auto const& name : tgt->GetAllFileSetNames()) {
  5509. auto const* file_set = tgt->GetFileSet(name);
  5510. if (!file_set) {
  5511. tgt->GetMakefile()->IssueMessage(
  5512. MessageType::INTERNAL_ERROR,
  5513. cmStrCat("Target \"", tgt->GetName(),
  5514. "\" is tracked to have file set \"", name,
  5515. "\", but it was not found."));
  5516. continue;
  5517. }
  5518. cm::GenEx::Context context(this->LocalGenerator, config);
  5519. auto fileEntries = file_set->CompileFileEntries();
  5520. auto directoryEntries = file_set->CompileDirectoryEntries();
  5521. auto directories =
  5522. file_set->EvaluateDirectoryEntries(directoryEntries, context, this);
  5523. std::map<std::string, std::vector<std::string>> files;
  5524. for (auto const& entry : fileEntries) {
  5525. file_set->EvaluateFileEntry(directories, files, entry, context, this);
  5526. }
  5527. for (auto const& it : files) {
  5528. for (auto const& filename : it.second) {
  5529. auto collapsedFile = cmSystemTools::CollapseFullPath(filename);
  5530. per_config.FileSetCache[collapsedFile] = file_set;
  5531. }
  5532. }
  5533. }
  5534. per_config.BuiltFileSetCache = true;
  5535. }
  5536. std::string cmGeneratorTarget::GetSwiftModuleName() const
  5537. {
  5538. return this->GetPropertyOrDefault("Swift_MODULE_NAME", this->GetName());
  5539. }
  5540. std::string cmGeneratorTarget::GetSwiftModuleFileName() const
  5541. {
  5542. std::string moduleFilename = this->GetPropertyOrDefault(
  5543. "Swift_MODULE", this->GetSwiftModuleName() + ".swiftmodule");
  5544. if (this->GetPolicyStatusCMP0195() == cmPolicies::NEW) {
  5545. if (cmValue moduleTriple =
  5546. this->Makefile->GetDefinition("CMAKE_Swift_MODULE_TRIPLE")) {
  5547. moduleFilename += "/" + *moduleTriple + ".swiftmodule";
  5548. }
  5549. }
  5550. return moduleFilename;
  5551. }
  5552. std::string cmGeneratorTarget::GetSwiftModuleDirectory(
  5553. std::string const& config) const
  5554. {
  5555. // This is like the *_OUTPUT_DIRECTORY properties except that we don't have a
  5556. // separate per-configuration target property.
  5557. //
  5558. // The property expands generator expressions. Multi-config generators append
  5559. // a per-configuration subdirectory to the specified directory unless a
  5560. // generator expression is used.
  5561. bool appendConfigDir = true;
  5562. std::string moduleDirectory;
  5563. if (cmValue value = this->GetProperty("Swift_MODULE_DIRECTORY")) {
  5564. moduleDirectory = cmGeneratorExpression::Evaluate(
  5565. *value, this->LocalGenerator, config, this);
  5566. appendConfigDir = *value == moduleDirectory;
  5567. }
  5568. if (moduleDirectory.empty()) {
  5569. moduleDirectory = this->LocalGenerator->GetCurrentBinaryDirectory();
  5570. }
  5571. if (appendConfigDir) {
  5572. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  5573. "/", config, "", moduleDirectory);
  5574. }
  5575. return moduleDirectory;
  5576. }
  5577. std::string cmGeneratorTarget::GetSwiftModulePath(
  5578. std::string const& config) const
  5579. {
  5580. return this->GetSwiftModuleDirectory(config) + "/" +
  5581. this->GetSwiftModuleFileName();
  5582. }
  5583. std::string cmGeneratorTarget::GetPropertyOrDefault(
  5584. std::string const& property, std::string defaultValue) const
  5585. {
  5586. if (cmValue name = this->GetProperty(property)) {
  5587. return *name;
  5588. }
  5589. return defaultValue;
  5590. }