cmLocalGenerator.cxx 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944
  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 "cmLocalGenerator.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <initializer_list>
  11. #include <iterator>
  12. #include <sstream>
  13. #include <type_traits>
  14. #include <unordered_set>
  15. #include <utility>
  16. #include <vector>
  17. #include <cm/memory>
  18. #include <cm/optional>
  19. #include <cm/string_view>
  20. #include <cmext/algorithm>
  21. #include <cmext/string_view>
  22. #include "cmsys/RegularExpression.hxx"
  23. #include "cmAlgorithms.h"
  24. #include "cmComputeLinkInformation.h"
  25. #include "cmCryptoHash.h"
  26. #include "cmCustomCommand.h"
  27. #include "cmCustomCommandGenerator.h"
  28. #include "cmCustomCommandLines.h"
  29. #include "cmCustomCommandTypes.h"
  30. #include "cmGeneratedFileStream.h"
  31. #include "cmGeneratorExpression.h"
  32. #include "cmGeneratorExpressionEvaluationFile.h"
  33. #include "cmGeneratorTarget.h"
  34. #include "cmGlobalGenerator.h"
  35. #include "cmInstallGenerator.h"
  36. #include "cmInstallScriptGenerator.h"
  37. #include "cmInstallTargetGenerator.h"
  38. #include "cmLinkLineComputer.h"
  39. #include "cmLinkLineDeviceComputer.h"
  40. #include "cmList.h"
  41. #include "cmMakefile.h"
  42. #include "cmMessageType.h"
  43. #include "cmRange.h"
  44. #include "cmRulePlaceholderExpander.h"
  45. #include "cmSourceFile.h"
  46. #include "cmSourceFileLocation.h"
  47. #include "cmSourceFileLocationKind.h"
  48. #include "cmStandardLevelResolver.h"
  49. #include "cmState.h"
  50. #include "cmStateDirectory.h"
  51. #include "cmStateTypes.h"
  52. #include "cmStringAlgorithms.h"
  53. #include "cmSystemTools.h"
  54. #include "cmTarget.h"
  55. #include "cmTestGenerator.h"
  56. #include "cmValue.h"
  57. #include "cmVersion.h"
  58. #include "cmake.h"
  59. #if defined(__HAIKU__)
  60. # include <FindDirectory.h>
  61. # include <StorageDefs.h>
  62. #endif
  63. // List of variables that are replaced when
  64. // rules are expanded. These variables are
  65. // replaced in the form <var> with GetSafeDefinition(var).
  66. // ${LANG} is replaced in the variable first with all enabled
  67. // languages.
  68. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  69. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  70. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  71. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  72. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  73. "CMAKE_${LANG}_LINK_FLAGS",
  74. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  75. "CMAKE_${LANG}_ARCHIVE",
  76. "CMAKE_AR",
  77. "CMAKE_CURRENT_SOURCE_DIR",
  78. "CMAKE_CURRENT_BINARY_DIR",
  79. "CMAKE_RANLIB",
  80. "CMAKE_MT",
  81. "CMAKE_TAPI",
  82. "CMAKE_CUDA_HOST_COMPILER",
  83. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  84. "CMAKE_HIP_HOST_COMPILER",
  85. "CMAKE_HIP_HOST_LINK_LAUNCHER",
  86. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  87. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  88. : cmOutputConverter(makefile->GetStateSnapshot())
  89. , DirectoryBacktrace(makefile->GetBacktrace())
  90. {
  91. this->GlobalGenerator = gg;
  92. this->Makefile = makefile;
  93. this->AliasTargets = makefile->GetAliasTargets();
  94. this->EmitUniversalBinaryFlags = true;
  95. this->BackwardsCompatibility = 0;
  96. this->BackwardsCompatibilityFinal = false;
  97. this->ComputeObjectMaxPath();
  98. // Canonicalize entries of the CPATH environment variable the same
  99. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  100. {
  101. std::vector<std::string> cpath;
  102. cmSystemTools::GetPath(cpath, "CPATH");
  103. for (std::string const& cp : cpath) {
  104. if (cmSystemTools::FileIsFullPath(cp)) {
  105. this->EnvCPATH.emplace_back(cmSystemTools::CollapseFullPath(cp));
  106. }
  107. }
  108. }
  109. std::vector<std::string> enabledLanguages =
  110. this->GetState()->GetEnabledLanguages();
  111. if (cmValue sysrootCompile =
  112. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  113. this->CompilerSysroot = *sysrootCompile;
  114. } else {
  115. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  116. }
  117. if (cmValue sysrootLink =
  118. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  119. this->LinkerSysroot = *sysrootLink;
  120. } else {
  121. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  122. }
  123. // OSX SYSROOT can be required by some tools, like tapi
  124. {
  125. cmValue osxSysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  126. this->VariableMappings["CMAKE_OSX_SYSROOT"] =
  127. osxSysroot.IsEmpty() ? "/" : this->EscapeForShell(*osxSysroot, true);
  128. }
  129. if (cmValue appleArchSysroots =
  130. this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
  131. std::string const& appleArchs =
  132. this->Makefile->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  133. cmList archs(appleArchs);
  134. cmList sysroots{ appleArchSysroots, cmList::EmptyElements::Yes };
  135. if (archs.size() == sysroots.size()) {
  136. for (cmList::size_type i = 0; i < archs.size(); ++i) {
  137. this->AppleArchSysroots[archs[i]] = sysroots[i];
  138. }
  139. } else {
  140. std::string const e =
  141. cmStrCat("CMAKE_APPLE_ARCH_SYSROOTS:\n ", *appleArchSysroots,
  142. "\n"
  143. "is not the same length as CMAKE_OSX_ARCHITECTURES:\n ",
  144. appleArchs);
  145. this->IssueMessage(MessageType::FATAL_ERROR, e);
  146. }
  147. }
  148. for (std::string const& lang : enabledLanguages) {
  149. if (lang == "NONE") {
  150. continue;
  151. }
  152. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  153. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  154. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  155. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  156. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  157. std::string const& compilerOptionTarget =
  158. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  159. std::string const& compilerExternalToolchain =
  160. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  161. std::string const& compilerOptionExternalToolchain =
  162. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  163. std::string const& compilerOptionSysroot =
  164. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  165. this->VariableMappings[compilerArg1] =
  166. this->Makefile->GetSafeDefinition(compilerArg1);
  167. this->VariableMappings[compilerTarget] =
  168. this->Makefile->GetSafeDefinition(compilerTarget);
  169. this->VariableMappings[compilerOptionTarget] =
  170. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  171. this->VariableMappings[compilerExternalToolchain] =
  172. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  173. this->VariableMappings[compilerOptionExternalToolchain] =
  174. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  175. this->VariableMappings[compilerOptionSysroot] =
  176. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  177. for (std::string replaceVar : ruleReplaceVars) {
  178. if (replaceVar.find("${LANG}") != std::string::npos) {
  179. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  180. }
  181. this->VariableMappings[replaceVar] =
  182. this->Makefile->GetSafeDefinition(replaceVar);
  183. }
  184. }
  185. }
  186. std::unique_ptr<cmRulePlaceholderExpander>
  187. cmLocalGenerator::CreateRulePlaceholderExpander() const
  188. {
  189. return cm::make_unique<cmRulePlaceholderExpander>(
  190. this->Compilers, this->VariableMappings, this->CompilerSysroot,
  191. this->LinkerSysroot);
  192. }
  193. cmLocalGenerator::~cmLocalGenerator() = default;
  194. void cmLocalGenerator::IssueMessage(MessageType t,
  195. std::string const& text) const
  196. {
  197. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  198. }
  199. void cmLocalGenerator::ComputeObjectMaxPath()
  200. {
  201. // Choose a maximum object file name length.
  202. #if defined(_WIN32) || defined(__CYGWIN__)
  203. this->ObjectPathMax = 250;
  204. #else
  205. this->ObjectPathMax = 1000;
  206. #endif
  207. cmValue plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  208. if (cmNonempty(plen)) {
  209. unsigned int pmax;
  210. if (sscanf(plen->c_str(), "%u", &pmax) == 1) {
  211. if (pmax >= 128) {
  212. this->ObjectPathMax = pmax;
  213. } else {
  214. std::ostringstream w;
  215. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  216. << ", which is less than the minimum of 128. "
  217. << "The value will be ignored.";
  218. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  219. }
  220. } else {
  221. std::ostringstream w;
  222. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << *plen
  223. << "\", which fails to parse as a positive integer. "
  224. << "The value will be ignored.";
  225. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  226. }
  227. }
  228. this->ObjectMaxPathViolations.clear();
  229. }
  230. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  231. const std::string& config,
  232. const std::string& lang,
  233. const cmGeneratorTarget* target)
  234. {
  235. if (!target) {
  236. return;
  237. }
  238. std::stable_sort(
  239. includeDirs.begin(), includeDirs.end(),
  240. [&target, &config, &lang](std::string const& a, std::string const& b) {
  241. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  242. target->IsSystemIncludeDirectory(b, config, lang);
  243. });
  244. }
  245. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  246. const std::string& config,
  247. const std::string& lang,
  248. const cmGeneratorTarget* target)
  249. {
  250. if (!target) {
  251. return;
  252. }
  253. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  254. [target, &config, &lang](BT<std::string> const& a,
  255. BT<std::string> const& b) {
  256. return !target->IsSystemIncludeDirectory(a.Value, config,
  257. lang) &&
  258. target->IsSystemIncludeDirectory(b.Value, config, lang);
  259. });
  260. }
  261. void cmLocalGenerator::TraceDependencies() const
  262. {
  263. // Generate the rule files for each target.
  264. const auto& targets = this->GetGeneratorTargets();
  265. for (const auto& target : targets) {
  266. if (!target->IsInBuildSystem()) {
  267. continue;
  268. }
  269. target->TraceDependencies();
  270. }
  271. }
  272. void cmLocalGenerator::GenerateTestFiles()
  273. {
  274. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  275. return;
  276. }
  277. // Compute the set of configurations.
  278. std::vector<std::string> configurationTypes =
  279. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  280. std::string config = this->Makefile->GetDefaultConfiguration();
  281. std::string file =
  282. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  283. "/CTestTestfile.cmake");
  284. cmGeneratedFileStream fout(file);
  285. fout.SetCopyIfDifferent(true);
  286. fout << "# CMake generated Testfile for \n"
  287. "# Source directory: "
  288. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  289. << "\n"
  290. "# Build directory: "
  291. << this->StateSnapshot.GetDirectory().GetCurrentBinary()
  292. << "\n"
  293. "# \n"
  294. "# This file includes the relevant testing commands "
  295. "required for \n"
  296. "# testing this directory and lists subdirectories to "
  297. "be tested as well.\n";
  298. std::string resourceSpecFile =
  299. this->Makefile->GetSafeDefinition("CTEST_RESOURCE_SPEC_FILE");
  300. if (!resourceSpecFile.empty()) {
  301. fout << "set(CTEST_RESOURCE_SPEC_FILE \"" << resourceSpecFile << "\")\n";
  302. }
  303. cmValue testIncludeFile = this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  304. if (testIncludeFile) {
  305. fout << "include(\"" << *testIncludeFile << "\")\n";
  306. }
  307. cmValue testIncludeFiles = this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  308. if (testIncludeFiles) {
  309. cmList includesList{ *testIncludeFiles };
  310. for (std::string const& i : includesList) {
  311. fout << "include(\"" << i << "\")\n";
  312. }
  313. }
  314. // Ask each test generator to write its code.
  315. for (const auto& tester : this->Makefile->GetTestGenerators()) {
  316. tester->Compute(this);
  317. tester->Generate(fout, config, configurationTypes);
  318. }
  319. using vec_t = std::vector<cmStateSnapshot>;
  320. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  321. for (cmStateSnapshot const& i : children) {
  322. // TODO: Use add_subdirectory instead?
  323. std::string outP = i.GetDirectory().GetCurrentBinary();
  324. outP = this->MaybeRelativeToCurBinDir(outP);
  325. outP = cmOutputConverter::EscapeForCMake(outP);
  326. fout << "subdirs(" << outP << ")\n";
  327. }
  328. // Add directory labels property
  329. cmValue directoryLabels =
  330. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  331. cmValue labels = this->Makefile->GetProperty("LABELS");
  332. if (labels || directoryLabels) {
  333. fout << "set_directory_properties(PROPERTIES LABELS ";
  334. if (labels) {
  335. fout << cmOutputConverter::EscapeForCMake(*labels);
  336. }
  337. if (labels && directoryLabels) {
  338. fout << ";";
  339. }
  340. if (directoryLabels) {
  341. fout << cmOutputConverter::EscapeForCMake(*directoryLabels);
  342. }
  343. fout << ")\n";
  344. }
  345. }
  346. void cmLocalGenerator::CreateEvaluationFileOutputs()
  347. {
  348. std::vector<std::string> const& configs =
  349. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  350. for (std::string const& c : configs) {
  351. this->CreateEvaluationFileOutputs(c);
  352. }
  353. }
  354. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  355. {
  356. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  357. geef->CreateOutputFile(this, config);
  358. }
  359. }
  360. void cmLocalGenerator::ProcessEvaluationFiles(
  361. std::vector<std::string>& generatedFiles)
  362. {
  363. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  364. geef->Generate(this);
  365. if (cmSystemTools::GetFatalErrorOccurred()) {
  366. return;
  367. }
  368. std::vector<std::string> files = geef->GetFiles();
  369. std::sort(files.begin(), files.end());
  370. std::vector<std::string> intersection;
  371. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  372. generatedFiles.end(),
  373. std::back_inserter(intersection));
  374. if (!intersection.empty()) {
  375. cmSystemTools::Error("Files to be generated by multiple different "
  376. "commands: " +
  377. cmWrap('"', intersection, '"', " "));
  378. return;
  379. }
  380. cm::append(generatedFiles, files);
  381. std::inplace_merge(generatedFiles.begin(),
  382. generatedFiles.end() - files.size(),
  383. generatedFiles.end());
  384. }
  385. }
  386. void cmLocalGenerator::GenerateInstallRules()
  387. {
  388. // Compute the install prefix.
  389. cmValue installPrefix =
  390. this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  391. std::string prefix = *installPrefix;
  392. #if defined(_WIN32) && !defined(__CYGWIN__)
  393. if (!installPrefix) {
  394. if (!cmSystemTools::GetEnv("SystemDrive", prefix)) {
  395. prefix = "C:";
  396. }
  397. cmValue project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  398. if (cmNonempty(project_name)) {
  399. prefix += "/Program Files/";
  400. prefix += *project_name;
  401. } else {
  402. prefix += "/InstalledCMakeProject";
  403. }
  404. }
  405. #elif defined(__HAIKU__)
  406. char dir[B_PATH_NAME_LENGTH];
  407. if (!installPrefix) {
  408. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  409. B_OK) {
  410. prefix = dir;
  411. } else {
  412. prefix = "/boot/system";
  413. }
  414. }
  415. #else
  416. if (!installPrefix) {
  417. prefix = "/usr/local";
  418. }
  419. #endif
  420. if (cmValue stagingPrefix =
  421. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  422. prefix = *stagingPrefix;
  423. }
  424. // Compute the set of configurations.
  425. std::vector<std::string> configurationTypes =
  426. this->Makefile->GetGeneratorConfigs(cmMakefile::OnlyMultiConfig);
  427. std::string config = this->Makefile->GetDefaultConfiguration();
  428. // Choose a default install configuration.
  429. std::string default_config = config;
  430. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  431. "DEBUG", nullptr };
  432. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  433. for (std::string const& configurationType : configurationTypes) {
  434. if (cmSystemTools::UpperCase(configurationType) == *c) {
  435. default_config = configurationType;
  436. }
  437. }
  438. }
  439. if (default_config.empty() && !configurationTypes.empty()) {
  440. default_config = configurationTypes[0];
  441. }
  442. // Create the install script file.
  443. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  444. std::string homedir = this->GetState()->GetBinaryDirectory();
  445. int toplevel_install = 0;
  446. if (file == homedir) {
  447. toplevel_install = 1;
  448. }
  449. file += "/cmake_install.cmake";
  450. cmGeneratedFileStream fout(file);
  451. fout.SetCopyIfDifferent(true);
  452. // Write the header.
  453. /* clang-format off */
  454. fout << "# Install script for directory: "
  455. << this->StateSnapshot.GetDirectory().GetCurrentSource()
  456. << "\n\n"
  457. "# Set the install prefix\n"
  458. "if(NOT DEFINED CMAKE_INSTALL_PREFIX)\n"
  459. " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")\n"
  460. "endif()\n"
  461. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  462. << "\"${CMAKE_INSTALL_PREFIX}\")\n\n";
  463. /* clang-format on */
  464. // Write support code for generating per-configuration install rules.
  465. /* clang-format off */
  466. fout <<
  467. "# Set the install configuration name.\n"
  468. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  469. " if(BUILD_TYPE)\n"
  470. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  471. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  472. " else()\n"
  473. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  474. " endif()\n"
  475. " message(STATUS \"Install configuration: "
  476. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  477. "endif()\n"
  478. "\n";
  479. /* clang-format on */
  480. // Write support code for dealing with component-specific installs.
  481. /* clang-format off */
  482. fout <<
  483. "# Set the component getting installed.\n"
  484. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  485. " if(COMPONENT)\n"
  486. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  487. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  488. " else()\n"
  489. " set(CMAKE_INSTALL_COMPONENT)\n"
  490. " endif()\n"
  491. "endif()\n"
  492. "\n";
  493. /* clang-format on */
  494. // Copy user-specified install options to the install code.
  495. if (cmValue so_no_exe =
  496. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  497. /* clang-format off */
  498. fout <<
  499. "# Install shared libraries without execute permission?\n"
  500. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  501. " set(CMAKE_INSTALL_SO_NO_EXE \"" << *so_no_exe << "\")\n"
  502. "endif()\n"
  503. "\n";
  504. /* clang-format on */
  505. }
  506. // Copy cmake cross compile state to install code.
  507. if (cmValue crosscompiling =
  508. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  509. /* clang-format off */
  510. fout <<
  511. "# Is this installation the result of a crosscompile?\n"
  512. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  513. " set(CMAKE_CROSSCOMPILING \"" << *crosscompiling << "\")\n"
  514. "endif()\n"
  515. "\n";
  516. /* clang-format on */
  517. }
  518. // Write default directory permissions.
  519. if (cmValue defaultDirPermissions = this->Makefile->GetDefinition(
  520. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  521. /* clang-format off */
  522. fout <<
  523. "# Set default install directory permissions.\n"
  524. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  525. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  526. << *defaultDirPermissions << "\")\n"
  527. "endif()\n"
  528. "\n";
  529. /* clang-format on */
  530. }
  531. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM so that
  532. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  533. // has same platform variable as when running cmake
  534. if (cmValue platform = this->Makefile->GetDefinition(
  535. "CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM")) {
  536. /* clang-format off */
  537. fout <<
  538. "# Set default install directory permissions.\n"
  539. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM)\n"
  540. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_PLATFORM \""
  541. << *platform << "\")\n"
  542. "endif()\n"
  543. "\n";
  544. /* clang-format on */
  545. }
  546. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL so that
  547. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  548. // has same tool selected as when running cmake
  549. if (cmValue command =
  550. this->Makefile->GetDefinition("CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL")) {
  551. /* clang-format off */
  552. fout <<
  553. "# Set default install directory permissions.\n"
  554. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL)\n"
  555. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_TOOL \""
  556. << *command << "\")\n"
  557. "endif()\n"
  558. "\n";
  559. /* clang-format on */
  560. }
  561. // Write out CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND so that
  562. // installed code that uses `file(GET_RUNTIME_DEPENDENCIES)`
  563. // has same path to the tool as when running cmake
  564. if (cmValue command = this->Makefile->GetDefinition(
  565. "CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND")) {
  566. /* clang-format off */
  567. fout <<
  568. "# Set default install directory permissions.\n"
  569. "if(NOT DEFINED CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND)\n"
  570. " set(CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND \""
  571. << *command << "\")\n"
  572. "endif()\n"
  573. "\n";
  574. /* clang-format on */
  575. }
  576. // Write out CMAKE_OBJDUMP so that installed code that uses
  577. // `file(GET_RUNTIME_DEPENDENCIES)` and hasn't specified
  578. // CMAKE_GET_RUNTIME_DEPENDENCIES_COMMAND has consistent
  579. // logic to fallback to CMAKE_OBJDUMP when `objdump` is
  580. // not on the path
  581. if (cmValue command = this->Makefile->GetDefinition("CMAKE_OBJDUMP")) {
  582. /* clang-format off */
  583. fout <<
  584. "# Set default install directory permissions.\n"
  585. "if(NOT DEFINED CMAKE_OBJDUMP)\n"
  586. " set(CMAKE_OBJDUMP \""
  587. << *command << "\")\n"
  588. "endif()\n"
  589. "\n";
  590. /* clang-format on */
  591. }
  592. this->AddGeneratorSpecificInstallSetup(fout);
  593. // Ask each install generator to write its code.
  594. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  595. auto const& installers = this->Makefile->GetInstallGenerators();
  596. bool haveSubdirectoryInstall = false;
  597. bool haveInstallAfterSubdirectory = false;
  598. if (status == cmPolicies::WARN) {
  599. for (const auto& installer : installers) {
  600. installer->CheckCMP0082(haveSubdirectoryInstall,
  601. haveInstallAfterSubdirectory);
  602. installer->Generate(fout, config, configurationTypes);
  603. }
  604. } else {
  605. for (const auto& installer : installers) {
  606. installer->Generate(fout, config, configurationTypes);
  607. }
  608. }
  609. // Write rules from old-style specification stored in targets.
  610. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  611. // Include install scripts from subdirectories.
  612. switch (status) {
  613. case cmPolicies::WARN:
  614. if (haveInstallAfterSubdirectory &&
  615. this->Makefile->PolicyOptionalWarningEnabled(
  616. "CMAKE_POLICY_WARNING_CMP0082")) {
  617. std::ostringstream e;
  618. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  619. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  620. }
  621. CM_FALLTHROUGH;
  622. case cmPolicies::OLD: {
  623. std::vector<cmStateSnapshot> children =
  624. this->Makefile->GetStateSnapshot().GetChildren();
  625. if (!children.empty()) {
  626. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  627. fout << " # Include the install script for each subdirectory.\n";
  628. for (cmStateSnapshot const& c : children) {
  629. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  630. std::string odir = c.GetDirectory().GetCurrentBinary();
  631. cmSystemTools::ConvertToUnixSlashes(odir);
  632. fout << " include(\"" << odir << "/cmake_install.cmake\")\n";
  633. }
  634. }
  635. fout << "\n";
  636. fout << "endif()\n\n";
  637. }
  638. } break;
  639. case cmPolicies::REQUIRED_IF_USED:
  640. case cmPolicies::REQUIRED_ALWAYS:
  641. case cmPolicies::NEW:
  642. // NEW behavior is handled in
  643. // cmInstallSubdirectoryGenerator::GenerateScript()
  644. break;
  645. }
  646. // Record the install manifest.
  647. if (toplevel_install) {
  648. /* clang-format off */
  649. fout <<
  650. "if(CMAKE_INSTALL_COMPONENT)\n"
  651. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  652. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  653. "else()\n"
  654. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  655. "endif()\n"
  656. "\n"
  657. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  658. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  659. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  660. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  661. /* clang-format on */
  662. }
  663. }
  664. void cmLocalGenerator::AddGeneratorTarget(
  665. std::unique_ptr<cmGeneratorTarget> gt)
  666. {
  667. cmGeneratorTarget* gt_ptr = gt.get();
  668. this->GeneratorTargets.push_back(std::move(gt));
  669. this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
  670. this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
  671. }
  672. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  673. {
  674. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  675. this->GlobalGenerator->IndexGeneratorTarget(gt);
  676. }
  677. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
  678. std::unique_ptr<cmGeneratorTarget> gt)
  679. {
  680. this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
  681. }
  682. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  683. const std::string& name) const
  684. {
  685. auto ti = this->GeneratorTargetSearchIndex.find(name);
  686. if (ti != this->GeneratorTargetSearchIndex.end()) {
  687. return ti->second;
  688. }
  689. return nullptr;
  690. }
  691. void cmLocalGenerator::ComputeTargetManifest()
  692. {
  693. // Collect the set of configuration types.
  694. std::vector<std::string> configNames =
  695. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  696. // Add our targets to the manifest for each configuration.
  697. const auto& targets = this->GetGeneratorTargets();
  698. for (const auto& target : targets) {
  699. if (!target->IsInBuildSystem()) {
  700. continue;
  701. }
  702. for (std::string const& c : configNames) {
  703. target->ComputeTargetManifest(c);
  704. }
  705. }
  706. }
  707. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  708. {
  709. // Collect the set of configuration types.
  710. std::vector<std::string> configNames =
  711. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  712. using LanguagePair = std::pair<std::string, std::string>;
  713. std::vector<LanguagePair> pairedLanguages{
  714. { "OBJC", "C" }, { "OBJCXX", "CXX" }, { "CUDA", "CXX" }, { "HIP", "CXX" }
  715. };
  716. std::set<LanguagePair> inferredEnabledLanguages;
  717. for (auto const& lang : pairedLanguages) {
  718. if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
  719. inferredEnabledLanguages.insert(lang);
  720. }
  721. }
  722. // Process compile features of all targets.
  723. const auto& targets = this->GetGeneratorTargets();
  724. for (const auto& target : targets) {
  725. for (std::string const& c : configNames) {
  726. if (!target->ComputeCompileFeatures(c)) {
  727. return false;
  728. }
  729. }
  730. // Now that C/C++ _STANDARD values have been computed
  731. // set the values to ObjC/ObjCXX _STANDARD variables
  732. if (target->CanCompileSources()) {
  733. for (std::string const& c : configNames) {
  734. target->ComputeCompileFeatures(c, inferredEnabledLanguages);
  735. }
  736. }
  737. }
  738. return true;
  739. }
  740. bool cmLocalGenerator::IsRootMakefile() const
  741. {
  742. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  743. }
  744. cmState* cmLocalGenerator::GetState() const
  745. {
  746. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  747. }
  748. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  749. {
  750. return this->Makefile->GetStateSnapshot();
  751. }
  752. std::string cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  753. const std::string& prop,
  754. const std::string& config)
  755. {
  756. cmValue value = this->Makefile->GetProperty(prop);
  757. if (target) {
  758. value = target->GetProperty(prop);
  759. }
  760. if (value) {
  761. return cmGeneratorExpression::Evaluate(*value, this, config, target);
  762. }
  763. return "";
  764. }
  765. std::string cmLocalGenerator::ConvertToIncludeReference(
  766. std::string const& path, OutputFormat format)
  767. {
  768. return this->ConvertToOutputForExisting(path, format);
  769. }
  770. std::string cmLocalGenerator::GetIncludeFlags(
  771. std::vector<std::string> const& includeDirs, cmGeneratorTarget* target,
  772. std::string const& lang, std::string const& config, bool forResponseFile)
  773. {
  774. if (lang.empty()) {
  775. return "";
  776. }
  777. std::vector<std::string> includes = includeDirs;
  778. MoveSystemIncludesToEnd(includes, config, lang, target);
  779. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  780. std::ostringstream includeFlags;
  781. std::string const& includeFlag =
  782. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  783. bool quotePaths = false;
  784. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  785. quotePaths = true;
  786. }
  787. std::string sep = " ";
  788. bool repeatFlag = true;
  789. // should the include flag be repeated like ie. -IA -IB
  790. if (cmValue incSep = this->Makefile->GetDefinition(
  791. cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang))) {
  792. // if there is a separator then the flag is not repeated but is only
  793. // given once i.e. -classpath a:b:c
  794. sep = *incSep;
  795. repeatFlag = false;
  796. }
  797. // Support special system include flag if it is available and the
  798. // normal flag is repeated for each directory.
  799. cmValue sysIncludeFlag = nullptr;
  800. cmValue sysIncludeFlagWarning = nullptr;
  801. if (repeatFlag) {
  802. sysIncludeFlag = this->Makefile->GetDefinition(
  803. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  804. sysIncludeFlagWarning = this->Makefile->GetDefinition(
  805. cmStrCat("_CMAKE_INCLUDE_SYSTEM_FLAG_", lang, "_WARNING"));
  806. }
  807. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  808. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  809. cmValue sysFwSearchFlag = this->Makefile->GetDefinition(
  810. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  811. bool flagUsed = false;
  812. bool sysIncludeFlagUsed = false;
  813. std::set<std::string> emitted;
  814. #ifdef __APPLE__
  815. emitted.insert("/System/Library/Frameworks");
  816. #endif
  817. for (std::string const& i : includes) {
  818. if (cmNonempty(fwSearchFlag) && this->Makefile->IsOn("APPLE") &&
  819. cmSystemTools::IsPathToFramework(i)) {
  820. std::string const frameworkDir = cmSystemTools::GetFilenamePath(i);
  821. if (emitted.insert(frameworkDir).second) {
  822. if (sysFwSearchFlag && target &&
  823. target->IsSystemIncludeDirectory(frameworkDir, config, lang)) {
  824. includeFlags << *sysFwSearchFlag;
  825. } else {
  826. includeFlags << *fwSearchFlag;
  827. }
  828. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  829. << " ";
  830. }
  831. continue;
  832. }
  833. if (!flagUsed || repeatFlag) {
  834. if (sysIncludeFlag && target &&
  835. target->IsSystemIncludeDirectory(i, config, lang)) {
  836. includeFlags << *sysIncludeFlag;
  837. sysIncludeFlagUsed = true;
  838. } else {
  839. includeFlags << includeFlag;
  840. }
  841. flagUsed = true;
  842. }
  843. std::string includePath = this->ConvertToIncludeReference(i, shellFormat);
  844. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  845. includeFlags << "\"";
  846. }
  847. includeFlags << includePath;
  848. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  849. includeFlags << "\"";
  850. }
  851. includeFlags << sep;
  852. }
  853. if (sysIncludeFlagUsed && sysIncludeFlagWarning) {
  854. includeFlags << *sysIncludeFlagWarning;
  855. }
  856. std::string flags = includeFlags.str();
  857. // remove trailing separators
  858. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  859. flags.back() = ' ';
  860. }
  861. return cmTrimWhitespace(flags);
  862. }
  863. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  864. cmGeneratorTarget* target,
  865. const std::string& lang,
  866. const std::string& config)
  867. {
  868. std::vector<BT<std::string>> tmpFlags;
  869. this->AddCompileOptions(tmpFlags, target, lang, config);
  870. this->AppendFlags(flags, tmpFlags);
  871. }
  872. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  873. cmGeneratorTarget* target,
  874. const std::string& lang,
  875. const std::string& config)
  876. {
  877. std::string langFlagRegexVar = cmStrCat("CMAKE_", lang, "_FLAG_REGEX");
  878. if (cmValue langFlagRegexStr =
  879. this->Makefile->GetDefinition(langFlagRegexVar)) {
  880. // Filter flags acceptable to this language.
  881. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  882. std::vector<std::string> opts;
  883. cmSystemTools::ParseWindowsCommandLine(targetFlags->c_str(), opts);
  884. // Re-escape these flags since COMPILE_FLAGS were already parsed
  885. // as a command line above.
  886. std::string compileOpts;
  887. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr->c_str());
  888. if (!compileOpts.empty()) {
  889. flags.emplace_back(std::move(compileOpts));
  890. }
  891. }
  892. std::vector<BT<std::string>> targetCompileOpts =
  893. target->GetCompileOptions(config, lang);
  894. // COMPILE_OPTIONS are escaped.
  895. this->AppendCompileOptions(flags, targetCompileOpts,
  896. langFlagRegexStr->c_str());
  897. } else {
  898. // Use all flags.
  899. if (cmValue targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  900. // COMPILE_FLAGS are not escaped for historical reasons.
  901. std::string compileFlags;
  902. this->AppendFlags(compileFlags, *targetFlags);
  903. if (!compileFlags.empty()) {
  904. flags.emplace_back(std::move(compileFlags));
  905. }
  906. }
  907. std::vector<BT<std::string>> targetCompileOpts =
  908. target->GetCompileOptions(config, lang);
  909. // COMPILE_OPTIONS are escaped.
  910. this->AppendCompileOptions(flags, targetCompileOpts);
  911. }
  912. cmStandardLevelResolver standardResolver(this->Makefile);
  913. for (auto const& it : target->GetMaxLanguageStandards()) {
  914. cmValue standard = target->GetLanguageStandard(it.first, config);
  915. if (!standard) {
  916. continue;
  917. }
  918. if (standardResolver.IsLaterStandard(it.first, *standard, it.second)) {
  919. std::ostringstream e;
  920. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  921. << "\" was evaluated when computing the link "
  922. "implementation, and the \""
  923. << it.first << "_STANDARD\" was \"" << it.second
  924. << "\" for that computation. Computing the "
  925. "COMPILE_FEATURES based on the link implementation resulted in a "
  926. "higher \""
  927. << it.first << "_STANDARD\" \"" << *standard
  928. << "\". "
  929. "This is not permitted. The COMPILE_FEATURES may not both depend "
  930. "on "
  931. "and be depended on by the link implementation.\n";
  932. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  933. return;
  934. }
  935. }
  936. // Add Warning as errors flags
  937. if (!this->GetCMakeInstance()->GetIgnoreWarningAsError()) {
  938. const cmValue wError = target->GetProperty("COMPILE_WARNING_AS_ERROR");
  939. const cmValue wErrorOpts = this->Makefile->GetDefinition(
  940. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_WARNING_AS_ERROR"));
  941. if (wError.IsOn() && wErrorOpts.IsSet()) {
  942. std::string wErrorFlags;
  943. this->AppendCompileOptions(wErrorFlags, *wErrorOpts);
  944. if (!wErrorFlags.empty()) {
  945. flags.emplace_back(std::move(wErrorFlags));
  946. }
  947. }
  948. }
  949. // Add compile flag for the MSVC compiler only.
  950. cmMakefile* mf = this->GetMakefile();
  951. if (cmValue jmc =
  952. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  953. // Handle Just My Code debugging flags, /JMC.
  954. // If the target is a Managed C++ one, /JMC is not compatible.
  955. if (target->GetManagedType(config) !=
  956. cmGeneratorTarget::ManagedType::Managed) {
  957. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  958. // to ON
  959. if (cmValue jmcExprGen =
  960. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  961. std::string isJMCEnabled =
  962. cmGeneratorExpression::Evaluate(*jmcExprGen, this, config);
  963. if (cmIsOn(isJMCEnabled)) {
  964. cmList optList{ *jmc };
  965. std::string jmcFlags;
  966. this->AppendCompileOptions(jmcFlags, optList);
  967. if (!jmcFlags.empty()) {
  968. flags.emplace_back(std::move(jmcFlags));
  969. }
  970. }
  971. }
  972. }
  973. }
  974. }
  975. cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
  976. const std::string& target, cmCustomCommandType type,
  977. std::unique_ptr<cmCustomCommand> cc, cmObjectLibraryCommands objLibCommands)
  978. {
  979. cmTarget* t = this->Makefile->GetCustomCommandTarget(
  980. target, objLibCommands, this->DirectoryBacktrace);
  981. if (!t) {
  982. return nullptr;
  983. }
  984. cc->SetBacktrace(this->DirectoryBacktrace);
  985. detail::AddCustomCommandToTarget(*this, cmCommandOrigin::Generator, t, type,
  986. std::move(cc));
  987. return t;
  988. }
  989. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  990. std::unique_ptr<cmCustomCommand> cc, bool replace)
  991. {
  992. // Make sure there is at least one output.
  993. if (cc->GetOutputs().empty()) {
  994. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  995. return nullptr;
  996. }
  997. cc->SetBacktrace(this->DirectoryBacktrace);
  998. return detail::AddCustomCommandToOutput(*this, cmCommandOrigin::Generator,
  999. std::move(cc), replace);
  1000. }
  1001. cmTarget* cmLocalGenerator::AddUtilityCommand(
  1002. const std::string& utilityName, bool excludeFromAll,
  1003. std::unique_ptr<cmCustomCommand> cc)
  1004. {
  1005. cmTarget* target =
  1006. this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
  1007. target->SetIsGeneratorProvided(true);
  1008. if (cc->GetCommandLines().empty() && cc->GetDepends().empty()) {
  1009. return target;
  1010. }
  1011. cc->SetBacktrace(this->DirectoryBacktrace);
  1012. detail::AddUtilityCommand(*this, cmCommandOrigin::Generator, target,
  1013. std::move(cc));
  1014. return target;
  1015. }
  1016. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1017. cmGeneratorTarget const* target, std::string const& lang,
  1018. std::string const& config, bool stripImplicitDirs,
  1019. bool appendAllImplicitDirs) const
  1020. {
  1021. std::vector<BT<std::string>> result;
  1022. // Do not repeat an include path.
  1023. std::set<std::string> emitted;
  1024. auto emitDir = [&result, &emitted](std::string const& dir) {
  1025. if (emitted.insert(dir).second) {
  1026. result.emplace_back(dir);
  1027. }
  1028. };
  1029. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  1030. if (emitted.insert(dir.Value).second) {
  1031. result.emplace_back(dir);
  1032. }
  1033. };
  1034. // When automatic include directories are requested for a build then
  1035. // include the source and binary directories at the beginning of the
  1036. // include path to approximate include file behavior for an
  1037. // in-source build. This does not account for the case of a source
  1038. // file in a subdirectory of the current source directory but we
  1039. // cannot fix this because not all native build tools support
  1040. // per-source-file include paths.
  1041. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  1042. // Current binary directory
  1043. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  1044. // Current source directory
  1045. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  1046. }
  1047. if (!target) {
  1048. return result;
  1049. }
  1050. // Standard include directories to be added unconditionally at the end.
  1051. // These are intended to simulate additional implicit include directories.
  1052. cmList userStandardDirs;
  1053. {
  1054. std::string const value = this->Makefile->GetSafeDefinition(
  1055. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  1056. userStandardDirs.assign(value);
  1057. for (std::string& usd : userStandardDirs) {
  1058. cmSystemTools::ConvertToUnixSlashes(usd);
  1059. }
  1060. }
  1061. // Implicit include directories
  1062. std::vector<std::string> implicitDirs;
  1063. std::set<std::string> implicitSet;
  1064. // Include directories to be excluded as if they were implicit.
  1065. std::set<std::string> implicitExclude;
  1066. {
  1067. // Raw list of implicit include directories
  1068. // Start with "standard" directories that we unconditionally add below.
  1069. std::vector<std::string> impDirVec = userStandardDirs;
  1070. // Load implicit include directories for this language.
  1071. // We ignore this for Fortran because:
  1072. // * There are no standard library headers to avoid overriding.
  1073. // * Compilers like gfortran do not search their own implicit include
  1074. // directories for modules ('.mod' files).
  1075. if (lang != "Fortran") {
  1076. size_t const impDirVecOldSize = impDirVec.size();
  1077. cmList::append(impDirVec,
  1078. this->Makefile->GetDefinition(cmStrCat(
  1079. "CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES")));
  1080. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  1081. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  1082. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  1083. }
  1084. // The CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES are computed using
  1085. // try_compile in CMAKE_DETERMINE_COMPILER_ABI, but the implicit include
  1086. // directories are not known during that try_compile. This can be a
  1087. // problem when the HIP runtime include path is /usr/include because the
  1088. // runtime include path is always added to the userDirs and the compiler
  1089. // includes standard library headers via "__clang_hip_runtime_wrapper.h".
  1090. if (lang == "HIP" && impDirVec.size() == impDirVecOldSize &&
  1091. !cm::contains(impDirVec, "/usr/include")) {
  1092. implicitExclude.emplace("/usr/include");
  1093. }
  1094. }
  1095. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  1096. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  1097. // variables are now computed. On macOS the /usr/include directory is
  1098. // inside the platform SDK so the computed value does not contain it
  1099. // directly. In this case adding -I/usr/include can hide SDK headers so we
  1100. // must still exclude it.
  1101. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  1102. !cm::contains(impDirVec, "/usr/include") &&
  1103. std::find_if(impDirVec.begin(), impDirVec.end(),
  1104. [](std::string const& d) {
  1105. return cmHasLiteralSuffix(d, "/usr/include");
  1106. }) != impDirVec.end()) {
  1107. // Only exclude this hard coded path for backwards compatibility.
  1108. implicitExclude.emplace("/usr/include");
  1109. }
  1110. for (std::string const& i : impDirVec) {
  1111. if (implicitSet.insert(this->GlobalGenerator->GetRealPath(i)).second) {
  1112. implicitDirs.emplace_back(i);
  1113. }
  1114. }
  1115. }
  1116. bool const isCorCxx = (lang == "C" || lang == "CXX");
  1117. // Resolve symlinks in CPATH for comparison with resolved include paths.
  1118. // We do this here instead of when EnvCPATH is populated in case symlinks
  1119. // on disk have changed in the meantime.
  1120. std::set<std::string> resolvedEnvCPATH;
  1121. if (isCorCxx) {
  1122. for (std::string const& i : this->EnvCPATH) {
  1123. resolvedEnvCPATH.emplace(this->GlobalGenerator->GetRealPath(i));
  1124. }
  1125. }
  1126. // Checks if this is not an excluded (implicit) include directory.
  1127. auto notExcluded = [this, &implicitSet, &implicitExclude, &resolvedEnvCPATH,
  1128. isCorCxx](std::string const& dir) -> bool {
  1129. std::string const& real_dir = this->GlobalGenerator->GetRealPath(dir);
  1130. return
  1131. // Do not exclude directories that are not in any excluded set.
  1132. !(cm::contains(implicitSet, real_dir) ||
  1133. cm::contains(implicitExclude, dir))
  1134. // Do not exclude entries of the CPATH environment variable even though
  1135. // they are implicitly searched by the compiler. They are meant to be
  1136. // user-specified directories that can be re-ordered or converted to
  1137. // -isystem without breaking real compiler builtin headers.
  1138. || (isCorCxx && cm::contains(resolvedEnvCPATH, real_dir));
  1139. };
  1140. // Get the target-specific include directories.
  1141. std::vector<BT<std::string>> userDirs =
  1142. target->GetIncludeDirectories(config, lang);
  1143. // Support putting all the in-project include directories first if
  1144. // it is requested by the project.
  1145. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  1146. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  1147. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  1148. for (BT<std::string> const& udr : userDirs) {
  1149. // Emit this directory only if it is a subdirectory of the
  1150. // top-level source or binary tree.
  1151. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  1152. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  1153. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  1154. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  1155. if (notExcluded(udr.Value)) {
  1156. emitBT(udr);
  1157. }
  1158. }
  1159. }
  1160. }
  1161. // Emit remaining non implicit user directories.
  1162. for (BT<std::string> const& udr : userDirs) {
  1163. if (notExcluded(udr.Value)) {
  1164. emitBT(udr);
  1165. }
  1166. }
  1167. // Sort result
  1168. MoveSystemIncludesToEnd(result, config, lang, target);
  1169. // Append standard include directories for this language.
  1170. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  1171. for (std::string& usd : userStandardDirs) {
  1172. emitDir(usd);
  1173. userDirs.emplace_back(std::move(usd));
  1174. }
  1175. // Append compiler implicit include directories
  1176. if (!stripImplicitDirs) {
  1177. // Append implicit directories that were requested by the user only
  1178. for (BT<std::string> const& udr : userDirs) {
  1179. if (cm::contains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  1180. emitBT(udr);
  1181. }
  1182. }
  1183. // Append remaining implicit directories (on demand)
  1184. if (appendAllImplicitDirs) {
  1185. for (std::string& imd : implicitDirs) {
  1186. emitDir(imd);
  1187. }
  1188. }
  1189. }
  1190. return result;
  1191. }
  1192. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1193. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1194. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1195. bool appendAllImplicitDirs) const
  1196. {
  1197. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1198. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1199. dirs.reserve(dirs.size() + tmp.size());
  1200. for (BT<std::string>& v : tmp) {
  1201. dirs.emplace_back(std::move(v.Value));
  1202. }
  1203. }
  1204. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1205. cmGeneratorTarget const* target, std::string const& lang,
  1206. std::string const& config) const
  1207. {
  1208. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1209. }
  1210. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1211. cmGeneratorTarget const* target,
  1212. const std::string& lang,
  1213. const std::string& config) const
  1214. {
  1215. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1216. }
  1217. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1218. std::string const& config,
  1219. std::string const& linkLanguage,
  1220. cmGeneratorTarget* target)
  1221. {
  1222. std::vector<BT<std::string>> tmpFlags =
  1223. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1224. this->AppendFlags(flags, tmpFlags);
  1225. }
  1226. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1227. std::string const& config, std::string const& linkLanguage,
  1228. cmGeneratorTarget* target)
  1229. {
  1230. const std::string configUpper = cmSystemTools::UpperCase(config);
  1231. std::vector<BT<std::string>> flags;
  1232. if (linkLanguage != "Swift" && !this->IsSplitSwiftBuild()) {
  1233. std::string staticLibFlags;
  1234. this->AppendFlags(
  1235. staticLibFlags,
  1236. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1237. if (!configUpper.empty()) {
  1238. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + configUpper;
  1239. this->AppendFlags(staticLibFlags,
  1240. this->Makefile->GetSafeDefinition(name));
  1241. }
  1242. if (!staticLibFlags.empty()) {
  1243. flags.emplace_back(std::move(staticLibFlags));
  1244. }
  1245. }
  1246. std::string staticLibFlags;
  1247. this->AppendFlags(staticLibFlags,
  1248. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1249. if (!configUpper.empty()) {
  1250. std::string name = "STATIC_LIBRARY_FLAGS_" + configUpper;
  1251. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1252. }
  1253. if (!staticLibFlags.empty()) {
  1254. flags.emplace_back(std::move(staticLibFlags));
  1255. }
  1256. std::vector<BT<std::string>> staticLibOpts =
  1257. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1258. // STATIC_LIBRARY_OPTIONS are escaped.
  1259. this->AppendCompileOptions(flags, staticLibOpts);
  1260. return flags;
  1261. }
  1262. void cmLocalGenerator::GetDeviceLinkFlags(
  1263. cmLinkLineDeviceComputer& linkLineComputer, const std::string& config,
  1264. std::string& linkLibs, std::string& linkFlags, std::string& frameworkPath,
  1265. std::string& linkPath, cmGeneratorTarget* target)
  1266. {
  1267. cmGeneratorTarget::DeviceLinkSetter setter(*target);
  1268. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1269. auto linklang = linkLineComputer.GetLinkerLanguage(target, config);
  1270. auto ipoEnabled = target->IsIPOEnabled(linklang, config);
  1271. if (!ipoEnabled) {
  1272. ipoEnabled = linkLineComputer.ComputeRequiresDeviceLinkingIPOFlag(*pcli);
  1273. }
  1274. if (ipoEnabled) {
  1275. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  1276. "CMAKE_CUDA_DEVICE_LINK_OPTIONS_IPO")) {
  1277. linkFlags += *cudaIPOFlags;
  1278. }
  1279. }
  1280. if (pcli) {
  1281. // Compute the required device link libraries when
  1282. // resolving gpu lang device symbols
  1283. this->OutputLinkLibraries(pcli, &linkLineComputer, linkLibs, frameworkPath,
  1284. linkPath);
  1285. }
  1286. this->AddVisibilityPresetFlags(linkFlags, target, "CUDA");
  1287. this->GetGlobalGenerator()->EncodeLiteral(linkFlags);
  1288. std::vector<std::string> linkOpts;
  1289. target->GetLinkOptions(linkOpts, config, "CUDA");
  1290. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1291. // LINK_OPTIONS are escaped.
  1292. this->AppendCompileOptions(linkFlags, linkOpts);
  1293. this->SetLinkScriptShell(false);
  1294. }
  1295. void cmLocalGenerator::GetTargetFlags(
  1296. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1297. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1298. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1299. {
  1300. std::vector<BT<std::string>> linkFlagsList;
  1301. std::vector<BT<std::string>> linkPathList;
  1302. std::vector<BT<std::string>> linkLibsList;
  1303. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1304. linkFlagsList, frameworkPath, linkPathList, target);
  1305. this->AppendFlags(linkFlags, linkFlagsList);
  1306. this->AppendFlags(linkPath, linkPathList);
  1307. this->AppendFlags(linkLibs, linkLibsList);
  1308. }
  1309. void cmLocalGenerator::GetTargetFlags(
  1310. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1311. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1312. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1313. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1314. {
  1315. const std::string configUpper = cmSystemTools::UpperCase(config);
  1316. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1317. const char* libraryLinkVariable =
  1318. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1319. const std::string linkLanguage =
  1320. linkLineComputer->GetLinkerLanguage(target, config);
  1321. switch (target->GetType()) {
  1322. case cmStateEnums::STATIC_LIBRARY:
  1323. linkFlags = this->GetStaticLibraryFlags(config, linkLanguage, target);
  1324. break;
  1325. case cmStateEnums::MODULE_LIBRARY:
  1326. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1327. CM_FALLTHROUGH;
  1328. case cmStateEnums::SHARED_LIBRARY: {
  1329. std::string sharedLibFlags;
  1330. if (linkLanguage != "Swift") {
  1331. sharedLibFlags = cmStrCat(
  1332. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1333. if (!configUpper.empty()) {
  1334. std::string build = cmStrCat(libraryLinkVariable, '_', configUpper);
  1335. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1336. sharedLibFlags += " ";
  1337. }
  1338. }
  1339. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1340. if (targetLinkFlags) {
  1341. sharedLibFlags += *targetLinkFlags;
  1342. sharedLibFlags += " ";
  1343. }
  1344. if (!configUpper.empty()) {
  1345. targetLinkFlags =
  1346. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1347. if (targetLinkFlags) {
  1348. sharedLibFlags += *targetLinkFlags;
  1349. sharedLibFlags += " ";
  1350. }
  1351. }
  1352. if (!sharedLibFlags.empty()) {
  1353. this->GetGlobalGenerator()->EncodeLiteral(sharedLibFlags);
  1354. linkFlags.emplace_back(std::move(sharedLibFlags));
  1355. }
  1356. std::vector<BT<std::string>> linkOpts =
  1357. target->GetLinkOptions(config, linkLanguage);
  1358. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1359. // LINK_OPTIONS are escaped.
  1360. this->AppendCompileOptions(linkFlags, linkOpts);
  1361. this->SetLinkScriptShell(false);
  1362. if (pcli) {
  1363. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1364. frameworkPath, linkPath);
  1365. }
  1366. } break;
  1367. case cmStateEnums::EXECUTABLE: {
  1368. std::string exeFlags;
  1369. if (linkLanguage != "Swift") {
  1370. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1371. exeFlags += " ";
  1372. if (!configUpper.empty()) {
  1373. exeFlags += this->Makefile->GetSafeDefinition(
  1374. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", configUpper));
  1375. exeFlags += " ";
  1376. }
  1377. if (linkLanguage.empty()) {
  1378. cmSystemTools::Error(
  1379. "CMake can not determine linker language for target: " +
  1380. target->GetName());
  1381. return;
  1382. }
  1383. if (target->IsWin32Executable(config)) {
  1384. exeFlags += this->Makefile->GetSafeDefinition(
  1385. cmStrCat("CMAKE_", linkLanguage, "_CREATE_WIN32_EXE"));
  1386. exeFlags += " ";
  1387. } else {
  1388. exeFlags += this->Makefile->GetSafeDefinition(
  1389. cmStrCat("CMAKE_", linkLanguage, "_CREATE_CONSOLE_EXE"));
  1390. exeFlags += " ";
  1391. }
  1392. if (target->IsExecutableWithExports()) {
  1393. exeFlags += this->Makefile->GetSafeDefinition(
  1394. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1395. exeFlags += " ";
  1396. }
  1397. }
  1398. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, config);
  1399. if (pcli) {
  1400. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1401. frameworkPath, linkPath);
  1402. }
  1403. if (this->Makefile->IsOn("BUILD_SHARED_LIBS")) {
  1404. std::string sFlagVar = "CMAKE_SHARED_BUILD_" + linkLanguage + "_FLAGS";
  1405. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1406. exeFlags += " ";
  1407. }
  1408. std::string cmp0065Flags =
  1409. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1410. if (!cmp0065Flags.empty()) {
  1411. exeFlags += cmp0065Flags;
  1412. exeFlags += " ";
  1413. }
  1414. cmValue targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1415. if (targetLinkFlags) {
  1416. exeFlags += *targetLinkFlags;
  1417. exeFlags += " ";
  1418. }
  1419. if (!configUpper.empty()) {
  1420. targetLinkFlags =
  1421. target->GetProperty(cmStrCat("LINK_FLAGS_", configUpper));
  1422. if (targetLinkFlags) {
  1423. exeFlags += *targetLinkFlags;
  1424. exeFlags += " ";
  1425. }
  1426. }
  1427. if (!exeFlags.empty()) {
  1428. this->GetGlobalGenerator()->EncodeLiteral(exeFlags);
  1429. linkFlags.emplace_back(std::move(exeFlags));
  1430. }
  1431. std::vector<BT<std::string>> linkOpts =
  1432. target->GetLinkOptions(config, linkLanguage);
  1433. this->SetLinkScriptShell(this->GetGlobalGenerator()->GetUseLinkScript());
  1434. // LINK_OPTIONS are escaped.
  1435. this->AppendCompileOptions(linkFlags, linkOpts);
  1436. this->SetLinkScriptShell(false);
  1437. } break;
  1438. default:
  1439. break;
  1440. }
  1441. std::string extraLinkFlags;
  1442. this->AppendLinkerTypeFlags(extraLinkFlags, target, config, linkLanguage);
  1443. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1444. linkLanguage);
  1445. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1446. this->AppendDependencyInfoLinkerFlags(extraLinkFlags, target, config,
  1447. linkLanguage);
  1448. this->AppendModuleDefinitionFlag(extraLinkFlags, target, linkLineComputer,
  1449. config);
  1450. if (!extraLinkFlags.empty()) {
  1451. this->GetGlobalGenerator()->EncodeLiteral(extraLinkFlags);
  1452. linkFlags.emplace_back(std::move(extraLinkFlags));
  1453. }
  1454. }
  1455. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1456. std::string const& config,
  1457. std::string const& lang,
  1458. std::string& flags,
  1459. std::string const& arch)
  1460. {
  1461. std::vector<BT<std::string>> tmpFlags =
  1462. this->GetTargetCompileFlags(target, config, lang, arch);
  1463. this->AppendFlags(flags, tmpFlags);
  1464. }
  1465. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1466. cmGeneratorTarget* target, std::string const& config,
  1467. std::string const& lang, std::string const& arch)
  1468. {
  1469. std::vector<BT<std::string>> flags;
  1470. std::string compileFlags;
  1471. cmMakefile* mf = this->GetMakefile();
  1472. // Add language-specific flags.
  1473. this->AddLanguageFlags(compileFlags, target, cmBuildStep::Compile, lang,
  1474. config);
  1475. if (target->IsIPOEnabled(lang, config)) {
  1476. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1477. }
  1478. this->AddArchitectureFlags(compileFlags, target, lang, config, arch);
  1479. if (lang == "Fortran") {
  1480. this->AppendFlags(compileFlags,
  1481. this->GetTargetFortranFlags(target, config));
  1482. } else if (lang == "Swift") {
  1483. // Only set the compile mode if CMP0157 is set
  1484. if (cm::optional<cmSwiftCompileMode> swiftCompileMode =
  1485. this->GetSwiftCompileMode(target, config)) {
  1486. std::string swiftCompileModeFlag;
  1487. switch (*swiftCompileMode) {
  1488. case cmSwiftCompileMode::Incremental: {
  1489. swiftCompileModeFlag = "-incremental";
  1490. if (cmValue flag =
  1491. mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_INCREMENTAL")) {
  1492. swiftCompileModeFlag = *flag;
  1493. }
  1494. break;
  1495. }
  1496. case cmSwiftCompileMode::Wholemodule: {
  1497. swiftCompileModeFlag = "-wmo";
  1498. if (cmValue flag =
  1499. mf->GetDefinition("CMAKE_Swift_COMPILE_OPTIONS_WMO")) {
  1500. swiftCompileModeFlag = *flag;
  1501. }
  1502. break;
  1503. }
  1504. case cmSwiftCompileMode::Singlefile:
  1505. break;
  1506. case cmSwiftCompileMode::Unknown: {
  1507. this->IssueMessage(
  1508. MessageType::AUTHOR_WARNING,
  1509. cmStrCat("Unknown Swift_COMPILATION_MODE on target '",
  1510. target->GetName(), "'"));
  1511. }
  1512. }
  1513. this->AppendFlags(compileFlags, swiftCompileModeFlag);
  1514. }
  1515. }
  1516. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1517. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1518. this->AddColorDiagnosticsFlags(compileFlags, lang);
  1519. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1520. this->AppendFlags(compileFlags,
  1521. this->GetFrameworkFlags(lang, config, target));
  1522. this->AppendFlags(compileFlags,
  1523. this->GetXcFrameworkFlags(lang, config, target));
  1524. if (!compileFlags.empty()) {
  1525. flags.emplace_back(std::move(compileFlags));
  1526. }
  1527. this->AddCompileOptions(flags, target, lang, config);
  1528. return flags;
  1529. }
  1530. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& lang,
  1531. std::string const& config,
  1532. cmGeneratorTarget* target)
  1533. {
  1534. cmLocalGenerator* lg = target->GetLocalGenerator();
  1535. cmMakefile* mf = lg->GetMakefile();
  1536. if (!target->IsApple()) {
  1537. return std::string();
  1538. }
  1539. cmValue fwSearchFlag =
  1540. mf->GetDefinition(cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  1541. cmValue sysFwSearchFlag = mf->GetDefinition(
  1542. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  1543. if (!fwSearchFlag && !sysFwSearchFlag) {
  1544. return std::string{};
  1545. }
  1546. std::set<std::string> emitted;
  1547. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1548. emitted.insert("/System/Library/Frameworks");
  1549. #endif
  1550. std::vector<std::string> includes;
  1551. lg->GetIncludeDirectories(includes, target, "C", config);
  1552. // check all include directories for frameworks as this
  1553. // will already have added a -F for the framework
  1554. for (std::string const& include : includes) {
  1555. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1556. std::string frameworkDir = cmStrCat(include, "/../");
  1557. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1558. emitted.insert(frameworkDir);
  1559. }
  1560. }
  1561. std::string flags;
  1562. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1563. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1564. for (std::string const& framework : frameworks) {
  1565. if (emitted.insert(framework).second) {
  1566. if (sysFwSearchFlag &&
  1567. target->IsSystemIncludeDirectory(framework, config, lang)) {
  1568. flags += *sysFwSearchFlag;
  1569. } else {
  1570. flags += *fwSearchFlag;
  1571. }
  1572. flags +=
  1573. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1574. flags += " ";
  1575. }
  1576. }
  1577. }
  1578. return flags;
  1579. }
  1580. std::string cmLocalGenerator::GetXcFrameworkFlags(std::string const& lang,
  1581. std::string const& config,
  1582. cmGeneratorTarget* target)
  1583. {
  1584. cmLocalGenerator* lg = target->GetLocalGenerator();
  1585. cmMakefile* mf = lg->GetMakefile();
  1586. if (!target->IsApple()) {
  1587. return std::string();
  1588. }
  1589. cmValue includeSearchFlag =
  1590. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  1591. cmValue sysIncludeSearchFlag =
  1592. mf->GetDefinition(cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  1593. if (!includeSearchFlag && !sysIncludeSearchFlag) {
  1594. return std::string{};
  1595. }
  1596. std::string flags;
  1597. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1598. std::vector<std::string> const& paths = cli->GetXcFrameworkHeaderPaths();
  1599. for (std::string const& path : paths) {
  1600. if (sysIncludeSearchFlag &&
  1601. target->IsSystemIncludeDirectory(path, config, lang)) {
  1602. flags += *sysIncludeSearchFlag;
  1603. } else {
  1604. flags += *includeSearchFlag;
  1605. }
  1606. flags += lg->ConvertToOutputFormat(path, cmOutputConverter::SHELL);
  1607. flags += " ";
  1608. }
  1609. }
  1610. return flags;
  1611. }
  1612. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1613. std::string const& config,
  1614. std::string const& lang,
  1615. std::set<std::string>& defines) const
  1616. {
  1617. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1618. for (BT<std::string> const& v : tmp) {
  1619. defines.emplace(v.Value);
  1620. }
  1621. }
  1622. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1623. cmGeneratorTarget const* target, std::string const& config,
  1624. std::string const& lang) const
  1625. {
  1626. std::set<BT<std::string>> defines;
  1627. // Add the export symbol definition for shared library objects.
  1628. if (const std::string* exportMacro = target->GetExportMacro()) {
  1629. this->AppendDefines(defines, *exportMacro);
  1630. }
  1631. // Add preprocessor definitions for this target and configuration.
  1632. std::vector<BT<std::string>> targetDefines =
  1633. target->GetCompileDefinitions(config, lang);
  1634. this->AppendDefines(defines, targetDefines);
  1635. return defines;
  1636. }
  1637. std::string cmLocalGenerator::GetTargetFortranFlags(
  1638. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1639. {
  1640. // Implemented by specific generators that override this.
  1641. return std::string();
  1642. }
  1643. /**
  1644. * Output the linking rules on a command line. For executables,
  1645. * targetLibrary should be a NULL pointer. For libraries, it should point
  1646. * to the name of the library. This will not link a library against itself.
  1647. */
  1648. void cmLocalGenerator::OutputLinkLibraries(
  1649. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1650. std::string& linkLibraries, std::string& frameworkPath,
  1651. std::string& linkPath)
  1652. {
  1653. std::vector<BT<std::string>> linkLibrariesList;
  1654. std::vector<BT<std::string>> linkPathList;
  1655. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1656. frameworkPath, linkPathList);
  1657. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1658. pcli->AppendValues(linkPath, linkPathList);
  1659. }
  1660. void cmLocalGenerator::OutputLinkLibraries(
  1661. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1662. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1663. std::vector<BT<std::string>>& linkPath)
  1664. {
  1665. cmComputeLinkInformation& cli = *pcli;
  1666. std::string linkLanguage = cli.GetLinkLanguage();
  1667. std::string libPathFlag;
  1668. if (cmValue value = this->Makefile->GetDefinition(
  1669. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1670. libPathFlag = *value;
  1671. } else {
  1672. libPathFlag =
  1673. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1674. }
  1675. std::string libPathTerminator;
  1676. if (cmValue value = this->Makefile->GetDefinition(
  1677. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1678. libPathTerminator = *value;
  1679. } else {
  1680. libPathTerminator =
  1681. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1682. }
  1683. // Add standard libraries for this language.
  1684. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1685. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1686. // Append the framework search path flags.
  1687. cmValue fwSearchFlag = this->Makefile->GetDefinition(
  1688. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1689. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1690. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1691. linkPath);
  1692. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1693. }
  1694. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1695. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1696. {
  1697. std::string linkFlags;
  1698. // Flags to link an executable to shared libraries.
  1699. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1700. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1701. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1702. bool add_shlib_flags = false;
  1703. switch (tgt.GetPolicyStatusCMP0065()) {
  1704. case cmPolicies::WARN:
  1705. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1706. this->Makefile->PolicyOptionalWarningEnabled(
  1707. "CMAKE_POLICY_WARNING_CMP0065")) {
  1708. std::ostringstream w;
  1709. /* clang-format off */
  1710. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1711. "For compatibility with older versions of CMake, "
  1712. "additional flags may be added to export symbols on all "
  1713. "executables regardless of their ENABLE_EXPORTS property.";
  1714. /* clang-format on */
  1715. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1716. }
  1717. CM_FALLTHROUGH;
  1718. case cmPolicies::OLD:
  1719. // OLD behavior is to always add the flags, except on AIX where
  1720. // we compute symbol exports if ENABLE_EXPORTS is on.
  1721. add_shlib_flags =
  1722. !(tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1723. break;
  1724. case cmPolicies::REQUIRED_IF_USED:
  1725. case cmPolicies::REQUIRED_ALWAYS:
  1726. this->IssueMessage(
  1727. MessageType::FATAL_ERROR,
  1728. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1729. CM_FALLTHROUGH;
  1730. case cmPolicies::NEW:
  1731. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1732. // except on AIX where we compute symbol exports.
  1733. add_shlib_flags =
  1734. !tgt.IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1735. break;
  1736. }
  1737. if (add_shlib_flags) {
  1738. linkFlags = this->Makefile->GetSafeDefinition(
  1739. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1740. }
  1741. }
  1742. return linkFlags;
  1743. }
  1744. bool cmLocalGenerator::AllAppleArchSysrootsAreTheSame(
  1745. const std::vector<std::string>& archs, cmValue sysroot)
  1746. {
  1747. if (!sysroot) {
  1748. return false;
  1749. }
  1750. return std::all_of(archs.begin(), archs.end(),
  1751. [this, sysroot](std::string const& arch) -> bool {
  1752. std::string const& archSysroot =
  1753. this->AppleArchSysroots[arch];
  1754. return cmIsOff(archSysroot) || *sysroot == archSysroot;
  1755. });
  1756. }
  1757. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1758. cmGeneratorTarget const* target,
  1759. const std::string& lang,
  1760. const std::string& config,
  1761. const std::string& filterArch)
  1762. {
  1763. // Only add Apple specific flags on Apple platforms
  1764. if (target->IsApple() && this->EmitUniversalBinaryFlags) {
  1765. std::vector<std::string> archs = target->GetAppleArchs(config, lang);
  1766. if (!archs.empty() &&
  1767. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX" ||
  1768. lang == "ASM")) {
  1769. for (std::string const& arch : archs) {
  1770. if (filterArch.empty() || filterArch == arch) {
  1771. flags += " -arch ";
  1772. flags += arch;
  1773. }
  1774. }
  1775. }
  1776. cmValue sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1777. if (sysroot && *sysroot == "/") {
  1778. sysroot = nullptr;
  1779. }
  1780. std::string sysrootFlagVar = "CMAKE_" + lang + "_SYSROOT_FLAG";
  1781. cmValue sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1782. if (cmNonempty(sysrootFlag)) {
  1783. if (!this->AppleArchSysroots.empty() &&
  1784. !this->AllAppleArchSysrootsAreTheSame(archs, sysroot)) {
  1785. for (std::string const& arch : archs) {
  1786. std::string const& archSysroot = this->AppleArchSysroots[arch];
  1787. if (cmIsOff(archSysroot)) {
  1788. continue;
  1789. }
  1790. if (filterArch.empty() || filterArch == arch) {
  1791. flags += " -Xarch_" + arch + " ";
  1792. // Combine sysroot flag and path to work with -Xarch
  1793. std::string arch_sysroot = *sysrootFlag + archSysroot;
  1794. flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
  1795. }
  1796. }
  1797. } else if (cmNonempty(sysroot)) {
  1798. flags += " ";
  1799. flags += *sysrootFlag;
  1800. flags += " ";
  1801. flags += this->ConvertToOutputFormat(*sysroot, SHELL);
  1802. }
  1803. }
  1804. cmValue deploymentTarget =
  1805. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1806. if (cmNonempty(deploymentTarget)) {
  1807. std::string deploymentTargetFlagVar =
  1808. "CMAKE_" + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1809. cmValue deploymentTargetFlag =
  1810. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1811. if (cmNonempty(deploymentTargetFlag) &&
  1812. // CMAKE_<LANG>_COMPILER_TARGET overrides a --target= for
  1813. // CMAKE_OSX_DEPLOYMENT_TARGET, e.g., for visionOS.
  1814. (!cmHasLiteralPrefix(*deploymentTarget, "--target=") ||
  1815. this->Makefile
  1816. ->GetDefinition(cmStrCat("CMAKE_", lang, "_COMPILER_TARGET"))
  1817. .IsEmpty())) {
  1818. std::string flag = *deploymentTargetFlag;
  1819. // Add the deployment target architecture to the flag, if needed.
  1820. static const std::string kARCH = "<ARCH>";
  1821. std::string::size_type archPos = flag.find(kARCH);
  1822. if (archPos != std::string::npos) {
  1823. // This placeholder is meant for visionOS, so default to arm64
  1824. // unless only non-arm64 archs are given.
  1825. std::string const arch =
  1826. (archs.empty() || cm::contains(archs, "arm64")) ? "arm64"
  1827. : archs[0];
  1828. // Replace the placeholder with its value.
  1829. flag = cmStrCat(flag.substr(0, archPos), arch,
  1830. flag.substr(archPos + kARCH.size()));
  1831. }
  1832. // Add the deployment target version to the flag.
  1833. static const std::string kVERSION_MIN = "<VERSION_MIN>";
  1834. std::string::size_type verPos = flag.find(kVERSION_MIN);
  1835. if (verPos != std::string::npos) {
  1836. // Replace the placeholder with its value.
  1837. flag = cmStrCat(flag.substr(0, verPos), *deploymentTarget,
  1838. flag.substr(verPos + kVERSION_MIN.size()));
  1839. } else {
  1840. // There is no placeholder, so append the value.
  1841. flag = cmStrCat(flag, *deploymentTarget);
  1842. }
  1843. flags += " ";
  1844. flags += flag;
  1845. }
  1846. }
  1847. }
  1848. }
  1849. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1850. cmGeneratorTarget const* target,
  1851. cmBuildStep compileOrLink,
  1852. const std::string& lang,
  1853. const std::string& config)
  1854. {
  1855. // Add language-specific flags.
  1856. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1857. config);
  1858. // Add the language standard flag for compiling, and sometimes linking.
  1859. if (compileOrLink == cmBuildStep::Compile ||
  1860. (compileOrLink == cmBuildStep::Link &&
  1861. // Some toolchains require use of the language standard flag
  1862. // when linking in order to use the matching standard library.
  1863. // FIXME: If CMake gains an abstraction for standard library
  1864. // selection, this will have to be reconciled with it.
  1865. this->Makefile->IsOn(
  1866. cmStrCat("CMAKE_", lang, "_LINK_WITH_STANDARD_COMPILE_OPTION")))) {
  1867. cmStandardLevelResolver standardResolver(this->Makefile);
  1868. std::string const& optionFlagDef =
  1869. standardResolver.GetCompileOptionDef(target, lang, config);
  1870. if (!optionFlagDef.empty()) {
  1871. cmValue opt =
  1872. target->Target->GetMakefile()->GetDefinition(optionFlagDef);
  1873. if (opt) {
  1874. cmList optList{ *opt };
  1875. for (std::string const& i : optList) {
  1876. this->AppendFlagEscape(flags, i);
  1877. }
  1878. }
  1879. }
  1880. }
  1881. std::string compiler = this->Makefile->GetSafeDefinition(
  1882. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1883. std::string compilerSimulateId = this->Makefile->GetSafeDefinition(
  1884. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1885. if (lang == "Swift") {
  1886. if (cmValue v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1887. if (cmSystemTools::VersionCompare(
  1888. cmSystemTools::OP_GREATER_EQUAL,
  1889. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1890. "4.2")) {
  1891. this->AppendFlags(flags, "-swift-version " + *v);
  1892. }
  1893. }
  1894. } else if (lang == "CUDA") {
  1895. target->AddCUDAArchitectureFlags(compileOrLink, config, flags);
  1896. target->AddCUDAToolkitFlags(flags);
  1897. } else if (lang == "ISPC") {
  1898. target->AddISPCTargetFlags(flags);
  1899. } else if (lang == "RC" &&
  1900. this->Makefile->GetSafeDefinition("CMAKE_RC_COMPILER")
  1901. .find("llvm-rc") != std::string::npos) {
  1902. compiler = this->Makefile->GetSafeDefinition("CMAKE_C_COMPILER_ID");
  1903. if (!compiler.empty()) {
  1904. compilerSimulateId =
  1905. this->Makefile->GetSafeDefinition("CMAKE_C_SIMULATE_ID");
  1906. } else {
  1907. compiler = this->Makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
  1908. compilerSimulateId =
  1909. this->Makefile->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID");
  1910. }
  1911. } else if (lang == "HIP") {
  1912. target->AddHIPArchitectureFlags(compileOrLink, config, flags);
  1913. }
  1914. // Add VFS Overlay for Clang compilers
  1915. if (compiler == "Clang") {
  1916. if (cmValue vfsOverlay =
  1917. this->Makefile->GetDefinition("CMAKE_CLANG_VFS_OVERLAY")) {
  1918. if (compilerSimulateId == "MSVC") {
  1919. this->AppendCompileOptions(
  1920. flags,
  1921. std::vector<std::string>{ "-Xclang", "-ivfsoverlay", "-Xclang",
  1922. *vfsOverlay });
  1923. } else {
  1924. this->AppendCompileOptions(
  1925. flags, std::vector<std::string>{ "-ivfsoverlay", *vfsOverlay });
  1926. }
  1927. }
  1928. }
  1929. // Add MSVC runtime library flags. This is activated by the presence
  1930. // of a default selection whether or not it is overridden by a property.
  1931. cmValue msvcRuntimeLibraryDefault =
  1932. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1933. if (cmNonempty(msvcRuntimeLibraryDefault)) {
  1934. cmValue msvcRuntimeLibraryValue =
  1935. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1936. if (!msvcRuntimeLibraryValue) {
  1937. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1938. }
  1939. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1940. *msvcRuntimeLibraryValue, this, config, target);
  1941. if (!msvcRuntimeLibrary.empty()) {
  1942. if (cmValue msvcRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1943. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1944. msvcRuntimeLibrary)) {
  1945. this->AppendCompileOptions(flags, *msvcRuntimeLibraryOptions);
  1946. } else if ((this->Makefile->GetSafeDefinition(
  1947. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1948. this->Makefile->GetSafeDefinition(
  1949. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1950. !cmSystemTools::GetErrorOccurredFlag()) {
  1951. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1952. this->IssueMessage(MessageType::FATAL_ERROR,
  1953. "MSVC_RUNTIME_LIBRARY value '" +
  1954. msvcRuntimeLibrary + "' not known for this " +
  1955. lang + " compiler.");
  1956. }
  1957. }
  1958. }
  1959. // Add Watcom runtime library flags. This is activated by the presence
  1960. // of a default selection whether or not it is overridden by a property.
  1961. cmValue watcomRuntimeLibraryDefault =
  1962. this->Makefile->GetDefinition("CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT");
  1963. if (cmNonempty(watcomRuntimeLibraryDefault)) {
  1964. cmValue watcomRuntimeLibraryValue =
  1965. target->GetProperty("WATCOM_RUNTIME_LIBRARY");
  1966. if (!watcomRuntimeLibraryValue) {
  1967. watcomRuntimeLibraryValue = watcomRuntimeLibraryDefault;
  1968. }
  1969. std::string const watcomRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1970. *watcomRuntimeLibraryValue, this, config, target);
  1971. if (!watcomRuntimeLibrary.empty()) {
  1972. if (cmValue watcomRuntimeLibraryOptions = this->Makefile->GetDefinition(
  1973. "CMAKE_" + lang + "_COMPILE_OPTIONS_WATCOM_RUNTIME_LIBRARY_" +
  1974. watcomRuntimeLibrary)) {
  1975. this->AppendCompileOptions(flags, *watcomRuntimeLibraryOptions);
  1976. } else if ((this->Makefile->GetSafeDefinition(
  1977. "CMAKE_" + lang + "_COMPILER_ID") == "OpenWatcom" ||
  1978. this->Makefile->GetSafeDefinition(
  1979. "CMAKE_" + lang + "_SIMULATE_ID") == "OpenWatcom") &&
  1980. !cmSystemTools::GetErrorOccurredFlag()) {
  1981. // The compiler uses the Watcom ABI so it needs a known runtime
  1982. // library.
  1983. this->IssueMessage(MessageType::FATAL_ERROR,
  1984. "WATCOM_RUNTIME_LIBRARY value '" +
  1985. watcomRuntimeLibrary + "' not known for this " +
  1986. lang + " compiler.");
  1987. }
  1988. }
  1989. }
  1990. // Add MSVC debug information format flags if CMP0141 is NEW.
  1991. if (cm::optional<std::string> msvcDebugInformationFormat =
  1992. this->GetMSVCDebugFormatName(config, target)) {
  1993. if (!msvcDebugInformationFormat->empty()) {
  1994. if (cmValue msvcDebugInformationFormatOptions =
  1995. this->Makefile->GetDefinition(
  1996. cmStrCat("CMAKE_", lang,
  1997. "_COMPILE_OPTIONS_MSVC_DEBUG_INFORMATION_FORMAT_",
  1998. *msvcDebugInformationFormat))) {
  1999. this->AppendCompileOptions(flags, *msvcDebugInformationFormatOptions);
  2000. } else if ((this->Makefile->GetSafeDefinition(
  2001. cmStrCat("CMAKE_", lang, "_COMPILER_ID")) == "MSVC"_s ||
  2002. this->Makefile->GetSafeDefinition(
  2003. cmStrCat("CMAKE_", lang, "_SIMULATE_ID")) == "MSVC"_s) &&
  2004. !cmSystemTools::GetErrorOccurredFlag()) {
  2005. // The compiler uses the MSVC ABI so it needs a known runtime library.
  2006. this->IssueMessage(MessageType::FATAL_ERROR,
  2007. cmStrCat("MSVC_DEBUG_INFORMATION_FORMAT value '",
  2008. *msvcDebugInformationFormat,
  2009. "' not known for this ", lang,
  2010. " compiler."));
  2011. }
  2012. }
  2013. }
  2014. }
  2015. void cmLocalGenerator::AddLanguageFlagsForLinking(
  2016. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  2017. const std::string& config)
  2018. {
  2019. this->AddLanguageFlags(flags, target, cmBuildStep::Link, lang, config);
  2020. if (target->IsIPOEnabled(lang, config)) {
  2021. this->AppendFeatureOptions(flags, lang, "IPO");
  2022. }
  2023. }
  2024. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  2025. const std::string& name) const
  2026. {
  2027. auto imported = this->ImportedGeneratorTargets.find(name);
  2028. if (imported != this->ImportedGeneratorTargets.end()) {
  2029. return imported->second;
  2030. }
  2031. // find local alias to imported target
  2032. auto aliased = this->AliasTargets.find(name);
  2033. if (aliased != this->AliasTargets.end()) {
  2034. imported = this->ImportedGeneratorTargets.find(aliased->second);
  2035. if (imported != this->ImportedGeneratorTargets.end()) {
  2036. return imported->second;
  2037. }
  2038. }
  2039. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  2040. return t;
  2041. }
  2042. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  2043. }
  2044. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  2045. const std::string& config,
  2046. std::string& dep)
  2047. {
  2048. // Older CMake code may specify the dependency using the target
  2049. // output file rather than the target name. Such code would have
  2050. // been written before there was support for target properties that
  2051. // modify the name so stripping down to just the file name should
  2052. // produce the target name in this case.
  2053. std::string name = cmSystemTools::GetFilenameName(inName);
  2054. // If the input name is the empty string, there is no real
  2055. // dependency. Short-circuit the other checks:
  2056. if (name.empty()) {
  2057. return false;
  2058. }
  2059. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  2060. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  2061. }
  2062. // Look for a CMake target with the given name.
  2063. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  2064. // make sure it is not just a coincidence that the target name
  2065. // found is part of the inName
  2066. if (cmSystemTools::FileIsFullPath(inName)) {
  2067. std::string tLocation;
  2068. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  2069. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  2070. tLocation = target->GetLocation(config);
  2071. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  2072. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  2073. }
  2074. std::string depLocation =
  2075. cmSystemTools::GetFilenamePath(std::string(inName));
  2076. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  2077. if (depLocation != tLocation) {
  2078. // it is a full path to a depend that has the same name
  2079. // as a target but is in a different location so do not use
  2080. // the target as the depend
  2081. dep = inName;
  2082. return true;
  2083. }
  2084. }
  2085. switch (target->GetType()) {
  2086. case cmStateEnums::EXECUTABLE:
  2087. case cmStateEnums::STATIC_LIBRARY:
  2088. case cmStateEnums::SHARED_LIBRARY:
  2089. case cmStateEnums::MODULE_LIBRARY:
  2090. case cmStateEnums::UNKNOWN_LIBRARY:
  2091. dep = target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  2092. /*realname=*/true);
  2093. return true;
  2094. case cmStateEnums::OBJECT_LIBRARY:
  2095. // An object library has no single file on which to depend.
  2096. // This was listed to get the target-level dependency.
  2097. case cmStateEnums::INTERFACE_LIBRARY:
  2098. // An interface library has no file on which to depend.
  2099. // This was listed to get the target-level dependency.
  2100. case cmStateEnums::UTILITY:
  2101. case cmStateEnums::GLOBAL_TARGET:
  2102. // A utility target has no file on which to depend. This was listed
  2103. // only to get the target-level dependency.
  2104. return false;
  2105. }
  2106. }
  2107. // The name was not that of a CMake target. It must name a file.
  2108. if (cmSystemTools::FileIsFullPath(inName)) {
  2109. // This is a full path. Return it as given.
  2110. dep = inName;
  2111. return true;
  2112. }
  2113. // Check for a source file in this directory that matches the
  2114. // dependency.
  2115. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  2116. dep = sf->ResolveFullPath();
  2117. return true;
  2118. }
  2119. // Treat the name as relative to the source directory in which it
  2120. // was given.
  2121. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  2122. // If the in-source path does not exist, assume it instead lives in the
  2123. // binary directory.
  2124. if (!cmSystemTools::FileExists(dep)) {
  2125. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  2126. }
  2127. dep = cmSystemTools::CollapseFullPath(dep, this->GetBinaryDirectory());
  2128. return true;
  2129. }
  2130. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  2131. const std::string& lang, bool shared)
  2132. {
  2133. std::string flagsVar;
  2134. // Add flags for dealing with shared libraries for this language.
  2135. if (shared) {
  2136. this->AppendFlags(flags,
  2137. this->Makefile->GetSafeDefinition(
  2138. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  2139. }
  2140. }
  2141. static void AddVisibilityCompileOption(std::string& flags,
  2142. cmGeneratorTarget const* target,
  2143. cmLocalGenerator* lg,
  2144. const std::string& lang,
  2145. std::string* warnCMP0063)
  2146. {
  2147. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  2148. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2149. if (!opt) {
  2150. return;
  2151. }
  2152. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  2153. cmValue prop = target->GetProperty(flagDefine);
  2154. if (!prop) {
  2155. return;
  2156. }
  2157. if (warnCMP0063) {
  2158. *warnCMP0063 += " " + flagDefine + "\n";
  2159. return;
  2160. }
  2161. if ((*prop != "hidden") && (*prop != "default") && (*prop != "protected") &&
  2162. (*prop != "internal")) {
  2163. std::ostringstream e;
  2164. e << "Target " << target->GetName() << " uses unsupported value \""
  2165. << *prop << "\" for " << flagDefine << "."
  2166. << " The supported values are: default, hidden, protected, and "
  2167. "internal.";
  2168. cmSystemTools::Error(e.str());
  2169. return;
  2170. }
  2171. std::string option = *opt + *prop;
  2172. lg->AppendFlags(flags, option);
  2173. }
  2174. static void AddInlineVisibilityCompileOption(std::string& flags,
  2175. cmGeneratorTarget const* target,
  2176. cmLocalGenerator* lg,
  2177. std::string* warnCMP0063,
  2178. const std::string& lang)
  2179. {
  2180. std::string compileOption =
  2181. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2182. cmValue opt = lg->GetMakefile()->GetDefinition(compileOption);
  2183. if (!opt) {
  2184. return;
  2185. }
  2186. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2187. if (!prop) {
  2188. return;
  2189. }
  2190. if (warnCMP0063) {
  2191. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2192. return;
  2193. }
  2194. lg->AppendFlags(flags, *opt);
  2195. }
  2196. void cmLocalGenerator::AddVisibilityPresetFlags(
  2197. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2198. {
  2199. if (lang.empty()) {
  2200. return;
  2201. }
  2202. std::string warnCMP0063;
  2203. std::string* pWarnCMP0063 = nullptr;
  2204. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2205. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2206. !target->IsExecutableWithExports()) {
  2207. switch (target->GetPolicyStatusCMP0063()) {
  2208. case cmPolicies::OLD:
  2209. return;
  2210. case cmPolicies::WARN:
  2211. pWarnCMP0063 = &warnCMP0063;
  2212. break;
  2213. default:
  2214. break;
  2215. }
  2216. }
  2217. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2218. if (lang == "CXX" || lang == "OBJCXX") {
  2219. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2220. }
  2221. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2222. std::ostringstream w;
  2223. /* clang-format off */
  2224. w <<
  2225. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2226. "Target \"" << target->GetName() << "\" of "
  2227. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2228. "has the following visibility properties set for " << lang << ":\n" <<
  2229. warnCMP0063 <<
  2230. "For compatibility CMake is not honoring them for this target.";
  2231. /* clang-format on */
  2232. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2233. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2234. }
  2235. }
  2236. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2237. cmGeneratorTarget const* target,
  2238. std::string const& lang,
  2239. const std::string& config)
  2240. {
  2241. int targetType = target->GetType();
  2242. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2243. (targetType == cmStateEnums::MODULE_LIBRARY));
  2244. if (this->GetShouldUseOldFlags(shared, lang)) {
  2245. this->AddSharedFlags(flags, lang, shared);
  2246. } else {
  2247. if (target->GetLinkInterfaceDependentBoolProperty(
  2248. "POSITION_INDEPENDENT_CODE", config)) {
  2249. this->AddPositionIndependentFlags(flags, lang, targetType);
  2250. }
  2251. if (shared) {
  2252. this->AppendFeatureOptions(flags, lang, "DLL");
  2253. }
  2254. }
  2255. }
  2256. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2257. const std::string& lang) const
  2258. {
  2259. std::string originalFlags =
  2260. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2261. if (shared) {
  2262. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2263. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2264. if (flags != originalFlags) {
  2265. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2266. case cmPolicies::WARN: {
  2267. std::ostringstream e;
  2268. e << "Variable " << flagsVar
  2269. << " has been modified. CMake "
  2270. "will ignore the POSITION_INDEPENDENT_CODE target property "
  2271. "for "
  2272. "shared libraries and will use the "
  2273. << flagsVar
  2274. << " variable "
  2275. "instead. This may cause errors if the original content of "
  2276. << flagsVar << " was removed.\n"
  2277. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2278. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2279. CM_FALLTHROUGH;
  2280. }
  2281. case cmPolicies::OLD:
  2282. return true;
  2283. case cmPolicies::REQUIRED_IF_USED:
  2284. case cmPolicies::REQUIRED_ALWAYS:
  2285. case cmPolicies::NEW:
  2286. return false;
  2287. }
  2288. }
  2289. }
  2290. return false;
  2291. }
  2292. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2293. std::string const& lang,
  2294. int targetType)
  2295. {
  2296. std::string picFlags;
  2297. if (targetType == cmStateEnums::EXECUTABLE) {
  2298. picFlags = this->Makefile->GetSafeDefinition(
  2299. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2300. }
  2301. if (picFlags.empty()) {
  2302. picFlags = this->Makefile->GetSafeDefinition(
  2303. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2304. }
  2305. if (!picFlags.empty()) {
  2306. cmList options{ picFlags };
  2307. for (std::string const& o : options) {
  2308. this->AppendFlagEscape(flags, o);
  2309. }
  2310. }
  2311. }
  2312. void cmLocalGenerator::AddColorDiagnosticsFlags(std::string& flags,
  2313. const std::string& lang)
  2314. {
  2315. cmValue diag = this->Makefile->GetDefinition("CMAKE_COLOR_DIAGNOSTICS");
  2316. if (diag.IsSet()) {
  2317. std::string colorFlagName;
  2318. if (diag.IsOn()) {
  2319. colorFlagName =
  2320. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS");
  2321. } else {
  2322. colorFlagName =
  2323. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_COLOR_DIAGNOSTICS_OFF");
  2324. }
  2325. cmList options{ this->Makefile->GetDefinition(colorFlagName) };
  2326. for (auto const& option : options) {
  2327. this->AppendFlagEscape(flags, option);
  2328. }
  2329. }
  2330. }
  2331. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2332. const std::string& var,
  2333. const std::string& config)
  2334. {
  2335. // Add the flags from the variable itself.
  2336. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2337. // Add the flags from the build-type specific variable.
  2338. if (!config.empty()) {
  2339. const std::string flagsVar =
  2340. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2341. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2342. }
  2343. }
  2344. void cmLocalGenerator::AppendFlags(std::string& flags,
  2345. const std::string& newFlags) const
  2346. {
  2347. bool allSpaces = std::all_of(newFlags.begin(), newFlags.end(), cmIsSpace);
  2348. if (!newFlags.empty() && !allSpaces) {
  2349. if (!flags.empty()) {
  2350. flags += " ";
  2351. }
  2352. flags += newFlags;
  2353. }
  2354. }
  2355. void cmLocalGenerator::AppendFlags(
  2356. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2357. {
  2358. for (BT<std::string> const& flag : newFlags) {
  2359. this->AppendFlags(flags, flag.Value);
  2360. }
  2361. }
  2362. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2363. const std::string& rawFlag) const
  2364. {
  2365. this->AppendFlags(
  2366. flags,
  2367. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2368. }
  2369. void cmLocalGenerator::AddISPCDependencies(cmGeneratorTarget* target)
  2370. {
  2371. std::vector<std::string> enabledLanguages =
  2372. this->GetState()->GetEnabledLanguages();
  2373. if (std::find(enabledLanguages.begin(), enabledLanguages.end(), "ISPC") ==
  2374. enabledLanguages.end()) {
  2375. return;
  2376. }
  2377. cmValue ispcHeaderSuffixProp = target->GetProperty("ISPC_HEADER_SUFFIX");
  2378. assert(ispcHeaderSuffixProp);
  2379. std::vector<std::string> ispcArchSuffixes =
  2380. detail::ComputeISPCObjectSuffixes(target);
  2381. const bool extra_objects = (ispcArchSuffixes.size() > 1);
  2382. std::vector<std::string> configsList =
  2383. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2384. for (std::string const& config : configsList) {
  2385. std::string rootObjectDir = target->GetObjectDirectory(config);
  2386. std::string headerDir = rootObjectDir;
  2387. if (cmValue prop = target->GetProperty("ISPC_HEADER_DIRECTORY")) {
  2388. headerDir = cmSystemTools::CollapseFullPath(
  2389. cmStrCat(this->GetBinaryDirectory(), '/', *prop));
  2390. }
  2391. std::vector<cmSourceFile*> sources;
  2392. target->GetSourceFiles(sources, config);
  2393. // build up the list of ispc headers and extra objects that this target is
  2394. // generating
  2395. for (cmSourceFile const* sf : sources) {
  2396. // Generate this object file's rule file.
  2397. const std::string& lang = sf->GetLanguage();
  2398. if (lang == "ISPC") {
  2399. std::string const& objectName = target->GetObjectName(sf);
  2400. // Drop both ".obj" and the source file extension
  2401. std::string ispcSource =
  2402. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  2403. ispcSource =
  2404. cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  2405. auto headerPath =
  2406. cmStrCat(headerDir, '/', ispcSource, *ispcHeaderSuffixProp);
  2407. target->AddISPCGeneratedHeader(headerPath, config);
  2408. if (extra_objects) {
  2409. std::vector<std::string> objs = detail::ComputeISPCExtraObjects(
  2410. objectName, rootObjectDir, ispcArchSuffixes);
  2411. target->AddISPCGeneratedObject(std::move(objs), config);
  2412. }
  2413. }
  2414. }
  2415. }
  2416. }
  2417. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2418. {
  2419. std::vector<std::string> configsList =
  2420. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2421. for (std::string const& config : configsList) {
  2422. // FIXME: Refactor collection of sources to not evaluate object
  2423. // libraries.
  2424. std::vector<cmSourceFile*> sources;
  2425. target->GetSourceFiles(sources, config);
  2426. const std::string configUpper = cmSystemTools::UpperCase(config);
  2427. static const std::array<std::string, 4> langs = { { "C", "CXX", "OBJC",
  2428. "OBJCXX" } };
  2429. std::set<std::string> pchLangSet;
  2430. if (this->GetGlobalGenerator()->IsXcode()) {
  2431. for (const std::string& lang : langs) {
  2432. const std::string pchHeader = target->GetPchHeader(config, lang, "");
  2433. if (!pchHeader.empty()) {
  2434. pchLangSet.emplace(lang);
  2435. }
  2436. }
  2437. }
  2438. for (const std::string& lang : langs) {
  2439. auto langSources = std::count_if(
  2440. sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2441. return lang == sf->GetLanguage() &&
  2442. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2443. });
  2444. if (langSources == 0) {
  2445. continue;
  2446. }
  2447. std::vector<std::string> architectures;
  2448. if (!this->GetGlobalGenerator()->IsXcode()) {
  2449. architectures = target->GetAppleArchs(config, lang);
  2450. }
  2451. if (architectures.empty()) {
  2452. architectures.emplace_back();
  2453. } else {
  2454. std::string useMultiArchPch;
  2455. for (const std::string& arch : architectures) {
  2456. const std::string pchHeader =
  2457. target->GetPchHeader(config, lang, arch);
  2458. if (!pchHeader.empty()) {
  2459. useMultiArchPch = cmStrCat(useMultiArchPch, ";-Xarch_", arch,
  2460. ";-include", pchHeader);
  2461. }
  2462. }
  2463. if (!useMultiArchPch.empty()) {
  2464. target->Target->AppendProperty(
  2465. cmStrCat(lang, "_COMPILE_OPTIONS_USE_PCH"),
  2466. cmStrCat("$<$<CONFIG:", config, ">:", useMultiArchPch, ">"));
  2467. }
  2468. }
  2469. for (const std::string& arch : architectures) {
  2470. const std::string pchSource = target->GetPchSource(config, lang, arch);
  2471. const std::string pchHeader = target->GetPchHeader(config, lang, arch);
  2472. if (pchSource.empty() || pchHeader.empty()) {
  2473. if (this->GetGlobalGenerator()->IsXcode() && !pchLangSet.empty()) {
  2474. for (auto* sf : sources) {
  2475. const auto sourceLanguage = sf->GetLanguage();
  2476. if (!sourceLanguage.empty() &&
  2477. pchLangSet.find(sourceLanguage) == pchLangSet.end()) {
  2478. sf->SetProperty("SKIP_PRECOMPILE_HEADERS", "ON");
  2479. }
  2480. }
  2481. }
  2482. continue;
  2483. }
  2484. cmValue pchExtension =
  2485. this->Makefile->GetDefinition("CMAKE_PCH_EXTENSION");
  2486. if (pchExtension.IsEmpty()) {
  2487. continue;
  2488. }
  2489. cmValue ReuseFrom =
  2490. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2491. auto* pch_sf = this->Makefile->GetOrCreateSource(
  2492. pchSource, false, cmSourceFileLocationKind::Known);
  2493. // PCH sources should never be scanned as they cannot contain C++
  2494. // module references.
  2495. pch_sf->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2496. if (!this->GetGlobalGenerator()->IsXcode()) {
  2497. if (!ReuseFrom) {
  2498. target->AddSource(pchSource, true);
  2499. }
  2500. const std::string pchFile = target->GetPchFile(config, lang, arch);
  2501. // Exclude the pch files from linking
  2502. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2503. if (!ReuseFrom) {
  2504. pch_sf->AppendProperty(
  2505. "OBJECT_OUTPUTS",
  2506. cmStrCat("$<$<CONFIG:", config, ">:", pchFile, ">"));
  2507. } else {
  2508. auto* reuseTarget =
  2509. this->GlobalGenerator->FindGeneratorTarget(*ReuseFrom);
  2510. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2511. const std::string compilerId =
  2512. this->Makefile->GetSafeDefinition(
  2513. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2514. const std::string compilerVersion =
  2515. this->Makefile->GetSafeDefinition(
  2516. cmStrCat("CMAKE_", lang, "_COMPILER_VERSION"));
  2517. const std::string langFlags =
  2518. this->Makefile->GetSafeDefinition(
  2519. cmStrCat("CMAKE_", lang, "_FLAGS_", configUpper));
  2520. bool editAndContinueDebugInfo = false;
  2521. bool programDatabaseDebugInfo = false;
  2522. cm::optional<std::string> msvcDebugInformationFormat =
  2523. this->GetMSVCDebugFormatName(config, target);
  2524. if (msvcDebugInformationFormat &&
  2525. !msvcDebugInformationFormat->empty()) {
  2526. editAndContinueDebugInfo =
  2527. *msvcDebugInformationFormat == "EditAndContinue";
  2528. programDatabaseDebugInfo =
  2529. *msvcDebugInformationFormat == "ProgramDatabase";
  2530. } else {
  2531. editAndContinueDebugInfo =
  2532. langFlags.find("/ZI") != std::string::npos ||
  2533. langFlags.find("-ZI") != std::string::npos;
  2534. programDatabaseDebugInfo =
  2535. langFlags.find("/Zi") != std::string::npos ||
  2536. langFlags.find("-Zi") != std::string::npos;
  2537. }
  2538. // MSVC 2008 is producing both .pdb and .idb files with /Zi.
  2539. bool msvc2008OrLess =
  2540. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  2541. compilerVersion, "16.0") &&
  2542. compilerId == "MSVC";
  2543. // but not when used via toolset -Tv90
  2544. if (this->Makefile->GetSafeDefinition(
  2545. "CMAKE_VS_PLATFORM_TOOLSET") == "v90") {
  2546. msvc2008OrLess = false;
  2547. }
  2548. if (editAndContinueDebugInfo || msvc2008OrLess) {
  2549. this->CopyPchCompilePdb(config, lang, target, *ReuseFrom,
  2550. reuseTarget, { ".pdb", ".idb" });
  2551. } else if (programDatabaseDebugInfo) {
  2552. this->CopyPchCompilePdb(config, lang, target, *ReuseFrom,
  2553. reuseTarget, { ".pdb" });
  2554. }
  2555. }
  2556. // Link to the pch object file
  2557. std::string pchSourceObj =
  2558. reuseTarget->GetPchFileObject(config, lang, arch);
  2559. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  2560. std::string linkerProperty = "LINK_FLAGS_";
  2561. if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
  2562. linkerProperty = "STATIC_LIBRARY_FLAGS_";
  2563. }
  2564. target->Target->AppendProperty(
  2565. cmStrCat(linkerProperty, configUpper),
  2566. cmStrCat(" ",
  2567. this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2568. cm::nullopt, true);
  2569. } else if (reuseTarget->GetType() ==
  2570. cmStateEnums::OBJECT_LIBRARY) {
  2571. target->Target->AppendProperty(
  2572. "INTERFACE_LINK_LIBRARIES",
  2573. cmStrCat("$<$<CONFIG:", config,
  2574. ">:$<LINK_ONLY:", pchSourceObj, ">>"));
  2575. }
  2576. }
  2577. } else {
  2578. pch_sf->SetProperty("PCH_EXTENSION", pchExtension);
  2579. }
  2580. // Add pchHeader to source files, which will
  2581. // be grouped as "Precompile Header File"
  2582. auto* pchHeader_sf = this->Makefile->GetOrCreateSource(
  2583. pchHeader, false, cmSourceFileLocationKind::Known);
  2584. std::string err;
  2585. pchHeader_sf->ResolveFullPath(&err);
  2586. if (!err.empty()) {
  2587. std::ostringstream msg;
  2588. msg << "Unable to resolve full path of PCH-header '" << pchHeader
  2589. << "' assigned to target " << target->GetName()
  2590. << ", although its path is supposed to be known!";
  2591. this->IssueMessage(MessageType::FATAL_ERROR, msg.str());
  2592. }
  2593. target->AddSource(pchHeader);
  2594. }
  2595. }
  2596. }
  2597. }
  2598. }
  2599. void cmLocalGenerator::CopyPchCompilePdb(
  2600. const std::string& config, const std::string& language,
  2601. cmGeneratorTarget* target, const std::string& ReuseFrom,
  2602. cmGeneratorTarget* reuseTarget, const std::vector<std::string>& extensions)
  2603. {
  2604. const std::string pdb_prefix =
  2605. this->GetGlobalGenerator()->IsMultiConfig() ? cmStrCat(config, "/") : "";
  2606. const std::string target_compile_pdb_dir =
  2607. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2608. target->GetName(), ".dir/");
  2609. const std::string copy_script = cmStrCat(
  2610. target_compile_pdb_dir, "copy_idb_pdb_", config.c_str(), ".cmake");
  2611. cmGeneratedFileStream file(copy_script);
  2612. file << "# CMake generated file\n";
  2613. file << "# The compiler generated pdb file needs to be written to disk\n"
  2614. << "# by mspdbsrv. The foreach retry loop is needed to make sure\n"
  2615. << "# the pdb file is ready to be copied.\n\n";
  2616. for (auto const& extension : extensions) {
  2617. const std::string from_file =
  2618. cmStrCat(reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2619. "/", ReuseFrom, ".dir/${PDB_PREFIX}", ReuseFrom, extension);
  2620. const std::string to_dir =
  2621. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2622. target->GetName(), ".dir/${PDB_PREFIX}");
  2623. const std::string to_file = cmStrCat(to_dir, ReuseFrom, extension);
  2624. std::string dest_file = to_file;
  2625. std::string const& prefix = target->GetSafeProperty("PREFIX");
  2626. if (!prefix.empty()) {
  2627. dest_file = cmStrCat(to_dir, prefix, ReuseFrom, extension);
  2628. }
  2629. file << "foreach(retry RANGE 1 30)\n";
  2630. file << " if (EXISTS \"" << from_file << "\" AND (NOT EXISTS \""
  2631. << dest_file << "\" OR NOT \"" << dest_file << " \" IS_NEWER_THAN \""
  2632. << from_file << "\"))\n";
  2633. file << " execute_process(COMMAND ${CMAKE_COMMAND} -E copy";
  2634. file << " \"" << from_file << "\""
  2635. << " \"" << to_dir << "\" RESULT_VARIABLE result "
  2636. << " ERROR_QUIET)\n";
  2637. file << " if (NOT result EQUAL 0)\n"
  2638. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2639. << " -E sleep 1)\n"
  2640. << " else()\n";
  2641. if (!prefix.empty()) {
  2642. file << " file(REMOVE \"" << dest_file << "\")\n";
  2643. file << " file(RENAME \"" << to_file << "\" \"" << dest_file << "\")\n";
  2644. }
  2645. file << " break()\n"
  2646. << " endif()\n";
  2647. file << " elseif(NOT EXISTS \"" << from_file << "\")\n"
  2648. << " execute_process(COMMAND ${CMAKE_COMMAND}"
  2649. << " -E sleep 1)\n"
  2650. << " endif()\n";
  2651. file << "endforeach()\n";
  2652. }
  2653. auto configGenex = [&](cm::string_view expr) -> std::string {
  2654. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2655. return cmStrCat("$<$<CONFIG:", config, ">:", expr, ">");
  2656. }
  2657. return std::string(expr);
  2658. };
  2659. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2660. { configGenex(cmSystemTools::GetCMakeCommand()),
  2661. configGenex(cmStrCat("-DPDB_PREFIX=", pdb_prefix)), configGenex("-P"),
  2662. configGenex(copy_script) });
  2663. const char* no_message = "";
  2664. std::vector<std::string> outputs;
  2665. outputs.push_back(configGenex(
  2666. cmStrCat(target_compile_pdb_dir, pdb_prefix, ReuseFrom, ".pdb")));
  2667. auto cc = cm::make_unique<cmCustomCommand>();
  2668. cc->SetCommandLines(commandLines);
  2669. cc->SetComment(no_message);
  2670. cc->SetStdPipesUTF8(true);
  2671. cc->AppendDepends({ reuseTarget->GetPchFile(config, language) });
  2672. if (this->GetGlobalGenerator()->IsVisualStudio()) {
  2673. cc->SetByproducts(outputs);
  2674. this->AddCustomCommandToTarget(
  2675. target->GetName(), cmCustomCommandType::PRE_BUILD, std::move(cc),
  2676. cmObjectLibraryCommands::Accept);
  2677. } else {
  2678. cc->SetOutputs(outputs);
  2679. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(std::move(cc));
  2680. copy_rule->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2681. if (copy_rule) {
  2682. target->AddSource(copy_rule->ResolveFullPath());
  2683. }
  2684. }
  2685. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2686. target_compile_pdb_dir);
  2687. }
  2688. cm::optional<std::string> cmLocalGenerator::GetMSVCDebugFormatName(
  2689. std::string const& config, cmGeneratorTarget const* target)
  2690. {
  2691. // MSVC debug information format selection is activated by the presence
  2692. // of a default whether or not it is overridden by a property.
  2693. cm::optional<std::string> msvcDebugInformationFormat;
  2694. cmValue msvcDebugInformationFormatDefault = this->Makefile->GetDefinition(
  2695. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT");
  2696. if (cmNonempty(msvcDebugInformationFormatDefault)) {
  2697. cmValue msvcDebugInformationFormatValue =
  2698. target->GetProperty("MSVC_DEBUG_INFORMATION_FORMAT");
  2699. if (!msvcDebugInformationFormatValue) {
  2700. msvcDebugInformationFormatValue = msvcDebugInformationFormatDefault;
  2701. }
  2702. msvcDebugInformationFormat = cmGeneratorExpression::Evaluate(
  2703. *msvcDebugInformationFormatValue, this, config, target);
  2704. }
  2705. return msvcDebugInformationFormat;
  2706. }
  2707. cm::optional<cmSwiftCompileMode> cmLocalGenerator::GetSwiftCompileMode(
  2708. cmGeneratorTarget const* target, std::string const& config)
  2709. {
  2710. cmMakefile const* mf = this->GetMakefile();
  2711. cmValue const swiftCompileModeDefault =
  2712. mf->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT");
  2713. if (!cmNonempty(swiftCompileModeDefault)) {
  2714. return {};
  2715. }
  2716. cmValue swiftCompileMode = target->GetProperty("Swift_COMPILATION_MODE");
  2717. if (!swiftCompileMode) {
  2718. swiftCompileMode = swiftCompileModeDefault;
  2719. }
  2720. std::string const expandedCompileMode =
  2721. cmGeneratorExpression::Evaluate(*swiftCompileMode, this, config, target);
  2722. if (expandedCompileMode == "wholemodule") {
  2723. return cmSwiftCompileMode::Wholemodule;
  2724. }
  2725. if (expandedCompileMode == "singlefile") {
  2726. return cmSwiftCompileMode::Singlefile;
  2727. }
  2728. if (expandedCompileMode == "incremental") {
  2729. return cmSwiftCompileMode::Incremental;
  2730. }
  2731. return cmSwiftCompileMode::Unknown;
  2732. }
  2733. bool cmLocalGenerator::IsSplitSwiftBuild() const
  2734. {
  2735. return cmNonempty(this->GetMakefile()->GetDefinition(
  2736. "CMAKE_Swift_COMPILATION_MODE_DEFAULT"));
  2737. }
  2738. namespace {
  2739. inline void RegisterUnitySources(cmGeneratorTarget* target, cmSourceFile* sf,
  2740. std::string const& filename)
  2741. {
  2742. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2743. sf->SetProperty("UNITY_SOURCE_FILE", filename);
  2744. }
  2745. }
  2746. cmLocalGenerator::UnitySource cmLocalGenerator::WriteUnitySource(
  2747. cmGeneratorTarget* target, std::vector<std::string> const& configs,
  2748. cmRange<std::vector<UnityBatchedSource>::const_iterator> sources,
  2749. cmValue beforeInclude, cmValue afterInclude, std::string filename) const
  2750. {
  2751. cmValue uniqueIdName = target->GetProperty("UNITY_BUILD_UNIQUE_ID");
  2752. cmGeneratedFileStream file(
  2753. filename, false, target->GetGlobalGenerator()->GetMakefileEncoding());
  2754. file.SetCopyIfDifferent(true);
  2755. file << "/* generated by CMake */\n\n";
  2756. bool perConfig = false;
  2757. for (UnityBatchedSource const& ubs : sources) {
  2758. cm::optional<std::string> cond;
  2759. if (ubs.Configs.size() != configs.size()) {
  2760. perConfig = true;
  2761. cond = std::string();
  2762. cm::string_view sep;
  2763. for (size_t ci : ubs.Configs) {
  2764. cond = cmStrCat(*cond, sep, "defined(CMAKE_UNITY_CONFIG_",
  2765. cmSystemTools::UpperCase(configs[ci]), ")");
  2766. sep = " || "_s;
  2767. }
  2768. }
  2769. RegisterUnitySources(target, ubs.Source, filename);
  2770. WriteUnitySourceInclude(file, cond, ubs.Source->ResolveFullPath(),
  2771. beforeInclude, afterInclude, uniqueIdName);
  2772. }
  2773. return UnitySource(std::move(filename), perConfig);
  2774. }
  2775. void cmLocalGenerator::WriteUnitySourceInclude(
  2776. std::ostream& unity_file, cm::optional<std::string> const& cond,
  2777. std::string const& sf_full_path, cmValue beforeInclude, cmValue afterInclude,
  2778. cmValue uniqueIdName) const
  2779. {
  2780. if (cond) {
  2781. unity_file << "#if " << *cond << "\n";
  2782. }
  2783. if (cmNonempty(uniqueIdName)) {
  2784. std::string pathToHash;
  2785. auto PathEqOrSubDir = [](std::string const& a, std::string const& b) {
  2786. return (cmSystemTools::ComparePath(a, b) ||
  2787. cmSystemTools::IsSubDirectory(a, b));
  2788. };
  2789. const auto path = cmSystemTools::GetFilenamePath(sf_full_path);
  2790. if (PathEqOrSubDir(path, this->GetBinaryDirectory())) {
  2791. pathToHash = "BLD_" +
  2792. cmSystemTools::RelativePath(this->GetBinaryDirectory(), sf_full_path);
  2793. } else if (PathEqOrSubDir(path, this->GetSourceDirectory())) {
  2794. pathToHash = "SRC_" +
  2795. cmSystemTools::RelativePath(this->GetSourceDirectory(), sf_full_path);
  2796. } else {
  2797. pathToHash = "ABS_" + sf_full_path;
  2798. }
  2799. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  2800. unity_file << "/* " << pathToHash << " */\n"
  2801. << "#undef " << *uniqueIdName << "\n"
  2802. << "#define " << *uniqueIdName << " unity_"
  2803. << hasher.HashString(pathToHash) << "\n";
  2804. }
  2805. if (beforeInclude) {
  2806. unity_file << *beforeInclude << "\n";
  2807. }
  2808. unity_file << "/* NOLINTNEXTLINE(bugprone-suspicious-include) */\n";
  2809. unity_file << "#include \"" << sf_full_path << "\"\n";
  2810. if (afterInclude) {
  2811. unity_file << *afterInclude << "\n";
  2812. }
  2813. if (cond) {
  2814. unity_file << "#endif\n";
  2815. }
  2816. unity_file << "\n";
  2817. }
  2818. std::vector<cmLocalGenerator::UnitySource>
  2819. cmLocalGenerator::AddUnityFilesModeAuto(
  2820. cmGeneratorTarget* target, std::string const& lang,
  2821. std::vector<std::string> const& configs,
  2822. std::vector<UnityBatchedSource> const& filtered_sources,
  2823. cmValue beforeInclude, cmValue afterInclude,
  2824. std::string const& filename_base, size_t batchSize)
  2825. {
  2826. if (batchSize == 0) {
  2827. batchSize = filtered_sources.size();
  2828. }
  2829. std::vector<UnitySource> unity_files;
  2830. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2831. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2832. chunk = std::min(itemsLeft, batchSize);
  2833. std::string extension;
  2834. if (lang == "C") {
  2835. extension = "_c.c";
  2836. } else if (lang == "CXX") {
  2837. extension = "_cxx.cxx";
  2838. } else if (lang == "OBJC") {
  2839. extension = "_m.m";
  2840. } else if (lang == "OBJCXX") {
  2841. extension = "_mm.mm";
  2842. }
  2843. std::string filename = cmStrCat(filename_base, "unity_", batch, extension);
  2844. auto const begin = filtered_sources.begin() + batch * batchSize;
  2845. auto const end = begin + chunk;
  2846. unity_files.emplace_back(this->WriteUnitySource(
  2847. target, configs, cmMakeRange(begin, end), beforeInclude, afterInclude,
  2848. std::move(filename)));
  2849. }
  2850. return unity_files;
  2851. }
  2852. std::vector<cmLocalGenerator::UnitySource>
  2853. cmLocalGenerator::AddUnityFilesModeGroup(
  2854. cmGeneratorTarget* target, std::string const& lang,
  2855. std::vector<std::string> const& configs,
  2856. std::vector<UnityBatchedSource> const& filtered_sources,
  2857. cmValue beforeInclude, cmValue afterInclude,
  2858. std::string const& filename_base)
  2859. {
  2860. std::vector<UnitySource> unity_files;
  2861. // sources organized by group name. Drop any source
  2862. // without a group
  2863. std::unordered_map<std::string, std::vector<UnityBatchedSource>>
  2864. explicit_mapping;
  2865. for (UnityBatchedSource const& ubs : filtered_sources) {
  2866. if (cmValue value = ubs.Source->GetProperty("UNITY_GROUP")) {
  2867. auto i = explicit_mapping.find(*value);
  2868. if (i == explicit_mapping.end()) {
  2869. std::vector<UnityBatchedSource> sources{ ubs };
  2870. explicit_mapping.emplace(*value, std::move(sources));
  2871. } else {
  2872. i->second.emplace_back(ubs);
  2873. }
  2874. }
  2875. }
  2876. for (auto const& item : explicit_mapping) {
  2877. auto const& name = item.first;
  2878. std::string filename = cmStrCat(filename_base, "unity_", name,
  2879. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2880. unity_files.emplace_back(this->WriteUnitySource(
  2881. target, configs, cmMakeRange(item.second), beforeInclude, afterInclude,
  2882. std::move(filename)));
  2883. }
  2884. return unity_files;
  2885. }
  2886. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2887. {
  2888. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2889. return;
  2890. }
  2891. std::vector<UnityBatchedSource> unitySources;
  2892. std::vector<std::string> configs =
  2893. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2894. std::map<cmSourceFile const*, size_t> index;
  2895. for (size_t ci = 0; ci < configs.size(); ++ci) {
  2896. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2897. // Their final set of object files might be transformed by unity builds.
  2898. std::vector<cmSourceFile*> sources;
  2899. target->GetSourceFiles(sources, configs[ci]);
  2900. for (cmSourceFile* sf : sources) {
  2901. // Files which need C++ scanning cannot participate in unity builds as
  2902. // there is a single place in TUs that may perform module-dependency bits
  2903. // and a unity source cannot `#include` them in-order and represent a
  2904. // valid TU.
  2905. if (sf->GetLanguage() == "CXX"_s &&
  2906. target->NeedDyndepForSource("CXX", configs[ci], sf)) {
  2907. continue;
  2908. }
  2909. auto mi = index.find(sf);
  2910. if (mi == index.end()) {
  2911. unitySources.emplace_back(sf);
  2912. std::map<cmSourceFile const*, size_t>::value_type entry(
  2913. sf, unitySources.size() - 1);
  2914. mi = index.insert(entry).first;
  2915. }
  2916. unitySources[mi->second].Configs.emplace_back(ci);
  2917. }
  2918. }
  2919. std::string filename_base =
  2920. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2921. target->GetName(), ".dir/Unity/");
  2922. cmValue batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2923. const size_t unityBatchSize = batchSizeString
  2924. ? static_cast<size_t>(std::atoi(batchSizeString->c_str()))
  2925. : 0;
  2926. cmValue beforeInclude =
  2927. target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2928. cmValue afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2929. cmValue unityMode = target->GetProperty("UNITY_BUILD_MODE");
  2930. for (std::string lang : { "C", "CXX", "OBJC", "OBJCXX" }) {
  2931. std::vector<UnityBatchedSource> filtered_sources;
  2932. std::copy_if(unitySources.begin(), unitySources.end(),
  2933. std::back_inserter(filtered_sources),
  2934. [&](UnityBatchedSource const& ubs) -> bool {
  2935. cmSourceFile* sf = ubs.Source;
  2936. return sf->GetLanguage() == lang &&
  2937. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2938. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2939. !sf->GetProperty("COMPILE_OPTIONS") &&
  2940. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2941. !sf->GetProperty("COMPILE_FLAGS") &&
  2942. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2943. });
  2944. std::vector<UnitySource> unity_files;
  2945. if (!unityMode || *unityMode == "BATCH") {
  2946. unity_files = AddUnityFilesModeAuto(
  2947. target, lang, configs, filtered_sources, beforeInclude, afterInclude,
  2948. filename_base, unityBatchSize);
  2949. } else if (unityMode && *unityMode == "GROUP") {
  2950. unity_files =
  2951. AddUnityFilesModeGroup(target, lang, configs, filtered_sources,
  2952. beforeInclude, afterInclude, filename_base);
  2953. } else {
  2954. // unity mode is set to an unsupported value
  2955. std::string e("Invalid UNITY_BUILD_MODE value of " + *unityMode +
  2956. " assigned to target " + target->GetName() +
  2957. ". Acceptable values are BATCH and GROUP.");
  2958. this->IssueMessage(MessageType::FATAL_ERROR, e);
  2959. }
  2960. for (UnitySource const& file : unity_files) {
  2961. auto* unity = this->GetMakefile()->GetOrCreateSource(file.Path);
  2962. target->AddSource(file.Path, true);
  2963. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2964. unity->SetProperty("UNITY_SOURCE_FILE", file.Path);
  2965. unity->SetProperty("CXX_SCAN_FOR_MODULES", "0");
  2966. if (file.PerConfig) {
  2967. unity->SetProperty("COMPILE_DEFINITIONS",
  2968. "CMAKE_UNITY_CONFIG_$<UPPER_CASE:$<CONFIG>>");
  2969. }
  2970. }
  2971. }
  2972. }
  2973. void cmLocalGenerator::AppendLinkerTypeFlags(std::string& flags,
  2974. cmGeneratorTarget* target,
  2975. const std::string& config,
  2976. const std::string& linkLanguage)
  2977. {
  2978. switch (target->GetType()) {
  2979. case cmStateEnums::EXECUTABLE:
  2980. case cmStateEnums::SHARED_LIBRARY:
  2981. case cmStateEnums::MODULE_LIBRARY:
  2982. break;
  2983. default:
  2984. return;
  2985. }
  2986. auto usingLinker =
  2987. cmStrCat("CMAKE_", linkLanguage, "_USING_",
  2988. target->IsDeviceLink() ? "DEVICE_" : "", "LINKER_");
  2989. auto format = this->Makefile->GetDefinition(cmStrCat(usingLinker, "MODE"));
  2990. if (format && format != "FLAG"_s) {
  2991. return;
  2992. }
  2993. auto linkerType = target->GetLinkerTypeProperty(linkLanguage, config);
  2994. if (linkerType.empty()) {
  2995. linkerType = "DEFAULT";
  2996. }
  2997. usingLinker = cmStrCat(usingLinker, linkerType);
  2998. auto linkerTypeFlags = this->Makefile->GetDefinition(usingLinker);
  2999. if (linkerTypeFlags) {
  3000. if (!linkerTypeFlags.IsEmpty()) {
  3001. auto linkerFlags = cmExpandListWithBacktrace(linkerTypeFlags);
  3002. target->ResolveLinkerWrapper(linkerFlags, linkLanguage);
  3003. this->AppendFlags(flags, linkerFlags);
  3004. }
  3005. } else if (linkerType != "DEFAULT"_s) {
  3006. auto isCMakeLinkerType = [](const std::string& type) -> bool {
  3007. return std::all_of(type.cbegin(), type.cend(),
  3008. [](char c) { return std::isupper(c); });
  3009. };
  3010. if (isCMakeLinkerType(linkerType)) {
  3011. this->IssueMessage(
  3012. MessageType::FATAL_ERROR,
  3013. cmStrCat("LINKER_TYPE '", linkerType,
  3014. "' is unknown or not supported by this toolchain."));
  3015. } else {
  3016. this->IssueMessage(
  3017. MessageType::FATAL_ERROR,
  3018. cmStrCat("LINKER_TYPE '", linkerType,
  3019. "' is unknown. Did you forget to define the '", usingLinker,
  3020. "' variable?"));
  3021. }
  3022. }
  3023. }
  3024. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  3025. cmGeneratorTarget* target,
  3026. const std::string& config,
  3027. const std::string& lang)
  3028. {
  3029. if (!target->IsIPOEnabled(lang, config)) {
  3030. return;
  3031. }
  3032. switch (target->GetType()) {
  3033. case cmStateEnums::EXECUTABLE:
  3034. case cmStateEnums::SHARED_LIBRARY:
  3035. case cmStateEnums::MODULE_LIBRARY:
  3036. break;
  3037. default:
  3038. return;
  3039. }
  3040. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  3041. cmValue rawFlagsList = this->Makefile->GetDefinition(name);
  3042. if (!rawFlagsList) {
  3043. return;
  3044. }
  3045. cmList flagsList{ *rawFlagsList };
  3046. for (std::string const& o : flagsList) {
  3047. this->AppendFlagEscape(flags, o);
  3048. }
  3049. }
  3050. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  3051. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  3052. const std::string& lang)
  3053. {
  3054. // For now, only EXECUTABLE is concerned
  3055. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  3056. return;
  3057. }
  3058. const char* PICValue = target->GetLinkPIEProperty(config);
  3059. if (PICValue == nullptr) {
  3060. // POSITION_INDEPENDENT_CODE is not set
  3061. return;
  3062. }
  3063. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  3064. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  3065. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  3066. return;
  3067. }
  3068. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  3069. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  3070. if (pieFlags.empty()) {
  3071. return;
  3072. }
  3073. cmList flagsList{ pieFlags };
  3074. for (const auto& flag : flagsList) {
  3075. this->AppendFlagEscape(flags, flag);
  3076. }
  3077. }
  3078. void cmLocalGenerator::AppendDependencyInfoLinkerFlags(
  3079. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  3080. const std::string& linkLanguage)
  3081. {
  3082. if (!this->GetGlobalGenerator()->SupportsLinkerDependencyFile() ||
  3083. !target->HasLinkDependencyFile(config)) {
  3084. return;
  3085. }
  3086. auto depFlag = *this->Makefile->GetDefinition(
  3087. cmStrCat("CMAKE_", linkLanguage, "_LINKER_DEPFILE_FLAGS"));
  3088. if (depFlag.empty()) {
  3089. return;
  3090. }
  3091. auto depFile = this->ConvertToOutputFormat(
  3092. this->MaybeRelativeToWorkDir(this->GetLinkDependencyFile(target, config)),
  3093. cmOutputConverter::SHELL);
  3094. auto rulePlaceholderExpander = this->CreateRulePlaceholderExpander();
  3095. cmRulePlaceholderExpander::RuleVariables linkDepsVariables;
  3096. linkDepsVariables.DependencyFile = depFile.c_str();
  3097. rulePlaceholderExpander->ExpandRuleVariables(this, depFlag,
  3098. linkDepsVariables);
  3099. auto depFlags = cmExpandListWithBacktrace(depFlag);
  3100. target->ResolveLinkerWrapper(depFlags, linkLanguage);
  3101. this->AppendFlags(flags, depFlags);
  3102. }
  3103. std::string cmLocalGenerator::GetLinkDependencyFile(
  3104. cmGeneratorTarget* /*target*/, const std::string& /*config*/) const
  3105. {
  3106. return "link.d";
  3107. }
  3108. void cmLocalGenerator::AppendModuleDefinitionFlag(
  3109. std::string& flags, cmGeneratorTarget const* target,
  3110. cmLinkLineComputer* linkLineComputer, std::string const& config)
  3111. {
  3112. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  3113. target->GetModuleDefinitionInfo(config);
  3114. if (!mdi || mdi->DefFile.empty()) {
  3115. return;
  3116. }
  3117. cmValue defFileFlag =
  3118. this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  3119. if (!defFileFlag) {
  3120. return;
  3121. }
  3122. // Append the flag and value. Use ConvertToLinkReference to help
  3123. // vs6's "cl -link" pass it to the linker.
  3124. std::string flag =
  3125. cmStrCat(*defFileFlag,
  3126. this->ConvertToOutputFormat(
  3127. linkLineComputer->ConvertToLinkReference(mdi->DefFile),
  3128. cmOutputConverter::SHELL));
  3129. this->AppendFlags(flags, flag);
  3130. }
  3131. bool cmLocalGenerator::AppendLWYUFlags(std::string& flags,
  3132. const cmGeneratorTarget* target,
  3133. const std::string& lang)
  3134. {
  3135. auto useLWYU = target->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
  3136. (target->GetType() == cmStateEnums::TargetType::EXECUTABLE ||
  3137. target->GetType() == cmStateEnums::TargetType::SHARED_LIBRARY ||
  3138. target->GetType() == cmStateEnums::TargetType::MODULE_LIBRARY);
  3139. if (useLWYU) {
  3140. const auto& lwyuFlag = this->GetMakefile()->GetSafeDefinition(
  3141. cmStrCat("CMAKE_", lang, "_LINK_WHAT_YOU_USE_FLAG"));
  3142. useLWYU = !lwyuFlag.empty();
  3143. if (useLWYU) {
  3144. std::vector<BT<std::string>> lwyuOpts;
  3145. lwyuOpts.emplace_back(lwyuFlag);
  3146. this->AppendFlags(flags, target->ResolveLinkerWrapper(lwyuOpts, lang));
  3147. }
  3148. }
  3149. return useLWYU;
  3150. }
  3151. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  3152. std::string const& options_list,
  3153. const char* regex) const
  3154. {
  3155. // Short-circuit if there are no options.
  3156. if (options_list.empty()) {
  3157. return;
  3158. }
  3159. // Expand the list of options.
  3160. cmList options_vec{ options_list };
  3161. this->AppendCompileOptions(options, options_vec, regex);
  3162. }
  3163. void cmLocalGenerator::AppendCompileOptions(
  3164. std::string& options, const std::vector<std::string>& options_vec,
  3165. const char* regex) const
  3166. {
  3167. if (regex != nullptr) {
  3168. // Filter flags upon specified reges.
  3169. cmsys::RegularExpression r(regex);
  3170. for (std::string const& opt : options_vec) {
  3171. if (r.find(opt)) {
  3172. this->AppendFlagEscape(options, opt);
  3173. }
  3174. }
  3175. } else {
  3176. for (std::string const& opt : options_vec) {
  3177. this->AppendFlagEscape(options, opt);
  3178. }
  3179. }
  3180. }
  3181. void cmLocalGenerator::AppendCompileOptions(
  3182. std::vector<BT<std::string>>& options,
  3183. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  3184. {
  3185. if (regex != nullptr) {
  3186. // Filter flags upon specified regular expressions.
  3187. cmsys::RegularExpression r(regex);
  3188. for (BT<std::string> const& opt : options_vec) {
  3189. if (r.find(opt.Value)) {
  3190. std::string flag;
  3191. this->AppendFlagEscape(flag, opt.Value);
  3192. options.emplace_back(std::move(flag), opt.Backtrace);
  3193. }
  3194. }
  3195. } else {
  3196. for (BT<std::string> const& opt : options_vec) {
  3197. std::string flag;
  3198. this->AppendFlagEscape(flag, opt.Value);
  3199. options.emplace_back(std::move(flag), opt.Backtrace);
  3200. }
  3201. }
  3202. }
  3203. void cmLocalGenerator::AppendIncludeDirectories(
  3204. std::vector<std::string>& includes, const std::string& includes_list,
  3205. const cmSourceFile& sourceFile) const
  3206. {
  3207. // Short-circuit if there are no includes.
  3208. if (includes_list.empty()) {
  3209. return;
  3210. }
  3211. // Expand the list of includes.
  3212. cmList includes_vec{ includes_list };
  3213. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  3214. }
  3215. void cmLocalGenerator::AppendIncludeDirectories(
  3216. std::vector<std::string>& includes,
  3217. const std::vector<std::string>& includes_vec,
  3218. const cmSourceFile& sourceFile) const
  3219. {
  3220. std::unordered_set<std::string> uniqueIncludes;
  3221. for (const std::string& include : includes_vec) {
  3222. if (!cmSystemTools::FileIsFullPath(include)) {
  3223. std::ostringstream e;
  3224. e << "Found relative path while evaluating include directories of "
  3225. "\""
  3226. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  3227. << "\"\n";
  3228. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3229. return;
  3230. }
  3231. std::string inc = include;
  3232. if (!cmIsOff(inc)) {
  3233. cmSystemTools::ConvertToUnixSlashes(inc);
  3234. }
  3235. if (uniqueIncludes.insert(inc).second) {
  3236. includes.push_back(std::move(inc));
  3237. }
  3238. }
  3239. }
  3240. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  3241. std::string const& defines_list) const
  3242. {
  3243. std::set<BT<std::string>> tmp;
  3244. this->AppendDefines(tmp, cmExpandListWithBacktrace(defines_list));
  3245. for (BT<std::string> const& i : tmp) {
  3246. defines.emplace(i.Value);
  3247. }
  3248. }
  3249. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  3250. std::string const& defines_list) const
  3251. {
  3252. // Short-circuit if there are no definitions.
  3253. if (defines_list.empty()) {
  3254. return;
  3255. }
  3256. // Expand the list of definitions.
  3257. this->AppendDefines(defines, cmExpandListWithBacktrace(defines_list));
  3258. }
  3259. void cmLocalGenerator::AppendDefines(
  3260. std::set<BT<std::string>>& defines,
  3261. const std::vector<BT<std::string>>& defines_vec) const
  3262. {
  3263. for (BT<std::string> const& d : defines_vec) {
  3264. // Skip unsupported definitions.
  3265. if (!this->CheckDefinition(d.Value)) {
  3266. continue;
  3267. }
  3268. // remove any leading -D
  3269. if (cmHasLiteralPrefix(d.Value, "-D")) {
  3270. defines.emplace(d.Value.substr(2), d.Backtrace);
  3271. } else {
  3272. defines.insert(d);
  3273. }
  3274. }
  3275. }
  3276. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  3277. std::string& definesString,
  3278. const std::string& lang)
  3279. {
  3280. // Lookup the define flag for the current language.
  3281. std::string dflag = "-D";
  3282. if (!lang.empty()) {
  3283. cmValue df =
  3284. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  3285. if (cmNonempty(df)) {
  3286. dflag = *df;
  3287. }
  3288. }
  3289. const char* itemSeparator = definesString.empty() ? "" : " ";
  3290. for (std::string const& define : defines) {
  3291. // Append the definition with proper escaping.
  3292. std::string def = dflag;
  3293. if (this->GetState()->UseWatcomWMake()) {
  3294. // The Watcom compiler does its own command line parsing instead
  3295. // of using the windows shell rules. Definitions are one of
  3296. // -DNAME
  3297. // -DNAME=<cpp-token>
  3298. // -DNAME="c-string with spaces and other characters(?@#$)"
  3299. //
  3300. // Watcom will properly parse each of these cases from the
  3301. // command line without any escapes. However we still have to
  3302. // get the '$' and '#' characters through WMake as '$$' and
  3303. // '$#'.
  3304. for (char c : define) {
  3305. if (c == '$' || c == '#') {
  3306. def += '$';
  3307. }
  3308. def += c;
  3309. }
  3310. } else {
  3311. // Make the definition appear properly on the command line. Use
  3312. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  3313. std::string::size_type eq = define.find('=');
  3314. def += define.substr(0, eq);
  3315. if (eq != std::string::npos) {
  3316. def += "=";
  3317. def += this->EscapeForShell(define.substr(eq + 1), true);
  3318. }
  3319. }
  3320. definesString += itemSeparator;
  3321. itemSeparator = " ";
  3322. definesString += def;
  3323. }
  3324. }
  3325. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  3326. const std::string& lang,
  3327. const char* feature)
  3328. {
  3329. cmValue optionList = this->Makefile->GetDefinition(
  3330. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  3331. if (optionList) {
  3332. cmList options{ *optionList };
  3333. for (std::string const& o : options) {
  3334. this->AppendFlagEscape(flags, o);
  3335. }
  3336. }
  3337. }
  3338. cmValue cmLocalGenerator::GetFeature(const std::string& feature,
  3339. const std::string& config)
  3340. {
  3341. std::string featureName = feature;
  3342. // TODO: Define accumulation policy for features (prepend, append,
  3343. // replace). Currently we always replace.
  3344. if (!config.empty()) {
  3345. featureName += "_";
  3346. featureName += cmSystemTools::UpperCase(config);
  3347. }
  3348. cmStateSnapshot snp = this->StateSnapshot;
  3349. while (snp.IsValid()) {
  3350. if (cmValue value = snp.GetDirectory().GetProperty(featureName)) {
  3351. return value;
  3352. }
  3353. snp = snp.GetBuildsystemDirectoryParent();
  3354. }
  3355. return nullptr;
  3356. }
  3357. std::string cmLocalGenerator::GetProjectName() const
  3358. {
  3359. return this->StateSnapshot.GetProjectName();
  3360. }
  3361. std::string cmLocalGenerator::ConstructComment(
  3362. cmCustomCommandGenerator const& ccg, const char* default_comment) const
  3363. {
  3364. // Check for a comment provided with the command.
  3365. if (cm::optional<std::string> comment = ccg.GetComment()) {
  3366. return *comment;
  3367. }
  3368. // Construct a reasonable default comment if possible.
  3369. if (!ccg.GetOutputs().empty()) {
  3370. std::string comment;
  3371. comment = "Generating ";
  3372. const char* sep = "";
  3373. for (std::string const& o : ccg.GetOutputs()) {
  3374. comment += sep;
  3375. comment += this->MaybeRelativeToCurBinDir(o);
  3376. sep = ", ";
  3377. }
  3378. return comment;
  3379. }
  3380. // Otherwise use the provided default.
  3381. return default_comment;
  3382. }
  3383. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  3384. {
  3385. public:
  3386. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  3387. std::string const& dest, bool implib)
  3388. : cmInstallTargetGenerator(
  3389. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  3390. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  3391. false)
  3392. {
  3393. this->Compute(lg);
  3394. }
  3395. };
  3396. void cmLocalGenerator::GenerateTargetInstallRules(
  3397. std::ostream& os, const std::string& config,
  3398. std::vector<std::string> const& configurationTypes)
  3399. {
  3400. // Convert the old-style install specification from each target to
  3401. // an install generator and run it.
  3402. const auto& tgts = this->GetGeneratorTargets();
  3403. for (const auto& l : tgts) {
  3404. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3405. continue;
  3406. }
  3407. // Include the user-specified pre-install script for this target.
  3408. if (cmValue preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  3409. cmInstallScriptGenerator g(*preinstall, false, "", false, false);
  3410. g.Generate(os, config, configurationTypes);
  3411. }
  3412. // Install this target if a destination is given.
  3413. if (!l->Target->GetInstallPath().empty()) {
  3414. // Compute the full install destination. Note that converting
  3415. // to unix slashes also removes any trailing slash.
  3416. // We also skip over the leading slash given by the user.
  3417. std::string destination = l->Target->GetInstallPath().substr(1);
  3418. cmSystemTools::ConvertToUnixSlashes(destination);
  3419. if (destination.empty()) {
  3420. destination = ".";
  3421. }
  3422. // Generate the proper install generator for this target type.
  3423. switch (l->GetType()) {
  3424. case cmStateEnums::EXECUTABLE:
  3425. case cmStateEnums::STATIC_LIBRARY:
  3426. case cmStateEnums::MODULE_LIBRARY: {
  3427. // Use a target install generator.
  3428. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3429. false);
  3430. g.Generate(os, config, configurationTypes);
  3431. } break;
  3432. case cmStateEnums::SHARED_LIBRARY: {
  3433. #if defined(_WIN32) || defined(__CYGWIN__)
  3434. // Special code to handle DLL. Install the import library
  3435. // to the normal destination and the DLL to the runtime
  3436. // destination.
  3437. cmInstallTargetGeneratorLocal g1(this, l->GetName(), destination,
  3438. true);
  3439. g1.Generate(os, config, configurationTypes);
  3440. // We also skip over the leading slash given by the user.
  3441. destination = l->Target->GetRuntimeInstallPath().substr(1);
  3442. cmSystemTools::ConvertToUnixSlashes(destination);
  3443. cmInstallTargetGeneratorLocal g2(this, l->GetName(), destination,
  3444. false);
  3445. g2.Generate(os, config, configurationTypes);
  3446. #else
  3447. // Use a target install generator.
  3448. cmInstallTargetGeneratorLocal g(this, l->GetName(), destination,
  3449. false);
  3450. g.Generate(os, config, configurationTypes);
  3451. #endif
  3452. } break;
  3453. default:
  3454. break;
  3455. }
  3456. }
  3457. // Include the user-specified post-install script for this target.
  3458. if (cmValue postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  3459. cmInstallScriptGenerator g(*postinstall, false, "", false, false);
  3460. g.Generate(os, config, configurationTypes);
  3461. }
  3462. }
  3463. }
  3464. namespace {
  3465. bool cmLocalGeneratorShortenObjectName(std::string& objName,
  3466. std::string::size_type max_len)
  3467. {
  3468. // Check if the path can be shortened using an md5 sum replacement for
  3469. // a portion of the path.
  3470. std::string::size_type md5Len = 32;
  3471. std::string::size_type numExtraChars = objName.size() - max_len + md5Len;
  3472. std::string::size_type pos = objName.find('/', numExtraChars);
  3473. if (pos == std::string::npos) {
  3474. pos = objName.rfind('/', numExtraChars);
  3475. if (pos == std::string::npos || pos <= md5Len) {
  3476. return false;
  3477. }
  3478. }
  3479. // Replace the beginning of the path portion of the object name with
  3480. // its own md5 sum.
  3481. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  3482. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  3483. cm::string_view(objName).substr(pos));
  3484. objName = md5name;
  3485. // The object name is now shorter, check if it is short enough.
  3486. return pos >= numExtraChars;
  3487. }
  3488. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  3489. std::string::size_type dir_len,
  3490. std::string::size_type max_total_len)
  3491. {
  3492. // Enforce the maximum file name length if possible.
  3493. std::string::size_type max_obj_len = max_total_len;
  3494. if (dir_len < max_total_len) {
  3495. max_obj_len = max_total_len - dir_len;
  3496. if (objName.size() > max_obj_len) {
  3497. // The current object file name is too long. Try to shorten it.
  3498. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  3499. }
  3500. // The object file name is short enough.
  3501. return true;
  3502. }
  3503. // The build directory in which the object will be stored is
  3504. // already too deep.
  3505. return false;
  3506. }
  3507. }
  3508. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  3509. const std::string& sin, std::string const& dir_max)
  3510. {
  3511. // Look for an existing mapped name for this object file.
  3512. auto it = this->UniqueObjectNamesMap.find(sin);
  3513. // If no entry exists create one.
  3514. if (it == this->UniqueObjectNamesMap.end()) {
  3515. // Start with the original name.
  3516. std::string ssin = sin;
  3517. // Avoid full paths by removing leading slashes.
  3518. ssin.erase(0, ssin.find_first_not_of('/'));
  3519. // Avoid full paths by removing colons.
  3520. std::replace(ssin.begin(), ssin.end(), ':', '_');
  3521. // Avoid relative paths that go up the tree.
  3522. cmSystemTools::ReplaceString(ssin, "../", "__/");
  3523. // Avoid spaces.
  3524. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  3525. // Mangle the name if necessary.
  3526. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  3527. bool done;
  3528. int cc = 0;
  3529. char rpstr[100];
  3530. snprintf(rpstr, sizeof(rpstr), "_p_");
  3531. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  3532. std::string sssin = sin;
  3533. do {
  3534. done = true;
  3535. for (it = this->UniqueObjectNamesMap.begin();
  3536. it != this->UniqueObjectNamesMap.end(); ++it) {
  3537. if (it->second == ssin) {
  3538. done = false;
  3539. }
  3540. }
  3541. if (done) {
  3542. break;
  3543. }
  3544. sssin = ssin;
  3545. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  3546. snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
  3547. } while (!done);
  3548. }
  3549. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  3550. this->ObjectPathMax)) {
  3551. // Warn if this is the first time the path has been seen.
  3552. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  3553. std::ostringstream m;
  3554. /* clang-format off */
  3555. m << "The object file directory\n"
  3556. << " " << dir_max << "\n"
  3557. << "has " << dir_max.size() << " characters. "
  3558. << "The maximum full path to an object file is "
  3559. << this->ObjectPathMax << " characters "
  3560. << "(see CMAKE_OBJECT_PATH_MAX). "
  3561. << "Object file\n"
  3562. << " " << ssin << "\n"
  3563. << "cannot be safely placed under this directory. "
  3564. << "The build may not work correctly.";
  3565. /* clang-format on */
  3566. this->IssueMessage(MessageType::WARNING, m.str());
  3567. }
  3568. }
  3569. // Insert the newly mapped object file name.
  3570. std::map<std::string, std::string>::value_type e(sin, ssin);
  3571. it = this->UniqueObjectNamesMap.insert(e).first;
  3572. }
  3573. // Return the map entry.
  3574. return it->second;
  3575. }
  3576. void cmLocalGenerator::ComputeObjectFilenames(
  3577. std::map<cmSourceFile const*, std::string>& /*unused*/,
  3578. cmGeneratorTarget const* /*unused*/)
  3579. {
  3580. }
  3581. bool cmLocalGenerator::IsWindowsShell() const
  3582. {
  3583. return this->GetState()->UseWindowsShell();
  3584. }
  3585. bool cmLocalGenerator::IsWatcomWMake() const
  3586. {
  3587. return this->GetState()->UseWatcomWMake();
  3588. }
  3589. bool cmLocalGenerator::IsMinGWMake() const
  3590. {
  3591. return this->GetState()->UseMinGWMake();
  3592. }
  3593. bool cmLocalGenerator::IsNMake() const
  3594. {
  3595. return this->GetState()->UseNMake();
  3596. }
  3597. bool cmLocalGenerator::IsNinjaMulti() const
  3598. {
  3599. return this->GetState()->UseNinjaMulti();
  3600. }
  3601. namespace {
  3602. std::string relativeIfUnder(std::string const& top, std::string const& cur,
  3603. std::string const& path)
  3604. {
  3605. // Use a path relative to 'cur' if it can be expressed without
  3606. // a `../` sequence that leaves 'top'.
  3607. if (cmSystemTools::IsSubDirectory(path, cur) ||
  3608. (cmSystemTools::IsSubDirectory(cur, top) &&
  3609. cmSystemTools::IsSubDirectory(path, top))) {
  3610. return cmSystemTools::ForceToRelativePath(cur, path);
  3611. }
  3612. return path;
  3613. }
  3614. }
  3615. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  3616. const cmSourceFile& source, std::string const& dir_max,
  3617. bool* hasSourceExtension, char const* customOutputExtension)
  3618. {
  3619. // Construct the object file name using the full path to the source
  3620. // file which is its only unique identification.
  3621. std::string const& fullPath = source.GetFullPath();
  3622. // Try referencing the source relative to the source tree.
  3623. std::string relFromSource = relativeIfUnder(
  3624. this->GetSourceDirectory(), this->GetCurrentSourceDirectory(), fullPath);
  3625. assert(!relFromSource.empty());
  3626. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  3627. bool subSource = relSource && relFromSource[0] != '.';
  3628. // Try referencing the source relative to the binary tree.
  3629. std::string relFromBinary = relativeIfUnder(
  3630. this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory(), fullPath);
  3631. assert(!relFromBinary.empty());
  3632. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  3633. bool subBinary = relBinary && relFromBinary[0] != '.';
  3634. // Select a nice-looking reference to the source file to construct
  3635. // the object file name.
  3636. std::string objectName;
  3637. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  3638. // NOLINTNEXTLINE(bugprone-branch-clone)
  3639. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  3640. objectName = relFromSource;
  3641. } else if ((relBinary && !relSource) || (subBinary && !subSource) ||
  3642. relFromBinary.length() < relFromSource.length()) {
  3643. objectName = relFromBinary;
  3644. } else {
  3645. objectName = relFromSource;
  3646. }
  3647. // if it is still a full path check for the try compile case
  3648. // try compile never have in source sources, and should not
  3649. // have conflicting source file names in the same target
  3650. if (cmSystemTools::FileIsFullPath(objectName)) {
  3651. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  3652. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  3653. }
  3654. }
  3655. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  3656. // we don't end up having:
  3657. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  3658. cmValue unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  3659. cmValue pchExtension = source.GetProperty("PCH_EXTENSION");
  3660. const bool isPchObject = objectName.find("cmake_pch") != std::string::npos;
  3661. if (unitySourceFile || pchExtension || isPchObject) {
  3662. if (pchExtension) {
  3663. customOutputExtension = pchExtension->c_str();
  3664. }
  3665. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  3666. if (var.find(objectName)) {
  3667. objectName.erase(var.start(), var.end() - var.start());
  3668. }
  3669. }
  3670. // Replace the original source file extension with the object file
  3671. // extension.
  3672. bool keptSourceExtension = true;
  3673. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  3674. // Decide whether this language wants to replace the source
  3675. // extension with the object extension. For CMake 2.4
  3676. // compatibility do this by default.
  3677. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  3678. if (!replaceExt) {
  3679. std::string lang = source.GetLanguage();
  3680. if (!lang.empty()) {
  3681. replaceExt = this->Makefile->IsOn(
  3682. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  3683. }
  3684. }
  3685. // Remove the source extension if it is to be replaced.
  3686. if (replaceExt || customOutputExtension) {
  3687. keptSourceExtension = false;
  3688. std::string::size_type dot_pos = objectName.rfind('.');
  3689. if (dot_pos != std::string::npos) {
  3690. objectName = objectName.substr(0, dot_pos);
  3691. }
  3692. }
  3693. // Store the new extension.
  3694. if (customOutputExtension) {
  3695. objectName += customOutputExtension;
  3696. } else {
  3697. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  3698. }
  3699. }
  3700. if (hasSourceExtension) {
  3701. *hasSourceExtension = keptSourceExtension;
  3702. }
  3703. // Convert to a safe name.
  3704. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  3705. }
  3706. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  3707. {
  3708. return source.GetLanguage();
  3709. }
  3710. cmake* cmLocalGenerator::GetCMakeInstance() const
  3711. {
  3712. return this->GlobalGenerator->GetCMakeInstance();
  3713. }
  3714. std::string const& cmLocalGenerator::GetSourceDirectory() const
  3715. {
  3716. return this->GetCMakeInstance()->GetHomeDirectory();
  3717. }
  3718. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  3719. {
  3720. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  3721. }
  3722. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  3723. {
  3724. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  3725. }
  3726. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  3727. {
  3728. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  3729. }
  3730. std::string cmLocalGenerator::GetTargetDirectory(
  3731. const cmGeneratorTarget* /*unused*/) const
  3732. {
  3733. cmSystemTools::Error("GetTargetDirectory"
  3734. " called on cmLocalGenerator");
  3735. return "";
  3736. }
  3737. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3738. {
  3739. // The computed version may change until the project is fully
  3740. // configured.
  3741. if (!this->BackwardsCompatibilityFinal) {
  3742. unsigned int major = 0;
  3743. unsigned int minor = 0;
  3744. unsigned int patch = 0;
  3745. if (cmValue value =
  3746. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3747. switch (sscanf(value->c_str(), "%u.%u.%u", &major, &minor, &patch)) {
  3748. case 2:
  3749. patch = 0;
  3750. break;
  3751. case 1:
  3752. minor = 0;
  3753. patch = 0;
  3754. break;
  3755. default:
  3756. break;
  3757. }
  3758. }
  3759. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3760. this->BackwardsCompatibilityFinal = true;
  3761. }
  3762. return this->BackwardsCompatibility;
  3763. }
  3764. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3765. {
  3766. // Check the policy to decide whether to pay attention to this
  3767. // variable.
  3768. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3769. case cmPolicies::WARN:
  3770. // WARN is just OLD without warning because user code does not
  3771. // always affect whether this check is done.
  3772. CM_FALLTHROUGH;
  3773. case cmPolicies::OLD:
  3774. // Old behavior is to check the variable.
  3775. break;
  3776. case cmPolicies::NEW:
  3777. // New behavior is to ignore the variable.
  3778. case cmPolicies::REQUIRED_IF_USED:
  3779. case cmPolicies::REQUIRED_ALWAYS:
  3780. // This will never be the case because the only way to require
  3781. // the setting is to require the user to specify version policy
  3782. // 2.6 or higher. Once we add that requirement then this whole
  3783. // method can be removed anyway.
  3784. return false;
  3785. }
  3786. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3787. // equal to or lower than the given version.
  3788. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3789. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3790. }
  3791. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3792. cmPolicies::PolicyID id) const
  3793. {
  3794. return this->Makefile->GetPolicyStatus(id);
  3795. }
  3796. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3797. {
  3798. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3799. std::string::size_type pos = define.find_first_of("(=");
  3800. if (pos != std::string::npos) {
  3801. if (define[pos] == '(') {
  3802. std::ostringstream e;
  3803. /* clang-format off */
  3804. e << "WARNING: Function-style preprocessor definitions may not be "
  3805. << "passed on the compiler command line because many compilers "
  3806. << "do not support it.\n"
  3807. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3808. << "Consider defining the macro in a (configured) header file.\n";
  3809. /* clang-format on */
  3810. cmSystemTools::Message(e.str());
  3811. return false;
  3812. }
  3813. }
  3814. // Many compilers do not support # in the value so we disable it.
  3815. if (define.find_first_of('#') != std::string::npos) {
  3816. std::ostringstream e;
  3817. /* clang-format off */
  3818. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3819. << "passed on the compiler command line because many compilers "
  3820. << "do not support it.\n"
  3821. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3822. << "Consider defining the macro in a (configured) header file.\n";
  3823. /* clang-format on */
  3824. cmSystemTools::Message(e.str());
  3825. return false;
  3826. }
  3827. // Assume it is supported.
  3828. return true;
  3829. }
  3830. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3831. const std::string& prop)
  3832. {
  3833. if (cmValue val = target->GetProperty(prop)) {
  3834. mf->AddDefinition(prop, *val);
  3835. }
  3836. }
  3837. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3838. const std::string& targetName,
  3839. const std::string& fname)
  3840. {
  3841. // Find the Info.plist template.
  3842. cmValue in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3843. std::string inFile = cmNonempty(in) ? *in : "MacOSXBundleInfo.plist.in";
  3844. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3845. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3846. if (!inMod.empty()) {
  3847. inFile = inMod;
  3848. }
  3849. }
  3850. if (!cmSystemTools::FileExists(inFile, true)) {
  3851. std::ostringstream e;
  3852. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3853. << "\" could not be found.";
  3854. cmSystemTools::Error(e.str());
  3855. return;
  3856. }
  3857. // Convert target properties to variables in an isolated makefile
  3858. // scope to configure the file. If properties are set they will
  3859. // override user make variables. If not the configuration will fall
  3860. // back to the directory-level values set by the user.
  3861. cmMakefile* mf = this->Makefile;
  3862. cmMakefile::ScopePushPop varScope(mf);
  3863. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3864. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3865. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3866. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3867. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3868. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3869. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3870. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3871. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3872. mf->ConfigureFile(inFile, fname, false, false, false);
  3873. }
  3874. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3875. cmGeneratorTarget* target, const std::string& targetName,
  3876. const std::string& fname)
  3877. {
  3878. // Find the Info.plist template.
  3879. cmValue in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3880. std::string inFile = cmNonempty(in) ? *in : "MacOSXFrameworkInfo.plist.in";
  3881. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3882. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3883. if (!inMod.empty()) {
  3884. inFile = inMod;
  3885. }
  3886. }
  3887. if (!cmSystemTools::FileExists(inFile, true)) {
  3888. std::ostringstream e;
  3889. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3890. << "\" could not be found.";
  3891. cmSystemTools::Error(e.str());
  3892. return;
  3893. }
  3894. // Convert target properties to variables in an isolated makefile
  3895. // scope to configure the file. If properties are set they will
  3896. // override user make variables. If not the configuration will fall
  3897. // back to the directory-level values set by the user.
  3898. cmMakefile* mf = this->Makefile;
  3899. cmMakefile::ScopePushPop varScope(mf);
  3900. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3901. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3902. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3903. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3904. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3905. mf->ConfigureFile(inFile, fname, false, false, false);
  3906. }
  3907. namespace {
  3908. cm::string_view CustomOutputRoleKeyword(cmLocalGenerator::OutputRole role)
  3909. {
  3910. return (role == cmLocalGenerator::OutputRole::Primary ? "OUTPUT"_s
  3911. : "BYPRODUCTS"_s);
  3912. }
  3913. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3914. cmLocalGenerator::OutputRole role,
  3915. cmCommandOrigin origin,
  3916. const cmListFileBacktrace& lfbt)
  3917. {
  3918. if (cmGeneratorExpression::Find(output) != std::string::npos) {
  3919. lg.GetCMakeInstance()->IssueMessage(
  3920. MessageType::FATAL_ERROR,
  3921. "Generator expressions in custom command outputs are not implemented!",
  3922. lfbt);
  3923. return;
  3924. }
  3925. // Make sure the file will not be generated into the source
  3926. // directory during an out of source build.
  3927. if (!lg.GetMakefile()->CanIWriteThisFile(output)) {
  3928. lg.GetCMakeInstance()->IssueMessage(
  3929. MessageType::FATAL_ERROR,
  3930. cmStrCat(CustomOutputRoleKeyword(role), " path\n ", output,
  3931. "\nin a source directory as an output of custom command."),
  3932. lfbt);
  3933. return;
  3934. }
  3935. // Make sure the output file name has no invalid characters.
  3936. std::string::size_type pos = output.find_first_of("#<>");
  3937. if (pos != std::string::npos) {
  3938. lg.GetCMakeInstance()->IssueMessage(
  3939. MessageType::FATAL_ERROR,
  3940. cmStrCat(CustomOutputRoleKeyword(role), " containing a \"", output[pos],
  3941. "\" is not allowed."),
  3942. lfbt);
  3943. return;
  3944. }
  3945. // Outputs without generator expressions from the project are already
  3946. // created and marked as generated. Do not mark them again, because
  3947. // other commands might have overwritten the property.
  3948. if (origin == cmCommandOrigin::Generator) {
  3949. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3950. }
  3951. }
  3952. std::string ComputeCustomCommandRuleFileName(cmLocalGenerator& lg,
  3953. cmListFileBacktrace const& bt,
  3954. std::string const& output)
  3955. {
  3956. // If the output path has no generator expressions, use it directly.
  3957. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3958. return output;
  3959. }
  3960. // The output path contains a generator expression, but we must choose
  3961. // a single source file path to which to attach the custom command.
  3962. // Use some heuristics to provide a nice-looking name when possible.
  3963. // If the only genex is $<CONFIG>, replace that gracefully.
  3964. {
  3965. std::string simple = output;
  3966. cmSystemTools::ReplaceString(simple, "$<CONFIG>", "(CONFIG)");
  3967. if (cmGeneratorExpression::Find(simple) == std::string::npos) {
  3968. return simple;
  3969. }
  3970. }
  3971. // If the genex evaluates to the same value in all configurations, use that.
  3972. {
  3973. std::vector<std::string> allConfigOutputs =
  3974. lg.ExpandCustomCommandOutputGenex(output, bt);
  3975. if (allConfigOutputs.size() == 1) {
  3976. return allConfigOutputs.front();
  3977. }
  3978. }
  3979. // Fall back to a deterministic unique name.
  3980. cmCryptoHash h(cmCryptoHash::AlgoSHA256);
  3981. return cmStrCat(lg.GetCurrentBinaryDirectory(), "/CMakeFiles/",
  3982. h.HashString(output).substr(0, 16));
  3983. }
  3984. cmSourceFile* AddCustomCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  3985. std::unique_ptr<cmCustomCommand> cc,
  3986. bool replace)
  3987. {
  3988. cmMakefile* mf = lg.GetMakefile();
  3989. const auto& lfbt = cc->GetBacktrace();
  3990. const auto& outputs = cc->GetOutputs();
  3991. const auto& byproducts = cc->GetByproducts();
  3992. const auto& commandLines = cc->GetCommandLines();
  3993. // Choose a source file on which to store the custom command.
  3994. cmSourceFile* file = nullptr;
  3995. if (!commandLines.empty() && cc->HasMainDependency()) {
  3996. const auto& main_dependency = cc->GetMainDependency();
  3997. // The main dependency was specified. Use it unless a different
  3998. // custom command already used it.
  3999. file = mf->GetSource(main_dependency);
  4000. if (file && file->GetCustomCommand() && !replace) {
  4001. // The main dependency already has a custom command.
  4002. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  4003. // The existing custom command is identical. Silently ignore
  4004. // the duplicate.
  4005. return file;
  4006. }
  4007. // The existing custom command is different. We need to
  4008. // generate a rule file for this new command.
  4009. file = nullptr;
  4010. } else if (!file) {
  4011. file = mf->CreateSource(main_dependency);
  4012. }
  4013. }
  4014. // Generate a rule file if the main dependency is not available.
  4015. if (!file) {
  4016. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  4017. // Construct a rule file associated with the first output produced.
  4018. std::string outName = gg->GenerateRuleFile(
  4019. ComputeCustomCommandRuleFileName(lg, lfbt, outputs[0]));
  4020. // Check if the rule file already exists.
  4021. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  4022. if (file && file->GetCustomCommand() && !replace) {
  4023. // The rule file already exists.
  4024. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  4025. lg.GetCMakeInstance()->IssueMessage(
  4026. MessageType::FATAL_ERROR,
  4027. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  4028. "\nwhich already has a custom rule."),
  4029. lfbt);
  4030. }
  4031. return file;
  4032. }
  4033. // Create a cmSourceFile for the rule file.
  4034. if (!file) {
  4035. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  4036. }
  4037. file->SetProperty("__CMAKE_RULE", "1");
  4038. }
  4039. // Attach the custom command to the file.
  4040. if (file) {
  4041. cc->SetEscapeAllowMakeVars(true);
  4042. lg.AddSourceOutputs(file, outputs, cmLocalGenerator::OutputRole::Primary,
  4043. lfbt, origin);
  4044. lg.AddSourceOutputs(file, byproducts,
  4045. cmLocalGenerator::OutputRole::Byproduct, lfbt, origin);
  4046. file->SetCustomCommand(std::move(cc));
  4047. }
  4048. return file;
  4049. }
  4050. bool AnyOutputMatches(const std::string& name,
  4051. const std::vector<std::string>& outputs)
  4052. {
  4053. return std::any_of(outputs.begin(), outputs.end(),
  4054. [&name](std::string const& output) -> bool {
  4055. std::string::size_type pos = output.rfind(name);
  4056. // If the output matches exactly
  4057. return (pos != std::string::npos &&
  4058. pos == output.size() - name.size() &&
  4059. (pos == 0 || output[pos - 1] == '/'));
  4060. });
  4061. }
  4062. bool AnyTargetCommandOutputMatches(
  4063. const std::string& name, const std::vector<cmCustomCommand>& commands)
  4064. {
  4065. return std::any_of(commands.begin(), commands.end(),
  4066. [&name](cmCustomCommand const& command) -> bool {
  4067. return AnyOutputMatches(name, command.GetByproducts());
  4068. });
  4069. }
  4070. }
  4071. namespace detail {
  4072. void AddCustomCommandToTarget(cmLocalGenerator& lg, cmCommandOrigin origin,
  4073. cmTarget* target, cmCustomCommandType type,
  4074. std::unique_ptr<cmCustomCommand> cc)
  4075. {
  4076. // Add the command to the appropriate build step for the target.
  4077. cc->SetEscapeAllowMakeVars(true);
  4078. cc->SetTarget(target->GetName());
  4079. lg.AddTargetByproducts(target, cc->GetByproducts(), cc->GetBacktrace(),
  4080. origin);
  4081. switch (type) {
  4082. case cmCustomCommandType::PRE_BUILD:
  4083. target->AddPreBuildCommand(std::move(*cc));
  4084. break;
  4085. case cmCustomCommandType::PRE_LINK:
  4086. target->AddPreLinkCommand(std::move(*cc));
  4087. break;
  4088. case cmCustomCommandType::POST_BUILD:
  4089. target->AddPostBuildCommand(std::move(*cc));
  4090. break;
  4091. }
  4092. cc.reset();
  4093. }
  4094. cmSourceFile* AddCustomCommandToOutput(cmLocalGenerator& lg,
  4095. cmCommandOrigin origin,
  4096. std::unique_ptr<cmCustomCommand> cc,
  4097. bool replace)
  4098. {
  4099. return AddCustomCommand(lg, origin, std::move(cc), replace);
  4100. }
  4101. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  4102. const cmListFileBacktrace& lfbt,
  4103. const std::string& output,
  4104. const std::vector<std::string>& depends,
  4105. const cmImplicitDependsList& implicit_depends,
  4106. const cmCustomCommandLines& commandLines)
  4107. {
  4108. // Lookup an existing command.
  4109. cmSourceFile* sf = nullptr;
  4110. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  4111. sf = lg.GetSourceFileWithOutput(output);
  4112. } else {
  4113. // This output path has a generator expression. Evaluate it to
  4114. // find the output for any configurations.
  4115. for (std::string const& out :
  4116. lg.ExpandCustomCommandOutputGenex(output, lfbt)) {
  4117. sf = lg.GetSourceFileWithOutput(out);
  4118. if (sf) {
  4119. break;
  4120. }
  4121. }
  4122. }
  4123. if (sf) {
  4124. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  4125. cc->AppendCommands(commandLines);
  4126. cc->AppendDepends(depends);
  4127. cc->AppendImplicitDepends(implicit_depends);
  4128. return;
  4129. }
  4130. }
  4131. // No existing command found.
  4132. lg.GetCMakeInstance()->IssueMessage(
  4133. MessageType::FATAL_ERROR,
  4134. cmStrCat("Attempt to APPEND to custom command with output\n ", output,
  4135. "\nwhich is not already a custom command output."),
  4136. lfbt);
  4137. }
  4138. void AddUtilityCommand(cmLocalGenerator& lg, cmCommandOrigin origin,
  4139. cmTarget* target, std::unique_ptr<cmCustomCommand> cc)
  4140. {
  4141. // They might be moved away
  4142. auto byproducts = cc->GetByproducts();
  4143. auto lfbt = cc->GetBacktrace();
  4144. // Use an empty comment to avoid generation of default comment.
  4145. if (!cc->GetComment()) {
  4146. cc->SetComment("");
  4147. }
  4148. // Create the generated symbolic output name of the utility target.
  4149. std::string output =
  4150. lg.CreateUtilityOutput(target->GetName(), byproducts, lfbt);
  4151. cc->SetOutputs(output);
  4152. cmSourceFile* rule = AddCustomCommand(lg, origin, std::move(cc),
  4153. /*replace=*/false);
  4154. if (rule) {
  4155. lg.AddTargetByproducts(target, byproducts, lfbt, origin);
  4156. }
  4157. target->AddSource(output);
  4158. }
  4159. std::vector<std::string> ComputeISPCObjectSuffixes(cmGeneratorTarget* target)
  4160. {
  4161. const cmValue targetProperty = target->GetProperty("ISPC_INSTRUCTION_SETS");
  4162. cmList ispcTargets;
  4163. if (!targetProperty.IsOff()) {
  4164. ispcTargets.assign(targetProperty);
  4165. for (auto& ispcTarget : ispcTargets) {
  4166. // transform targets into the suffixes
  4167. auto pos = ispcTarget.find('-');
  4168. auto target_suffix = ispcTarget.substr(0, pos);
  4169. if (target_suffix ==
  4170. "avx1") { // when targeting avx1 ISPC uses the 'avx' output string
  4171. target_suffix = "avx";
  4172. }
  4173. ispcTarget = target_suffix;
  4174. }
  4175. }
  4176. return std::move(ispcTargets.data());
  4177. }
  4178. std::vector<std::string> ComputeISPCExtraObjects(
  4179. std::string const& objectName, std::string const& buildDirectory,
  4180. std::vector<std::string> const& ispcSuffixes)
  4181. {
  4182. auto normalizedDir = cmSystemTools::CollapseFullPath(buildDirectory);
  4183. std::vector<std::string> computedObjects;
  4184. computedObjects.reserve(ispcSuffixes.size());
  4185. auto extension = cmSystemTools::GetFilenameLastExtension(objectName);
  4186. // We can't use cmSystemTools::GetFilenameWithoutLastExtension as it
  4187. // drops any directories in objectName
  4188. auto objNameNoExt = objectName;
  4189. std::string::size_type dot_pos = objectName.rfind('.');
  4190. if (dot_pos != std::string::npos) {
  4191. objNameNoExt.resize(dot_pos);
  4192. }
  4193. for (const auto& ispcTarget : ispcSuffixes) {
  4194. computedObjects.emplace_back(
  4195. cmStrCat(normalizedDir, "/", objNameNoExt, "_", ispcTarget, extension));
  4196. }
  4197. return computedObjects;
  4198. }
  4199. }
  4200. cmSourcesWithOutput cmLocalGenerator::GetSourcesWithOutput(
  4201. const std::string& name) const
  4202. {
  4203. // Linear search? Also see GetSourceFileWithOutput for detail.
  4204. if (!cmSystemTools::FileIsFullPath(name)) {
  4205. cmSourcesWithOutput sources;
  4206. sources.Target = this->LinearGetTargetWithOutput(name);
  4207. sources.Source = this->LinearGetSourceFileWithOutput(
  4208. name, cmSourceOutputKind::OutputOrByproduct, sources.SourceIsByproduct);
  4209. return sources;
  4210. }
  4211. // Otherwise we use an efficient lookup map.
  4212. auto o = this->OutputToSource.find(name);
  4213. if (o != this->OutputToSource.end()) {
  4214. return o->second.Sources;
  4215. }
  4216. return {};
  4217. }
  4218. cmSourceFile* cmLocalGenerator::GetSourceFileWithOutput(
  4219. const std::string& name, cmSourceOutputKind kind) const
  4220. {
  4221. // If the queried path is not absolute we use the backward compatible
  4222. // linear-time search for an output with a matching suffix.
  4223. if (!cmSystemTools::FileIsFullPath(name)) {
  4224. bool byproduct = false;
  4225. return this->LinearGetSourceFileWithOutput(name, kind, byproduct);
  4226. }
  4227. // Otherwise we use an efficient lookup map.
  4228. auto o = this->OutputToSource.find(name);
  4229. if (o != this->OutputToSource.end() &&
  4230. (!o->second.Sources.SourceIsByproduct ||
  4231. kind == cmSourceOutputKind::OutputOrByproduct)) {
  4232. // Source file could also be null pointer for example if we found the
  4233. // byproduct of a utility target, a PRE_BUILD, PRE_LINK, or POST_BUILD
  4234. // command of a target, or a not yet created custom command.
  4235. return o->second.Sources.Source;
  4236. }
  4237. return nullptr;
  4238. }
  4239. std::string cmLocalGenerator::CreateUtilityOutput(
  4240. std::string const& targetName, std::vector<std::string> const&,
  4241. cmListFileBacktrace const&)
  4242. {
  4243. std::string force =
  4244. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/", targetName);
  4245. // The output is not actually created so mark it symbolic.
  4246. if (cmSourceFile* sf = this->Makefile->GetOrCreateGeneratedSource(force)) {
  4247. sf->SetProperty("SYMBOLIC", "1");
  4248. } else {
  4249. cmSystemTools::Error("Could not get source file entry for " + force);
  4250. }
  4251. return force;
  4252. }
  4253. std::vector<cmCustomCommandGenerator>
  4254. cmLocalGenerator::MakeCustomCommandGenerators(cmCustomCommand const& cc,
  4255. std::string const& config)
  4256. {
  4257. std::vector<cmCustomCommandGenerator> ccgs;
  4258. ccgs.emplace_back(cc, config, this);
  4259. return ccgs;
  4260. }
  4261. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputPaths(
  4262. cmCompiledGeneratorExpression const& cge, std::string const& config)
  4263. {
  4264. cmList paths{ cge.Evaluate(this, config) };
  4265. for (std::string& p : paths) {
  4266. p = cmSystemTools::CollapseFullPath(p, this->GetCurrentBinaryDirectory());
  4267. }
  4268. return std::move(paths.data());
  4269. }
  4270. std::vector<std::string> cmLocalGenerator::ExpandCustomCommandOutputGenex(
  4271. std::string const& o, cmListFileBacktrace const& bt)
  4272. {
  4273. std::vector<std::string> allConfigOutputs;
  4274. cmGeneratorExpression ge(*this->GetCMakeInstance(), bt);
  4275. std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(o);
  4276. std::vector<std::string> configs =
  4277. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4278. for (std::string const& config : configs) {
  4279. std::vector<std::string> configOutputs =
  4280. this->ExpandCustomCommandOutputPaths(*cge, config);
  4281. allConfigOutputs.reserve(allConfigOutputs.size() + configOutputs.size());
  4282. std::move(configOutputs.begin(), configOutputs.end(),
  4283. std::back_inserter(allConfigOutputs));
  4284. }
  4285. auto endUnique =
  4286. cmRemoveDuplicates(allConfigOutputs.begin(), allConfigOutputs.end());
  4287. allConfigOutputs.erase(endUnique, allConfigOutputs.end());
  4288. return allConfigOutputs;
  4289. }
  4290. void cmLocalGenerator::AddTargetByproducts(
  4291. cmTarget* target, const std::vector<std::string>& byproducts,
  4292. cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4293. {
  4294. for (std::string const& o : byproducts) {
  4295. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4296. this->UpdateOutputToSourceMap(o, target, bt, origin);
  4297. continue;
  4298. }
  4299. // This byproduct path has a generator expression. Evaluate it to
  4300. // register the byproducts for all configurations.
  4301. for (std::string const& b : this->ExpandCustomCommandOutputGenex(o, bt)) {
  4302. this->UpdateOutputToSourceMap(b, target, bt, cmCommandOrigin::Generator);
  4303. }
  4304. }
  4305. }
  4306. void cmLocalGenerator::AddSourceOutputs(
  4307. cmSourceFile* source, const std::vector<std::string>& outputs,
  4308. OutputRole role, cmListFileBacktrace const& bt, cmCommandOrigin origin)
  4309. {
  4310. for (std::string const& o : outputs) {
  4311. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  4312. this->UpdateOutputToSourceMap(o, source, role, bt, origin);
  4313. continue;
  4314. }
  4315. // This output path has a generator expression. Evaluate it to
  4316. // register the outputs for all configurations.
  4317. for (std::string const& out :
  4318. this->ExpandCustomCommandOutputGenex(o, bt)) {
  4319. this->UpdateOutputToSourceMap(out, source, role, bt,
  4320. cmCommandOrigin::Generator);
  4321. }
  4322. }
  4323. }
  4324. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& byproduct,
  4325. cmTarget* target,
  4326. cmListFileBacktrace const& bt,
  4327. cmCommandOrigin origin)
  4328. {
  4329. SourceEntry entry;
  4330. entry.Sources.Target = target;
  4331. auto pr = this->OutputToSource.emplace(byproduct, entry);
  4332. if (pr.second) {
  4333. CreateGeneratedSource(*this, byproduct, OutputRole::Byproduct, origin, bt);
  4334. } else {
  4335. SourceEntry& current = pr.first->second;
  4336. // Has the target already been set?
  4337. if (!current.Sources.Target) {
  4338. current.Sources.Target = target;
  4339. } else {
  4340. // Multiple custom commands/targets produce the same output (source file
  4341. // or target). See also comment in other UpdateOutputToSourceMap
  4342. // overload.
  4343. //
  4344. // TODO: Warn the user about this case.
  4345. }
  4346. }
  4347. }
  4348. void cmLocalGenerator::UpdateOutputToSourceMap(std::string const& output,
  4349. cmSourceFile* source,
  4350. OutputRole role,
  4351. cmListFileBacktrace const& bt,
  4352. cmCommandOrigin origin)
  4353. {
  4354. SourceEntry entry;
  4355. entry.Sources.Source = source;
  4356. entry.Sources.SourceIsByproduct = role == OutputRole::Byproduct;
  4357. auto pr = this->OutputToSource.emplace(output, entry);
  4358. if (pr.second) {
  4359. CreateGeneratedSource(*this, output, role, origin, bt);
  4360. } else {
  4361. SourceEntry& current = pr.first->second;
  4362. // Outputs take precedence over byproducts
  4363. if (!current.Sources.Source ||
  4364. (current.Sources.SourceIsByproduct && role == OutputRole::Primary)) {
  4365. current.Sources.Source = source;
  4366. current.Sources.SourceIsByproduct = false;
  4367. } else {
  4368. // Multiple custom commands produce the same output but may
  4369. // be attached to a different source file (MAIN_DEPENDENCY).
  4370. // LinearGetSourceFileWithOutput would return the first one,
  4371. // so keep the mapping for the first one.
  4372. //
  4373. // TODO: Warn the user about this case. However, the VS 8 generator
  4374. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  4375. // individual targets.
  4376. }
  4377. }
  4378. }
  4379. cmTarget* cmLocalGenerator::LinearGetTargetWithOutput(
  4380. const std::string& name) const
  4381. {
  4382. // We go through the ordered vector of targets to get reproducible results
  4383. // should multiple names match.
  4384. for (cmTarget* t : this->Makefile->GetOrderedTargets()) {
  4385. // Does the output of any command match the source file name?
  4386. if (AnyTargetCommandOutputMatches(name, t->GetPreBuildCommands())) {
  4387. return t;
  4388. }
  4389. if (AnyTargetCommandOutputMatches(name, t->GetPreLinkCommands())) {
  4390. return t;
  4391. }
  4392. if (AnyTargetCommandOutputMatches(name, t->GetPostBuildCommands())) {
  4393. return t;
  4394. }
  4395. }
  4396. return nullptr;
  4397. }
  4398. cmSourceFile* cmLocalGenerator::LinearGetSourceFileWithOutput(
  4399. const std::string& name, cmSourceOutputKind kind, bool& byproduct) const
  4400. {
  4401. // Outputs take precedence over byproducts.
  4402. byproduct = false;
  4403. cmSourceFile* fallback = nullptr;
  4404. // Look through all the source files that have custom commands and see if the
  4405. // custom command has the passed source file as an output.
  4406. for (const auto& src : this->Makefile->GetSourceFiles()) {
  4407. // Does this source file have a custom command?
  4408. if (src->GetCustomCommand()) {
  4409. // Does the output of the custom command match the source file name?
  4410. if (AnyOutputMatches(name, src->GetCustomCommand()->GetOutputs())) {
  4411. // Return the first matching output.
  4412. return src.get();
  4413. }
  4414. if (kind == cmSourceOutputKind::OutputOrByproduct) {
  4415. if (AnyOutputMatches(name, src->GetCustomCommand()->GetByproducts())) {
  4416. // Do not return the source yet as there might be a matching output.
  4417. fallback = src.get();
  4418. }
  4419. }
  4420. }
  4421. }
  4422. // Did we find a byproduct?
  4423. byproduct = fallback != nullptr;
  4424. return fallback;
  4425. }