cmGeneratorTarget.cxx 197 KB

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