cmGeneratorTarget.cxx 178 KB

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