cmGeneratorTarget.cxx 206 KB

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