cmGeneratorTarget.cxx 205 KB

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