cmGeneratorTarget.cxx 208 KB

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